Coverage Report

Created: 2026-11-12 06:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/opensc/src/libopensc/card-piv.c
Line
Count
Source
1
/*
2
 * card-piv.c: Support for PIV-II 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-2026  Douglas E. Engert <deengert@gmail.com>
7
 * Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com>
8
 * Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com>
9
 *
10
 * This library is free software; you can redistribute it and/or
11
 * modify it under the terms of the GNU Lesser General Public
12
 * License as published by the Free Software Foundation; either
13
 * version 2.1 of the License, or (at your option) any later version.
14
 *
15
 * This library is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18
 * Lesser General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Lesser General Public
21
 * License along with this library; if not, write to the Free Software
22
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23
 */
24
25
#ifdef HAVE_CONFIG_H
26
#include "config.h"
27
#endif
28
29
#include <ctype.h>
30
#include <fcntl.h>
31
#include <limits.h>
32
#include <stdlib.h>
33
#include <string.h>
34
35
#ifdef _WIN32
36
#include <io.h>
37
#else
38
#include <unistd.h>
39
#endif
40
41
#ifdef ENABLE_OPENSSL
42
/* openssl needed for card administration and SM */
43
#include <openssl/evp.h>
44
#include <openssl/pem.h>
45
#include <openssl/rand.h>
46
#include <openssl/sha.h>
47
#if !defined(OPENSSL_NO_EC)
48
#include <openssl/ec.h>
49
#endif
50
#endif
51
52
#include "common/compat_strlcat.h"
53
#include "common/compat_strlcpy.h"
54
#include "internal.h"
55
56
/* 800-73-4 SM and VCI need: ECC, SM and OpenSSL or LibreSSL */
57
#if defined(ENABLE_PIV_SM)
58
#include "compression.h"
59
#include <openssl/cmac.h>
60
#endif
61
62
#include "asn1.h"
63
#include "errors.h"
64
#include "cardctl.h"
65
#include "internal.h"
66
#include "simpletlv.h"
67
#include "ui/notify.h"
68
69
// clang-format off
70
71
enum {
72
  PIV_OBJ_CCC = 0,
73
  PIV_OBJ_CHUI,
74
  /*  PIV_OBJ_UCHUI is not in new with 800-73-2 */
75
  PIV_OBJ_X509_PIV_AUTH,
76
  PIV_OBJ_CHF,
77
  PIV_OBJ_PI,
78
  PIV_OBJ_CHFI,
79
  PIV_OBJ_X509_DS,
80
  PIV_OBJ_X509_KM,
81
  PIV_OBJ_X509_CARD_AUTH,
82
  PIV_OBJ_SEC_OBJ,
83
  PIV_OBJ_DISCOVERY,
84
  PIV_OBJ_HISTORY,
85
  PIV_OBJ_RETIRED_X509_1,
86
  PIV_OBJ_RETIRED_X509_2,
87
  PIV_OBJ_RETIRED_X509_3,
88
  PIV_OBJ_RETIRED_X509_4,
89
  PIV_OBJ_RETIRED_X509_5,
90
  PIV_OBJ_RETIRED_X509_6,
91
  PIV_OBJ_RETIRED_X509_7,
92
  PIV_OBJ_RETIRED_X509_8,
93
  PIV_OBJ_RETIRED_X509_9,
94
  PIV_OBJ_RETIRED_X509_10,
95
  PIV_OBJ_RETIRED_X509_11,
96
  PIV_OBJ_RETIRED_X509_12,
97
  PIV_OBJ_RETIRED_X509_13,
98
  PIV_OBJ_RETIRED_X509_14,
99
  PIV_OBJ_RETIRED_X509_15,
100
  PIV_OBJ_RETIRED_X509_16,
101
  PIV_OBJ_RETIRED_X509_17,
102
  PIV_OBJ_RETIRED_X509_18,
103
  PIV_OBJ_RETIRED_X509_19,
104
  PIV_OBJ_RETIRED_X509_20,
105
  PIV_OBJ_IRIS_IMAGE,
106
  PIV_OBJ_BITGT,
107
  PIV_OBJ_SM_CERT_SIGNER,
108
  PIV_OBJ_PCRDCS,
109
  PIV_OBJ_9B03,
110
  PIV_OBJ_9A06,
111
  PIV_OBJ_9C06,
112
  PIV_OBJ_9D06,
113
  PIV_OBJ_9E06,
114
  PIV_OBJ_8206,
115
  PIV_OBJ_8306,
116
  PIV_OBJ_8406,
117
  PIV_OBJ_8506,
118
  PIV_OBJ_8606,
119
  PIV_OBJ_8706,
120
  PIV_OBJ_8806,
121
  PIV_OBJ_8906,
122
  PIV_OBJ_8A06,
123
  PIV_OBJ_8B06,
124
  PIV_OBJ_8C06,
125
  PIV_OBJ_8D06,
126
  PIV_OBJ_8E06,
127
  PIV_OBJ_8F06,
128
  PIV_OBJ_9006,
129
  PIV_OBJ_9106,
130
  PIV_OBJ_9206,
131
  PIV_OBJ_9306,
132
  PIV_OBJ_9406,
133
  PIV_OBJ_9506,
134
  PIV_OBJ_LAST_ENUM
135
};
136
137
/*
138
 * Flags in the piv_obj_cache:
139
 * PIV_OBJ_CACHE_VALID means the data in the cache can be used.
140
 * It might have zero length indicating that the object was not found.
141
 * PIV_OBJ_CACHE_NOT_PRESENT means do not even try to read the object.
142
 * Either because the object did not parse or
143
 * these objects will only be present if the history object says
144
 * they are on the card, or the discovery or history object in not present.
145
 * If the file listed in the history object offCardCertURL was found,
146
 * its certs will be read into the cache and PIV_OBJ_CACHE_VALID set
147
 * and PIV_OBJ_CACHE_NOT_PRESENT unset.
148
 *
149
 */
150
151
49.7k
#define PIV_OBJ_CACHE_VALID   1
152
0
#define PIV_OBJ_CACHE_COMPRESSED  2
153
154k
#define PIV_OBJ_CACHE_NOT_PRESENT 8
154
155
typedef struct piv_obj_cache {
156
  u8* obj_data;
157
  size_t obj_len;
158
  u8* internal_obj_data; /* like a cert in the object */
159
  size_t internal_obj_len;
160
  int flags;
161
} piv_obj_cache_t;
162
163
enum {
164
  PIV_STATE_NORMAL = 0,
165
  PIV_STATE_MATCH,
166
  PIV_STATE_INIT
167
};
168
169
/* ccc_flags */
170
155
#define PIV_CCC_FOUND   0x00000001
171
439
#define PIV_CCC_F0_PIV    0x00000002
172
466
#define PIV_CCC_F0_CAC    0x00000004
173
247
#define PIV_CCC_F0_JAVA   0x00000008
174
1.70k
#define PIV_CCC_F3_CAC_PKI  0x00000010
175
176
1.62k
#define PIV_CCC_TAG_F0    0xF0
177
960
#define PIV_CCC_TAG_F3    0xF3
178
179
/* 800-73-4 Cipher Suite Table 14 */
180
#define PIV_CS_CS2    0x27
181
#define PIV_CS_CS7    0x2E
182
183
#ifdef ENABLE_PIV_SM
184
#ifdef USE_OPENSSL3_LIBCTX
185
#define PIV_LIBCTX card->ctx->ossl3ctx->libctx
186
#else
187
#define PIV_LIBCTX NULL
188
#endif
189
190
  /* Table 14 and other constants */
191
  typedef struct cipher_suite {
192
    u8 id; /* taken from AID "AC" tag */
193
    int field_length;
194
    int nid;     /* for OpenSSL curves */
195
    struct sc_object_id oid; /* for opensc */
196
    int p1;      /* for APDU */
197
    size_t Qlen; /* size of pubkey 04||x||y for all keys */
198
    size_t AuthCryptogramlen; /* both H and ICC must match */
199
    size_t Zlen; /* size of shared secret from ECDH */
200
    size_t otherinfolen; /* used in 4.1.6  Key Derivation */
201
202
    int o0len; /* first in otherinfo */
203
    u8 o0_char;
204
    size_t CBhlen;
205
    size_t T16Qehlen;
206
    size_t IDsicclen;
207
    size_t Nicclen;
208
    size_t CBicclen; /* last in otherinfo */
209
210
    int naeskeys; /* number of aes key generated */
211
    int aeskeylen; /* size of aes key bytes*/
212
    int kdf_hash_size; /* size of hash in bytes */
213
    EVP_MD *(*kdf_md)(void);
214
    const EVP_CIPHER *(*cipher_cbc)(void);
215
    const EVP_CIPHER *(*cipher_ecb)(void);
216
    char *cipher_cbc_name;
217
    char *cipher_ecb_name;
218
    char *curve_group;
219
  } cipher_suite_t;
220
221
#define PIV_CSS_SIZE 2
222
static cipher_suite_t css[PIV_CSS_SIZE] = {
223
    {PIV_CS_CS2, 256, NID_X9_62_prime256v1, {{1, 2, 840, 10045, 3, 1, 7, -1}},
224
    PIV_CS_CS2, 65, 16, 32, 61,
225
    4, 0x09, 1, 16, 8, 16, 1,
226
    4, 128/8, SHA256_DIGEST_LENGTH,
227
    (EVP_MD *(*)(void)) EVP_sha256,
228
    (const EVP_CIPHER *(*)(void)) EVP_aes_128_cbc,
229
    (const EVP_CIPHER *(*)(void)) EVP_aes_128_ecb,
230
    "aes-128-cbc", "aes-128-ecb",
231
    "prime256v1"},
232
233
    {PIV_CS_CS7, 384, NID_secp384r1, {{1, 3, 132, 0, 34, -1}},
234
    PIV_CS_CS7, 97, 16, 48, 69,
235
    4, 0x0D, 1, 16, 8, 24, 1,
236
    4, 256/8, SHA384_DIGEST_LENGTH,
237
    (EVP_MD *(*)(void)) EVP_sha384,
238
    (const EVP_CIPHER *(*)(void)) EVP_aes_256_cbc,
239
    (const EVP_CIPHER *(*)(void)) EVP_aes_256_ecb,
240
    "aes-256-cbc", "aes-256-ecb",
241
    "secp384r1"}
242
  };
243
244
/* 800-73-4  4.1.5 Card Verifiable Certificates */
245
typedef struct piv_cvc {
246
  sc_pkcs15_der_t der;          // Previous read der
247
  int cpi;            // Certificate profile indicator (0x80)
248
  char issuerID[8];         // Issuer Identification Number
249
  size_t issuerIDlen;         //  8 bytes of sha-1 or 16 byte for GUID
250
  u8  subjectID[16];          //  Subject Identifier (8) or GUID (16)  == CHUI
251
  size_t subjectIDlen;          //  8 bytes of sha-1 or 16 byte for GUID
252
  struct sc_object_id pubKeyOID;        // Public key algorithm object identifier
253
  u8 *publicPoint;          // Public point for ECC
254
  size_t publicPointlen;
255
  int roleID;           // Role Identifier 0x00 or 0x12
256
  u8 *body;           // signed part of CVC in DER
257
  size_t bodylen;
258
  struct sc_object_id  signatureAlgOID;     // Signature Algroithm Identifier
259
  u8 *signature;            // Certificate signature DER
260
  size_t signaturelen;
261
} piv_cvc_t;
262
263
#define PIV_SM_MAX_FIELD_LENGTH  384
264
#define PIV_SM_MAX_MD_LENGTH  SHA384_DIGEST_LENGTH
265
266
#define PIV_SM_FLAGS_SM_CERT_SIGNER_VERIFIED  0x000000001lu
267
#define PIV_SM_FLAGS_SM_CVC_VERIFIED    0X000000002lu
268
#define PIV_SM_FLAGS_SM_IN_CVC_VERIFIED   0x000000004lu
269
#define PIV_SM_FLAGS_SM_CERT_SIGNER_PRESENT 0x000000010lu
270
#define PIV_SM_FLAGS_SM_CVC_PRESENT   0X000000020lu
271
#define PIV_SM_FLAGS_SM_IN_CVC_PRESENT    0x000000040lu
272
#define PIV_SM_FLAGS_SM_IS_ACTIVE   0x000000080lu /* SM has been started */
273
  /* if card supports SP800-73-4 SM: */
274
#define PIV_SM_FLAGS_NEVER      0x000000100lu /* Don't use SM even if card support it */
275
                /* Default is use if card supports it */
276
                /* will use VCI if card supports it for contactless */
277
#define PIV_SM_FLAGS_ALWAYS     0x000000200lu /* Use SM or quit, VCI requires SM */
278
#define PIV_SM_FLAGS_DEFER_OPEN     0x000001000lu /* call sm_open from reader_lock_obtained */
279
#define PIV_SM_VCI_ACTIVE     0x000002000lu   /* VCI is active */
280
#define PIV_SM_GET_DATA_IN_CLEAR    0x000004000lu /* OK to do this GET DATA in the clear */
281
282
typedef struct piv_sm_session {
283
  /* set by piv_sm_open */
284
  int aes_size; /* 128 or 256 */
285
286
  u8 SKcfrm[32];
287
  u8 SKmac[32];
288
  u8 SKenc[32];  /* keys are either AES 128 or AES 256 */
289
  u8 SKrmac[32];
290
  u8 enc_counter[16];
291
  u8 enc_counter_last[16];
292
293
  u8 resp_enc_counter[16];
294
  u8 C_MCV[16];
295
  u8 C_MCV_last[16];
296
  u8 R_MCV[16];
297
  u8 R_MCV_last[16];
298
} piv_sm_session_t;
299
300
#define C_ASN1_PIV_CVC_PUBKEY_SIZE 3
301
  /* ECC key only */
302
static const struct sc_asn1_entry c_asn1_piv_cvc_pubkey[C_ASN1_PIV_CVC_PUBKEY_SIZE] = {
303
  { "publicKeyOID", SC_ASN1_OBJECT, SC_ASN1_UNI | SC_ASN1_OBJECT, 0, NULL, NULL },
304
  { "publicPoint", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 6, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
305
  { NULL, 0, 0, 0, NULL, NULL }
306
};
307
308
#define C_ASN1_PIV_CVC_DSOBJ_SIZE 2
309
static const struct sc_asn1_entry c_asn1_piv_cvc_dsobj[C_ASN1_PIV_CVC_DSOBJ_SIZE] = {
310
  { "DigitalSignature", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_TAG_SEQUENCE, 0, NULL, NULL },
311
  { NULL, 0, 0, 0, NULL, NULL }
312
};
313
314
#define C_ASN1_PIV_CVC_DSSIG_SIZE 3
315
static const struct sc_asn1_entry c_asn1_piv_cvc_dssig[C_ASN1_PIV_CVC_DSSIG_SIZE] = {
316
  { "signatureAlgorithmID", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_TAG_SEQUENCE, 0, NULL, NULL },
317
  { "signatureValue", SC_ASN1_BIT_STRING_NI, SC_ASN1_TAG_BIT_STRING, SC_ASN1_ALLOC, NULL, NULL },
318
  { NULL, 0, 0, 0, NULL, NULL }
319
};
320
321
#define C_ASN1_PIV_CVC_ALG_ID_SIZE 3
322
static const struct sc_asn1_entry c_asn1_piv_cvc_alg_id[C_ASN1_PIV_CVC_ALG_ID_SIZE] = {
323
  { "signatureAlgorithmOID", SC_ASN1_OBJECT, SC_ASN1_UNI | SC_ASN1_OBJECT, 0, NULL, NULL },
324
  { "nullParam",  SC_ASN1_NULL, SC_ASN1_UNI | SC_ASN1_TAG_NULL, SC_ASN1_OPTIONAL, NULL, NULL },
325
  { NULL, 0, 0, 0, NULL, NULL }
326
};
327
328
#define C_ASN1_PIV_CVC_BODY_SIZE 7
329
static const struct sc_asn1_entry c_asn1_piv_cvc_body[C_ASN1_PIV_CVC_BODY_SIZE] = {
330
  { "certificateProfileIdentifier", SC_ASN1_INTEGER, SC_ASN1_APP | 0x1F29, 0, NULL, NULL },
331
  { "Issuer ID Number", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 2, 0, NULL, NULL },
332
  { "Subject Identifier", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F20, 0, NULL, NULL },
333
  { "publicKey", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F49, 0, NULL, NULL },
334
  { "roleIdentifier", SC_ASN1_CALLBACK, SC_ASN1_APP | 0x1F4C, 0, NULL, NULL },
335
  /* signature is over the above 5 entries  treat roleIdentifier special to get end */
336
  { "DSignatureObject", SC_ASN1_STRUCT, SC_ASN1_APP | 0x1F37, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, NULL, NULL },
337
  { NULL, 0, 0, 0, NULL, NULL }
338
};
339
340
341
#define C_ASN1_PIV_CVC_SIZE 2
342
static const struct sc_asn1_entry c_asn1_piv_cvc[C_ASN1_PIV_CVC_SIZE] = {
343
  { "CVC certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL },
344
  { NULL, 0, 0, 0, NULL, NULL }
345
};
346
347
#define C_ASN1_PIV_SM_RESPONSE_SIZE 4
348
static const struct sc_asn1_entry c_asn1_sm_response[C_ASN1_PIV_SM_RESPONSE_SIZE] = {
349
  { "encryptedData",      SC_ASN1_CALLBACK,   SC_ASN1_CTX | 7,        SC_ASN1_OPTIONAL,       NULL, NULL },
350
  { "statusWord",         SC_ASN1_CALLBACK,   SC_ASN1_CTX | 0x19,     0,                      NULL, NULL },
351
  { "mac",                SC_ASN1_CALLBACK,   SC_ASN1_CTX | 0x0E,     0,                      NULL, NULL },
352
  { NULL, 0, 0, 0, NULL, NULL }
353
};
354
355
/*
356
 * SW internal apdu response table.
357
 *
358
 * Override APDU response error codes from iso7816.c to allow
359
 * handling of SM specific error
360
 */
361
static const struct sc_card_error piv_sm_errors[] = {
362
  {0x6882, SC_ERROR_SM, "SM not supported"},
363
  {0x6982, SC_ERROR_SM_NO_SESSION_KEYS, "SM Security status not satisfied"}, /* no session established */
364
  {0x6987, SC_ERROR_SM, "Expected SM Data Object missing"},
365
  {0x6988, SC_ERROR_SM_INVALID_SESSION_KEY, "SM Data Object incorrect"}, /* other process interference */
366
  {0, 0, NULL}
367
};
368
#endif /* ENABLE_PIV_SM */
369
370
/* 800-73-4 3.3.2 Discovery Object - PIN Usage Policy */
371
216
#define PIV_PP_PIN    0x00004000u
372
216
#define PIV_PP_GLOBAL   0x00002000u
373
#define PIV_PP_OCC    0x00001000u
374
#define PIV_PP_VCI_IMPL   0x00000800u
375
#define PIV_PP_VCI_WITHOUT_PC 0x00000400u
376
#define PIV_PP_PIV_PRIMARY  0x00000010u
377
3
#define PIV_PP_GLOBAL_PRIMARY 0x00000020u
378
379
/* init_flags */
380
5.76k
#define PIV_INIT_AID_PARSED     0x00000001u
381
1.42k
#define PIV_INIT_AID_AC_SM      0x00000002u
382
2.43k
#define PIV_INIT_DISCOVERY_PARSED   0x00000004u
383
108
#define PIV_INIT_DISCOVERY_PP     0x00000008u
384
89.8k
#define PIV_INIT_IN_READER_LOCK_OBTAINED  0x00000010u
385
1.59k
#define PIV_INIT_CONTACTLESS      0x00000020u
386
387
#define PIV_PAIRING_CODE_LEN   8
388
389
131k
#define PIV_NUM_YK_SLOT_INFO 26
390
391
typedef struct yk_slot_info_st {
392
  u8 slot;
393
  u8 invalid;
394
  u8 policy;
395
  u8 touch;
396
  u8 algorithm;
397
  struct sc_lv_data pubkey;
398
} yk_slot_info_t;
399
400
typedef struct piv_private_data {
401
  struct sc_lv_data aid_der; /* previous aid response to compare */
402
  int enumtag;
403
  int max_object_size; /* use setable option. In case objects get bigger */
404
  int selected_obj; /* The index into the piv_objects last selected */
405
  int return_only_cert; /* return the cert from the object */
406
  int rwb_state; /* first time -1, 0, in middle, 1 at eof */
407
  int operation; /* saved from set_security_env */
408
  unsigned long algorithm; /* saved from set_security_env */
409
  int key_ref; /* saved from set_security_env and */
410
  int alg_id;  /* used in decrypt, signature, derive */
411
  unsigned int alg_ids; /* from AID response, NIST required, card version */
412
  unsigned char * al_label; /* from Select AID Application Label */
413
  int al_labellen;
414
  int key_size; /*  RSA: modulus_bits EC: field_length in bits */
415
  u8* w_buf;   /* write_binary buffer */
416
  size_t w_buf_len; /* length of w_buff */
417
  piv_obj_cache_t obj_cache[PIV_OBJ_LAST_ENUM];
418
  int keysWithOnCardCerts;
419
  int keysWithOffCardCerts;
420
  char * offCardCertURL;
421
  int pin_preference; /* set from Discovery object */
422
  int logged_in;
423
  int pstate;
424
  int pin_cmd_verify;
425
  int context_specific;
426
  unsigned int pin_cmd_verify_sw1;
427
  unsigned int pin_cmd_verify_sw2;
428
  int tries_left; /* SC_PIN_CMD_GET_INFO tries_left from last */
429
  unsigned int card_issues; /* card_issues flags for this card */
430
  int object_test_verify; /* Can test this object to set verification state of card */
431
  int yubico_version; /* 3 byte version number of NEO or Yubikey4  as integer */
432
  yk_slot_info_t yk_slot_info[PIV_NUM_YK_SLOT_INFO];
433
  unsigned int ccc_flags;     /* From  CCC indicate if CAC card */
434
  unsigned int pin_policy; /* from discovery */
435
  unsigned int init_flags;
436
  u8  csID; /* 800-73-4 Cipher Suite ID 0x27 or 0x2E */
437
#ifdef ENABLE_PIV_SM
438
  cipher_suite_t *cs; /* active cipher_suite */
439
  piv_cvc_t sm_cvc;  /* 800-73-4:  SM CVC Table 15 */
440
  piv_cvc_t sm_in_cvc; /* Intermediate CVC Table 16 */
441
  unsigned long  sm_flags;
442
  unsigned char pairing_code[PIV_PAIRING_CODE_LEN]; /* 8 ASCII digits */
443
  piv_sm_session_t sm_session;
444
#endif /* ENABLE_PIV_SM */
445
} piv_private_data_t;
446
447
722k
#define PIV_DATA(card) ((piv_private_data_t*)card->drv_data)
448
449
struct piv_aid {
450
  int enumtag;
451
  size_t len_short; /* min length without version */
452
  size_t len_long;  /* With version and other stuff */
453
  u8 *value;
454
};
455
456
/*
457
 * The Generic AID entry should be the "A0 00 00 03 08 00 00 10 00 "
458
 * NIST published 800-73 on 10/6/2005
459
 * 800-73-1 March 2006 included Errata
460
 * 800-73-2 Part 1 implies  version is  "02 00"
461
 * i.e. "A0 00 00 03 08 00 00 01 00 02 00".
462
 * but we don't need the version number. But could get it from the PIX.
463
 * Discovery object was added.
464
 *
465
 * 800-73-3 Part 1 now refers to "01 00" i.e. going back to 800-73-1.
466
 * The main differences between 73-2, and 73-3 are the addition of the
467
 * key History object, certs and keys and Iris objects.
468
 * These can be discovered using GET DATA
469
470
 * 800-73-4 Has many changes, including optional Secure Messaging,
471
 * optional Virtual Contact Interface and pairing code.
472
 */
473
474
/* ATRs of cards known to have PIV applet. But must still be tested for a PIV applet */
475
/* Yubico, NitroKey, Token2 are identified by ATR historic bytes */
476
/* PivApplet does not provide ATR historic bytes */
477
478
static const struct sc_atr_table piv_atrs[] = {
479
  /* CAC cards with PIV from: CAC-utilziation-and-variation-matrix-v2.03-20May2016.doc */
480
  /*
481
   * https://www.cac.mil/Common-Access-Card/Developer-Resources/
482
   * https://www.cac.mil/Portals/53/Documents/DoD%20Token%20utilziation%20and%20variation%20matrix%20v2_06_17October2019.docx?ver=2019-10-18-102519-120
483
   */
484
  /* Oberthur Card Systems (PIV Endpoint) with PIV endpoint applet and PIV auth cert OBSOLETE */
485
  { "3B:DB:96:00:80:1F:03:00:31:C0:64:77:E3:03:00:82:90:00:C1", NULL, NULL, SC_CARD_TYPE_PIV_II_OBERTHUR, 0, NULL },
486
487
  /* Gemalto (PIV Endpoint) with PIV endpoint applet and PIV auth cert OBSOLETE */
488
  { "3B 7D 96 00 00 80 31 80 65 B0 83 11 13 AC 83 00 90 00", NULL, NULL, SC_CARD_TYPE_PIV_II_GEMALTO, 0, NULL },
489
490
  /* Gemalto (PIV Endpoint) 2 entries  2016, 2019 */
491
  { "3B:7D:96:00:00:80:31:80:65:B0:83:11:17:D6:83:00:90:00", NULL, NULL, SC_CARD_TYPE_PIV_II_GEMALTO, 0, NULL },
492
493
  /* Oberthur Card System (PIV Endpoint)  2 entries 2016, 2019 */
494
  { "3B:DB:96:00:80:1F:03:00:31:C0:64:B0:F3:10:00:07:90:00:80", NULL, NULL, SC_CARD_TYPE_PIV_II_OBERTHUR, 0, NULL },
495
  /* Oberthur Card System  with LCS 0F - Some VA cards have Terminated state */
496
  { "3B:DB:96:00:80:1F:03:00:31:C0:64:B0:F3:10:00:0F:90:00:88", NULL, NULL, SC_CARD_TYPE_PIV_II_OBERTHUR, 0, NULL },
497
498
  /* Giesecke & Devrient (PIV Endpoint)  2 entries 2016, 2019 */
499
  { "3B:7A:18:00:00:73:66:74:65:20:63:64:31:34:34", NULL, NULL, SC_CARD_TYPE_PIV_II_GI_DE_DUAL_CAC, 0, NULL },
500
  /* Giesecke & Devrient (CAC PIV Endpoint) 2019 */
501
  { "3B:F9:18:00:00:00:53:43:45:37:20:03:00:20:46", NULL, NULL, SC_CARD_TYPE_PIV_II_GI_DE_DUAL_CAC, 0, NULL },
502
  /* Giesecke & Devrient SCE7 (PIV-only) (DoD Alternate Token G+D Sm@rtCafe Expert v7.0 144K DI 2025) */
503
  { "3B:F9:96:00:00:80:31:FE:45:53:43:45:37:20:0F:00:20:46:4E", NULL, NULL, SC_CARD_TYPE_PIV_II_GI_DE, 0, NULL },
504
505
  /* IDEMIA (new name for Oberthur) (DoD Alternate Token IDEMIA Cosmo V8.0 2025 */
506
  { "3B:D8:18:00:80:B1:FE:45:1F:07:80:31:C1:64:08:06:92:0F:D5", NULL, NULL, SC_CARD_TYPE_PIV_II_OBERTHUR, 0, NULL },
507
  { "3b:86:80:01:80:31:c1:52:41:1a:7e", NULL, NULL, SC_CARD_TYPE_PIV_II_OBERTHUR, 0, NULL }, /* contactless */
508
509
  /* Following PIVKEY entries are from Windows registry provided by gw@taglio.com 2022-09-05 */
510
  /* PIVKEY PIVKey Feitian (02) */
511
  { "3b:9f:95:81:31:fe:9f:00:66:46:53:05:10:00:11:71:df:00:00:00:00:00:02", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
512
  /* PIVKey Feitian (7C)  aka C910 contactless */
513
  { "3b:8c:80:01:90:67:46:4a:00:64:16:06:f2:72:7e:00:7c", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
514
  /*PIVKey Feitian (E0)  aka C910 */
515
  { "3b:fc:18:00:00:81:31:80:45:90:67:46:4a:00:64:16:06:f2:72:7e:00:e0", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
516
  /* PIVKey Feitian (FE)  aka PIVKEY T600 token and T800  on Feitian eJAVA */
517
  { "3b:fc:18:00:00:81:31:80:45:90:67:46:4a:00:64:2d:70:c1:72:fe:e0:fe", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
518
  /* PIVKey JCOP241 (AD) */
519
  { "3b:f9:13:00:00:81:31:fe:45:53:50:49:56:4b:45:59:37:30:ad", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
520
  /* PIVKey JCOP242R2 (16) */
521
  { "3b:88:80:01:50:49:56:4b:45:59:37:30:16", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
522
  /* PIVKey JCOP242R2 (5E) */
523
  { "3b:88:80:01:4a:43:4f:50:76:32:34:31:5e", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
524
  /* PIVKey JCOP242R2 (B7) */
525
  { "3b:f8:13:00:00:81:31:fe:45:4a:43:4f:50:76:32:34:31:b7", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
526
  /* PIVKey JCOP3 (67) */
527
  { "3b:88:80:01:46:49:44:45:53:4d:4f:31:67", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
528
  /* PIVKey JCOP3 (8E) */
529
  { "3b:f8:13:00:00:81:31:fe:45:46:49:44:45:53:4d:4f:31:8e", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
530
  /* PIVKey JCOP31 (57) */
531
  { "3b:f9:18:00:ff:81:31:fe:45:4a:43:4f:50:33:31:56:32:32:57", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
532
  /* PIVKey NXP JCOP (03) */
533
  { "3b:8a:80:01:01:50:49:56:4b:45:59:37:30:16:03", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
534
  /* PIVKey NXP JCOP (FF)  aka CP70 */
535
  { "3b:f8:13:00:00:81:31:fe:45:50:49:56:4b:45:59:37:30:ff", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
536
  /* PIVKey SLE78 (3B) */
537
  { "3b:8d:80:01:53:4c:4a:35:32:47:44:4c:31:32:38:43:52:3b", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
538
  /* PIVKey SLE78 (6D) */
539
  { "3b:88:80:01:00:00:00:11:77:81:83:00:6d", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
540
  /* PIVKey SLE78 (28) aka C980 */
541
  { "3b:f9:96:00:00:81:31:fe:45:53:50:49:56:4b:45:59:37:30:28", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
542
  /* PIVKey SLE78 (44) aka C980 contactless */
543
  { "3b:89:80:01:53:50:49:56:4b:45:59:37:30:44", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
544
  /* PIVKey SLE78 (57B) */
545
  { "3b:fd:96:00:00:81:31:fe:45:53:4c:4a:35:32:47:44:4c:31:32:38:43:52:57", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
546
  /* This ATR is too generic. It will be accepted if Application Label in AID response matches */
547
  /* Which looks like there is no Application Label in AID response of these cards */
548
  /* PivApplet (at least when run in virtual machine) uses the same ATR */
549
  /* PIVKey uTrust (01) ISO 14443 Type B without historical bytes */
550
  /* { "3b:80:80:01:01", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL }, */
551
552
  /* PIVKey uTrust (73) */
553
  { "3b:96:11:81:21:75:75:54:72:75:73:74:73", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
554
  /* PIVKey uTrust FIDO2 (73) */
555
  { "3b:96:11:81:21:75:75:54:72:75:73:74:73", NULL, NULL, SC_CARD_TYPE_PIV_II_PIVKEY, 0, NULL },
556
557
  /* Swissbit iShield Key Pro with PIV endpoint applet */
558
  { "3b:97:11:81:21:75:69:53:68:69:65:6c:64:05", NULL, NULL, SC_CARD_TYPE_PIV_II_SWISSBIT, 0, NULL },
559
560
  /* ID-One PIV 2.4.1 on Cosmo V8.1 NIST sp800-73-4 with Secure Messaging and VCI  2020 */
561
  { "3b:d6:96:00:81:b1:fe:45:1f:87:80:31:c1:52:41:1a:2a", NULL, NULL, SC_CARD_TYPE_PIV_II_800_73_4, 0, NULL },
562
  { "3b:d6:97:00:81:b1:fe:45:1f:87:80:31:c1:52:41:12:23",
563
    "ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:00:00", NULL, SC_CARD_TYPE_PIV_II_800_73_4, 0, NULL },
564
  { "3b:86:80:01:80:31:c1:52:41:12:76", NULL, NULL, SC_CARD_TYPE_PIV_II_800_73_4, 0, NULL }, /* contactless */
565
566
  { NULL, NULL, NULL, 0, 0, NULL }
567
};
568
569
static struct piv_supported_ec_curves {
570
  struct sc_object_id oid;
571
  size_t size;
572
  unsigned int key_type;
573
} ec_curves[] = {
574
    {{{1, 2, 840, 10045, 3, 1, 7, -1}}, 256, SC_ALGORITHM_EC  }, /* secp256r1, nistp256, prime256v1, ansiX9p256r1 */
575
    {{{1, 3, 132, 0, 34, -1}},     384, SC_ALGORITHM_EC    }, /* secp384r1, nistp384, prime384v1, ansiX9p384r1 */
576
    {{{1, 3, 101, 112, -1}},     255, SC_ALGORITHM_EDDSA }, /* RFC8410 OID equivalent to ed25519 */
577
    {{{1, 3, 101, 110, -1}},     255, SC_ALGORITHM_XEDDSA}, /* RFC8410 OID equivalent to curve25519 */
578
    {{{-1}},          0,   0         }  /* This entry must not be touched. */
579
};
580
581
/* all cards must respond to entry 0, some may return different PIX which will accept */
582
static struct piv_aid piv_aids[] = {
583
  {SC_CARD_TYPE_PIV_II_GENERIC, /* Not really card type but what PIV AID is supported */
584
     9, 9, (u8 *) "\xA0\x00\x00\x03\x08\x00\x00\x10\x00" },
585
  {SC_CARD_TYPE_PIV_II_GI_DE, /* bug in some G&D cards in response to select aid */
586
     9, 9, (u8 *) "\xA0\x00\x00\x03\x08\x00\x10\x00\x01" },
587
  {0,  9, 0, NULL }
588
};
589
590
/* card_issues - bugs in PIV implementations requires special handling */
591
103k
#define CI_VERIFY_630X          0x00000001U /* VERIFY tries left returns 630X rather then 63CX */
592
483
#define CI_VERIFY_LC0_FAIL        0x00000002U /* VERIFY Lc=0 never returns 90 00 if PIN not needed */
593
              /* will also test after first PIN verify if protected object can be used instead */
594
2.18k
#define CI_NO_RANDOM          0x00000004U /* can not use Challenge to get random data or no 9B key */
595
0
#define CI_CANT_USE_GETDATA_FOR_STATE     0x00000008U /* No object to test verification inplace of VERIFY Lc=0 */
596
368
#define CI_LEAKS_FILE_NOT_FOUND       0x00000010U /* GET DATA of empty object returns 6A 82 even if PIN not verified */
597
47.5k
#define CI_DISCOVERY_USELESS        0x00000020U /* Discovery can not be used to query active AID invalid or no data returned */
598
43.9k
#define CI_PIV_AID_LOSE_STATE       0x00000040U /* PIV AID can lose the login state run with out it*/
599
600
424
#define CI_OTHER_AID_LOSE_STATE       0x00000100U /* Other drivers match routines may reset our security state and lose AID!!! */
601
301
#define CI_NFC_EXPOSE_TOO_MUCH        0x00000200U /* PIN, crypto and objects exposed over NFS in violation of 800-73-3 */
602
603
8.37k
#define CI_NO_EC384         0x00000400U /* does not have EC 384 */
604
2.01k
#define CI_NO_EC          0x00000800U /* No EC at all */
605
1
#define CI_ENFORCES_EC_HASH_EQ_KEYSIZE      0x00001000U /* Applet enforces hash size == EC field size for ECDSA. Windows issue */
606
607
/* PIV and PIV like cards are know to support these asymmetric algorithm identifiers used in alg_ids */
608
6.05k
#define AI_RSA_1024         0x00000001U
609
6.05k
#define AI_RSA_2048         0x00000002U
610
6.05k
#define AI_RSA_3072         0x00000004U
611
2.04k
#define AI_RSA_4096         0x00000008U
612
4.03k
#define AI_EC_256         0x00000100U
613
4.03k
#define AI_EC_384         0x00000200U
614
8.09k
#define AI_25519          0x00100000U
615
8.06k
#define AI_X25519         0x00200000U
616
/* NIST  cards have or do support these (non SM) algorithm identifiers */
617
4.03k
#define AI_NIST (AI_RSA_1024 | AI_RSA_2048 | AI_RSA_3072 | AI_EC_256 | AI_EC_384)
618
619
static struct {
620
  unsigned long ai_flag;
621
  unsigned char ai_id;
622
  unsigned long ai_sc_type;
623
  int ai_bits;
624
} ai_map[] = {
625
    { AI_RSA_3072, 0x05, SC_ALGORITHM_RSA, 3072 },
626
    { AI_RSA_1024, 0x06, SC_ALGORITHM_RSA, 1024 },
627
    { AI_RSA_2048, 0x07, SC_ALGORITHM_RSA, 2048 },
628
    { AI_RSA_4096, 0x16, SC_ALGORITHM_RSA,4096 },
629
    { AI_EC_256, 0x11, SC_ALGORITHM_EC, 256 },
630
    { AI_EC_384, 0x14, SC_ALGORITHM_EC, 384 },
631
    { AI_25519, 0xE0, SC_ALGORITHM_EDDSA, 255 },
632
    { AI_X25519, 0xE1, SC_ALGORITHM_XEDDSA, 255 },
633
    { 0, 0, 0, 0 }
634
  };
635
636
/* Application Label from select AID response where ATR can not be matched */
637
static struct {
638
  int al_type;
639
  unsigned char * al_label;
640
  int al_labellen;
641
} al_map[] = {
642
    { SC_CARD_TYPE_PIV_II_PIVAPPLET, (u8 *)"PivApplet v", 11 },
643
    { SC_CARD_TYPE_PIV_II_OPENFIPS201, (u8 *)"OpenFIPS201", 11 },
644
    { 0, NULL, 0 }
645
  };
646
647
/*
648
 * Flags in the piv_object:
649
 * PIV_OBJECT_NOT_PRESENT: the presents of the object is
650
 * indicated by the History object.
651
 */
652
653
0
#define PIV_OBJECT_TYPE_CERT    0x01
654
0
#define PIV_OBJECT_TYPE_PUBKEY    0x02
655
292k
#define PIV_OBJECT_NOT_PRESENT    0x04
656
#define PIV_OBJECT_TYPE_CVC   0x08 /* is in cert object */
657
#define PIV_OBJECT_NEEDS_PIN    0x10 /* On both contact and contactless */
658
#define PIV_OBJECT_NEEDS_VCI    0x20 /* NIST sp800-73-4 Requires VCI on contactless and card enforces this. */
659
               /* But also See CI_NFC_EXPOSE_TOO_MUCH for non approved PIV-like cards */
660
661
struct piv_object {
662
  int enumtag;
663
  const char * name;
664
  unsigned int resp_tag;
665
  const char * oidstring;
666
  size_t tag_len;
667
  u8  tag_value[3];
668
  u8  containerid[2]; /* will use as relative paths for simulation */
669
  int flags;              /* object has some internal object like a cert */
670
};
671
672
/* Must be in order, and one per enumerated PIV_OBJ */
673
static const struct piv_object piv_objects[] = {
674
  { PIV_OBJ_CCC, "Card Capability Container",
675
      SC_ASN1_APP | 0x13,
676
      "2.16.840.1.101.3.7.1.219.0", 3, {0x5F, 0xC1, 0x07}, {0xDB, 0x00}, PIV_OBJECT_NEEDS_VCI},
677
  { PIV_OBJ_CHUI, "Card Holder Unique Identifier",
678
      SC_ASN1_APP | 0x13,
679
      "2.16.840.1.101.3.7.2.48.0", 3, {0x5F, 0xC1, 0x02}, {0x30, 0x00}, 0},
680
  { PIV_OBJ_X509_PIV_AUTH, "X.509 Certificate for PIV Authentication",
681
      SC_ASN1_APP | 0x13,
682
      "2.16.840.1.101.3.7.2.1.1", 3, {0x5F, 0xC1, 0x05}, {0x01, 0x01}, PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI} ,
683
  { PIV_OBJ_CHF, "Card Holder Fingerprints",
684
      SC_ASN1_APP | 0x13,
685
      "2.16.840.1.101.3.7.2.96.16", 3, {0x5F, 0xC1, 0x03}, {0x60, 0x10}, PIV_OBJECT_NEEDS_PIN | PIV_OBJECT_NEEDS_VCI},
686
  { PIV_OBJ_PI, "Printed Information",
687
      SC_ASN1_APP | 0x13,
688
      "2.16.840.1.101.3.7.2.48.1", 3, {0x5F, 0xC1, 0x09}, {0x30, 0x01}, PIV_OBJECT_NEEDS_PIN | PIV_OBJECT_NEEDS_VCI},
689
  { PIV_OBJ_CHFI, "Cardholder Facial Images",
690
      SC_ASN1_APP | 0x13,
691
      "2.16.840.1.101.3.7.2.96.48", 3, {0x5F, 0xC1, 0x08}, {0x60, 0x30}, PIV_OBJECT_NEEDS_PIN | PIV_OBJECT_NEEDS_VCI},
692
  { PIV_OBJ_X509_DS, "X.509 Certificate for Digital Signature",
693
      SC_ASN1_APP | 0x13,
694
      "2.16.840.1.101.3.7.2.1.0", 3, {0x5F, 0xC1, 0x0A}, {0x01, 0x00}, PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
695
  { PIV_OBJ_X509_KM, "X.509 Certificate for Key Management",
696
      SC_ASN1_APP | 0x13,
697
      "2.16.840.1.101.3.7.2.1.2", 3, {0x5F, 0xC1, 0x0B}, {0x01, 0x02}, PIV_OBJECT_TYPE_CERT},
698
  { PIV_OBJ_X509_CARD_AUTH, "X.509 Certificate for Card Authentication",
699
      SC_ASN1_APP | 0x13,
700
      "2.16.840.1.101.3.7.2.5.0", 3, {0x5F, 0xC1, 0x01}, {0x05, 0x00}, PIV_OBJECT_TYPE_CERT},
701
  { PIV_OBJ_SEC_OBJ, "Security Object",
702
      SC_ASN1_APP | 0x13,
703
      "2.16.840.1.101.3.7.2.144.0", 3, {0x5F, 0xC1, 0x06}, {0x90, 0x00}, PIV_OBJECT_NEEDS_VCI},
704
  { PIV_OBJ_DISCOVERY, "Discovery Object",
705
      SC_ASN1_APP | SC_ASN1_CONS | 0x1E,
706
      "2.16.840.1.101.3.7.2.96.80", 1, {0x7E}, {0x60, 0x50}, 0},
707
  { PIV_OBJ_HISTORY, "Key History Object",
708
      SC_ASN1_APP | 0x13,
709
      "2.16.840.1.101.3.7.2.96.96", 3, {0x5F, 0xC1, 0x0C}, {0x60, 0x60}, PIV_OBJECT_NEEDS_VCI},
710
711
/* 800-73-3, 21 new objects, 20 history certificates */
712
  { PIV_OBJ_RETIRED_X509_1, "Retired X.509 Certificate for Key Management 1",
713
      SC_ASN1_APP | 0x13,
714
      "2.16.840.1.101.3.7.2.16.1", 3, {0x5F, 0xC1, 0x0D}, {0x10, 0x01},
715
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
716
  { PIV_OBJ_RETIRED_X509_2, "Retired X.509 Certificate for Key Management 2",
717
      SC_ASN1_APP | 0x13,
718
      "2.16.840.1.101.3.7.2.16.2", 3, {0x5F, 0xC1, 0x0E}, {0x10, 0x02},
719
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
720
  { PIV_OBJ_RETIRED_X509_3, "Retired X.509 Certificate for Key Management 3",
721
      SC_ASN1_APP | 0x13,
722
      "2.16.840.1.101.3.7.2.16.3", 3, {0x5F, 0xC1, 0x0F}, {0x10, 0x03},
723
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
724
  { PIV_OBJ_RETIRED_X509_4, "Retired X.509 Certificate for Key Management 4",
725
      SC_ASN1_APP | 0x13,
726
      "2.16.840.1.101.3.7.2.16.4", 3, {0x5F, 0xC1, 0x10}, {0x10, 0x04},
727
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
728
  { PIV_OBJ_RETIRED_X509_5, "Retired X.509 Certificate for Key Management 5",
729
      SC_ASN1_APP | 0x13,
730
      "2.16.840.1.101.3.7.2.16.5", 3, {0x5F, 0xC1, 0x11}, {0x10, 0x05},
731
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
732
  { PIV_OBJ_RETIRED_X509_6, "Retired X.509 Certificate for Key Management 6",
733
      SC_ASN1_APP | 0x13,
734
      "2.16.840.1.101.3.7.2.16.6", 3, {0x5F, 0xC1, 0x12}, {0x10, 0x06},
735
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
736
  { PIV_OBJ_RETIRED_X509_7, "Retired X.509 Certificate for Key Management 7",
737
      SC_ASN1_APP | 0x13,
738
      "2.16.840.1.101.3.7.2.16.7", 3, {0x5F, 0xC1, 0x13}, {0x10, 0x07},
739
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
740
  { PIV_OBJ_RETIRED_X509_8, "Retired X.509 Certificate for Key Management 8",
741
      SC_ASN1_APP | 0x13,
742
      "2.16.840.1.101.3.7.2.16.8", 3, {0x5F, 0xC1, 0x14}, {0x10, 0x08},
743
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
744
  { PIV_OBJ_RETIRED_X509_9, "Retired X.509 Certificate for Key Management 9",
745
      SC_ASN1_APP | 0x13,
746
      "2.16.840.1.101.3.7.2.16.9", 3, {0x5F, 0xC1, 0x15}, {0x10, 0x09},
747
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
748
  { PIV_OBJ_RETIRED_X509_10, "Retired X.509 Certificate for Key Management 10",
749
      SC_ASN1_APP | 0x13,
750
      "2.16.840.1.101.3.7.2.16.10", 3, {0x5F, 0xC1, 0x16}, {0x10, 0x0A},
751
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
752
  { PIV_OBJ_RETIRED_X509_11, "Retired X.509 Certificate for Key Management 11",
753
      SC_ASN1_APP | 0x13,
754
      "2.16.840.1.101.3.7.2.16.11", 3, {0x5F, 0xC1, 0x17}, {0x10, 0x0B},
755
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
756
  { PIV_OBJ_RETIRED_X509_12, "Retired X.509 Certificate for Key Management 12",
757
      SC_ASN1_APP | 0x13,
758
      "2.16.840.1.101.3.7.2.16.12", 3, {0x5F, 0xC1, 0x18}, {0x10, 0x0C},
759
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
760
  { PIV_OBJ_RETIRED_X509_13, "Retired X.509 Certificate for Key Management 13",
761
      SC_ASN1_APP | 0x13,
762
      "2.16.840.1.101.3.7.2.16.13", 3, {0x5F, 0xC1, 0x19}, {0x10, 0x0D},
763
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
764
  { PIV_OBJ_RETIRED_X509_14, "Retired X.509 Certificate for Key Management 14",
765
      SC_ASN1_APP | 0x13,
766
      "2.16.840.1.101.3.7.2.16.14", 3, {0x5F, 0xC1, 0x1A}, {0x10, 0x0E},
767
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
768
  { PIV_OBJ_RETIRED_X509_15, "Retired X.509 Certificate for Key Management 15",
769
      SC_ASN1_APP | 0x13,
770
      "2.16.840.1.101.3.7.2.16.15", 3, {0x5F, 0xC1, 0x1B}, {0x10, 0x0F},
771
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
772
  { PIV_OBJ_RETIRED_X509_16, "Retired X.509 Certificate for Key Management 16",
773
      SC_ASN1_APP | 0x13,
774
      "2.16.840.1.101.3.7.2.16.16", 3, {0x5F, 0xC1, 0x1C}, {0x10, 0x10},
775
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
776
  { PIV_OBJ_RETIRED_X509_17, "Retired X.509 Certificate for Key Management 17",
777
      SC_ASN1_APP | 0x13,
778
      "2.16.840.1.101.3.7.2.16.17", 3, {0x5F, 0xC1, 0x1D}, {0x10, 0x11},
779
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
780
  { PIV_OBJ_RETIRED_X509_18, "Retired X.509 Certificate for Key Management 18",
781
      SC_ASN1_APP | 0x13,
782
      "2.16.840.1.101.3.7.2.16.18", 3, {0x5F, 0xC1, 0x1E}, {0x10, 0x12},
783
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
784
  { PIV_OBJ_RETIRED_X509_19, "Retired X.509 Certificate for Key Management 19",
785
      SC_ASN1_APP | 0x13,
786
      "2.16.840.1.101.3.7.2.16.19", 3, {0x5F, 0xC1, 0x1F}, {0x10, 0x13},
787
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
788
  { PIV_OBJ_RETIRED_X509_20, "Retired X.509 Certificate for Key Management 20",
789
      SC_ASN1_APP | 0x13,
790
      "2.16.840.1.101.3.7.2.16.20", 3, {0x5F, 0xC1, 0x20}, {0x10, 0x14},
791
      PIV_OBJECT_NOT_PRESENT|PIV_OBJECT_TYPE_CERT | PIV_OBJECT_NEEDS_VCI},
792
793
  { PIV_OBJ_IRIS_IMAGE, "Cardholder Iris Images",
794
      SC_ASN1_APP | 0x13,
795
      "2.16.840.1.101.3.7.2.16.21", 3, {0x5F, 0xC1, 0x21}, {0x10, 0x15}, PIV_OBJECT_NEEDS_PIN | PIV_OBJECT_NEEDS_VCI},
796
797
/* 800-73-4, 3 new objects */
798
  { PIV_OBJ_BITGT, "Biometric Information Templates Group Template",
799
       SC_ASN1_APP | SC_ASN1_CONS | 0x1F61,
800
      "2.16.840.1.101.3.7.2.16.22", 2, {0x7F, 0x61}, {0x10, 0x16}, 0},
801
  { PIV_OBJ_SM_CERT_SIGNER, "Secure Messaging Certificate Signer",
802
      SC_ASN1_APP | 0x13,
803
      "2.16.840.1.101.3.7.2.16.23", 3, {0x5F, 0xC1, 0x22}, {0x10, 0x17},
804
      PIV_OBJECT_TYPE_CERT | PIV_OBJECT_TYPE_CVC},
805
  {PIV_OBJ_PCRDCS, "Pairing Code Reference Data Container",
806
      SC_ASN1_APP | 0x13,
807
      "2.16.840.1.101.3.7.2.16.24", 3, {0x5F, 0xC1, 0x23}, {0x10, 0x18}, PIV_OBJECT_NEEDS_PIN | PIV_OBJECT_NEEDS_VCI},
808
809
/* following not standard , to be used by piv-tool only for testing */
810
  { PIV_OBJ_9B03, "3DES-ECB ADM",
811
      SC_ASN1_APP | 0x13,
812
      "2.16.840.1.101.3.7.2.9999.3", 2, {0x9B, 0x03}, {0x9B, 0x03}, 0},
813
  /* Only used when signing a cert req, usually from engine
814
   * after piv-tool generated the key and saved the pub key
815
   * to a file. Note RSA key can be 1024, 2048 or 3072
816
   * but still use the "9x06" name.
817
   */
818
  { PIV_OBJ_9A06, "RSA 9A Pub key from last genkey",
819
      SC_ASN1_APP | 0x13,
820
      "2.16.840.1.101.3.7.2.9999.20", 2, {0x9A, 0x06}, {0x9A, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
821
  { PIV_OBJ_9C06, "Pub 9C key from last genkey",
822
      SC_ASN1_APP | 0x13,
823
      "2.16.840.1.101.3.7.2.9999.21", 2, {0x9C, 0x06}, {0x9C, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
824
  { PIV_OBJ_9D06, "Pub 9D key from last genkey",
825
      SC_ASN1_APP | 0x13,
826
      "2.16.840.1.101.3.7.2.9999.22", 2, {0x9D, 0x06}, {0x9D, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
827
  { PIV_OBJ_9E06, "Pub 9E key from last genkey",
828
      SC_ASN1_APP | 0x13,
829
      "2.16.840.1.101.3.7.2.9999.23", 2, {0x9E, 0x06}, {0x9E, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
830
831
  { PIV_OBJ_8206, "Pub 82 key ",
832
      SC_ASN1_APP | 0x13,
833
      "2.16.840.1.101.3.7.2.9999.101", 2, {0x82, 0x06}, {0x82, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
834
  { PIV_OBJ_8306, "Pub 83 key ",
835
      SC_ASN1_APP | 0x13,
836
      "2.16.840.1.101.3.7.2.9999.102", 2, {0x83, 0x06}, {0x83, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
837
  { PIV_OBJ_8406, "Pub 84 key ",
838
      SC_ASN1_APP | 0x13,
839
      "2.16.840.1.101.3.7.2.9999.103", 2, {0x84, 0x06}, {0x84, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
840
  { PIV_OBJ_8506, "Pub 85 key ",
841
      SC_ASN1_APP | 0x13,
842
      "2.16.840.1.101.3.7.2.9999.104", 2, {0x85, 0x06}, {0x85, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
843
  { PIV_OBJ_8606, "Pub 86 key ",
844
      SC_ASN1_APP | 0x13,
845
      "2.16.840.1.101.3.7.2.9999.105", 2, {0x86, 0x06}, {0x86, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
846
  { PIV_OBJ_8706, "Pub 87 key ",
847
      SC_ASN1_APP | 0x13,
848
      "2.16.840.1.101.3.7.2.9999.106", 2, {0x87, 0x06}, {0x87, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
849
  { PIV_OBJ_8806, "Pub 88 key ",
850
      SC_ASN1_APP | 0x13,
851
      "2.16.840.1.101.3.7.2.9999.107", 2, {0x88, 0x06}, {0x88, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
852
  { PIV_OBJ_8906, "Pub 89 key ",
853
      SC_ASN1_APP | 0x13,
854
      "2.16.840.1.101.3.7.2.9999.108", 2, {0x89, 0x06}, {0x89, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
855
  { PIV_OBJ_8A06, "Pub 8A key ",
856
      SC_ASN1_APP | 0x13,
857
      "2.16.840.1.101.3.7.2.9999.109", 2, {0x8A, 0x06}, {0x8A, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
858
  { PIV_OBJ_8B06, "Pub 8B key ",
859
      SC_ASN1_APP | 0x13,
860
      "2.16.840.1.101.3.7.2.9999.110", 2, {0x8B, 0x06}, {0x8B, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
861
  { PIV_OBJ_8C06, "Pub 8C key ",
862
      SC_ASN1_APP | 0x13,
863
      "2.16.840.1.101.3.7.2.9999.111", 2, {0x8C, 0x06}, {0x8C, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
864
  { PIV_OBJ_8D06, "Pub 8D key ",
865
      SC_ASN1_APP | 0x13,
866
      "2.16.840.1.101.3.7.2.9999.112", 2, {0x8D, 0x06}, {0x8D, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
867
  { PIV_OBJ_8E06, "Pub 8E key ",
868
      SC_ASN1_APP | 0x13,
869
      "2.16.840.1.101.3.7.2.9999.113", 2, {0x8E, 0x06}, {0x8E, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
870
  { PIV_OBJ_8F06, "Pub 8F key ",
871
      SC_ASN1_APP | 0x13,
872
      "2.16.840.1.101.3.7.2.9999.114", 2, {0x8F, 0x06}, {0x8F, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
873
  { PIV_OBJ_9006, "Pub 90 key ",
874
      SC_ASN1_APP | 0x13,
875
      "2.16.840.1.101.3.7.2.9999.115", 2, {0x90, 0x06}, {0x90, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
876
  { PIV_OBJ_9106, "Pub 91 key ",
877
      SC_ASN1_APP | 0x13,
878
      "2.16.840.1.101.3.7.2.9999.116", 2, {0x91, 0x06}, {0x91, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
879
  { PIV_OBJ_9206, "Pub 92 key ",
880
      SC_ASN1_APP | 0x13,
881
      "2.16.840.1.101.3.7.2.9999.117", 2, {0x92, 0x06}, {0x92, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
882
  { PIV_OBJ_9306, "Pub 93 key ",
883
      SC_ASN1_APP | 0x13,
884
      "2.16.840.1.101.3.7.2.9999.118", 2, {0x93, 0x06}, {0x93, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
885
  { PIV_OBJ_9406, "Pub 94 key ",
886
      SC_ASN1_APP | 0x13,
887
      "2.16.840.1.101.3.7.2.9999.119", 2, {0x94, 0x06}, {0x94, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
888
  { PIV_OBJ_9506, "Pub 95 key ",
889
      SC_ASN1_APP | 0x13,
890
      "2.16.840.1.101.3.7.2.9999.120", 2, {0x95, 0x06}, {0x95, 0x06}, PIV_OBJECT_TYPE_PUBKEY},
891
      /*
892
       * "Secure Messaging Certificate Signer" is just a certificate.
893
       * No pub or private key on the card.
894
       */
895
  { PIV_OBJ_LAST_ENUM, "", 0, "", 0, "", "", 0}
896
};
897
// clang-format on
898
899
static struct sc_card_operations piv_ops;
900
901
static struct sc_card_driver piv_drv = {
902
    "Personal Identity Verification Card",
903
    "PIV-II",
904
    &piv_ops,
905
    NULL, 0, NULL};
906
907
static int piv_get_cached_data(sc_card_t *card, int enumtag, u8 **buf, size_t *buf_len);
908
static int piv_cache_internal_data(sc_card_t *card, int enumtag);
909
static int piv_logout(sc_card_t *card);
910
static int piv_match_card_continued(sc_card_t *card);
911
static int piv_obj_cache_free_entry(sc_card_t *card, int enumtag, int flags);
912
static int piv_ai_map_find_by_id(sc_card_t *card, u8);
913
914
#ifdef ENABLE_PIV_SM
915
static void piv_inc(u8 *counter, size_t size);
916
static int piv_encode_apdu(sc_card_t *card, sc_apdu_t *plain, sc_apdu_t *sm_apdu);
917
static int piv_get_sm_apdu(sc_card_t *card, sc_apdu_t *plain, sc_apdu_t **sm_apdu);
918
static int piv_free_sm_apdu(sc_card_t *card, sc_apdu_t *plain, sc_apdu_t **sm_apdu);
919
static int piv_get_asn1_obj(sc_context_t *ctx, void *arg, const u8 *obj, size_t len, int depth);
920
static int piv_sm_open(struct sc_card *card);
921
static int piv_decode_apdu(sc_card_t *card, sc_apdu_t *plain, sc_apdu_t *sm_apdu);
922
static int piv_sm_close(sc_card_t *card);
923
static void piv_clear_cvc_content(piv_cvc_t *cvc);
924
static void piv_clear_sm_session(piv_sm_session_t *session);
925
static int piv_decode_cvc(sc_card_t *card, u8 **buf, size_t *buflen, piv_cvc_t *cvc);
926
static int piv_parse_pairing_code(sc_card_t *card, const char *option);
927
static int Q2OS(int fsize, u8 *Q, size_t Qlen, u8 *OS, size_t *OSlen);
928
static int piv_send_vci_pairing_code(struct sc_card *card, u8 *paring_code);
929
static int piv_sm_verify_sig(struct sc_card *card, const EVP_MD *type,
930
    EVP_PKEY *pkey, u8 *data, size_t data_size,
931
    unsigned char *sig, size_t siglen);
932
static int piv_sm_verify_certs(struct sc_card *card);
933
934
static void
935
piv_inc(u8 *counter, size_t size)
936
{
937
  unsigned int c = 1;
938
  unsigned int b;
939
  int i;
940
  for (i = (int)size - 1; c != 0 && i >= 0; i--) {
941
    b = c + counter[i];
942
    counter[i] = b & 0xff;
943
    c = b >> 8;
944
  }
945
}
946
947
/*
948
 *  Construct SM protected APDU
949
 */
950
951
static int
952
piv_encode_apdu(sc_card_t *card, sc_apdu_t *plain, sc_apdu_t *sm_apdu)
953
{
954
  int r = 0;
955
  piv_private_data_t *priv = PIV_DATA(card);
956
  cipher_suite_t *cs = priv->cs;
957
  u8 pad[16] = {0x80};
958
  u8 zeros[16] = {0x00};
959
  u8 IV[16];
960
  u8 header[16];
961
  int padlen = 16; /* may be less */
962
  u8 *sbuf = NULL;
963
  size_t sbuflen = 0;
964
  int MCVlen = 16;
965
  int enc_datalen = 0;
966
  int T87len;
967
  int T97len = 2 + 1;
968
  int T8Elen = 2 + 8;
969
970
  int outli = 0;
971
  int outl = 0;
972
  int outll = 0;
973
  int outdl = 0;
974
  u8 discard[16];
975
  int macdatalen;
976
  size_t C_MCVlen = 16; /* debugging*/
977
978
  u8 *p;
979
  EVP_CIPHER_CTX *ed_ctx = NULL;
980
#if OPENSSL_VERSION_NUMBER < 0x30000000L
981
  CMAC_CTX *cmac_ctx = NULL;
982
#else
983
  EVP_MAC_CTX *cmac_ctx = NULL;
984
  EVP_MAC *mac = NULL;
985
  OSSL_PARAM cmac_params[2];
986
  size_t cmac_params_n;
987
#endif
988
989
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
990
991
#if OPENSSL_VERSION_NUMBER < 0x30000000L
992
  cmac_ctx = CMAC_CTX_new();
993
  if (cmac_ctx == NULL) {
994
    sc_log_openssl(card->ctx);
995
    r = SC_ERROR_INTERNAL;
996
    goto err;
997
  }
998
#else
999
  mac = EVP_MAC_fetch(PIV_LIBCTX, "cmac", NULL);
1000
  cmac_params_n = 0;
1001
  cmac_params[cmac_params_n++] = OSSL_PARAM_construct_utf8_string("cipher", cs->cipher_cbc_name, 0);
1002
  cmac_params[cmac_params_n] = OSSL_PARAM_construct_end();
1003
  if (mac == NULL || (cmac_ctx = EVP_MAC_CTX_new(mac)) == NULL) {
1004
    sc_log_openssl(card->ctx);
1005
    r = SC_ERROR_INTERNAL;
1006
    goto err;
1007
  }
1008
#endif
1009
1010
  ed_ctx = EVP_CIPHER_CTX_new();
1011
  if (ed_ctx == NULL) {
1012
    r = SC_ERROR_INTERNAL;
1013
    goto err;
1014
  }
1015
1016
  if (EVP_EncryptInit_ex(ed_ctx, (*cs->cipher_ecb)(), NULL, priv->sm_session.SKenc, zeros) != 1 ||
1017
      EVP_CIPHER_CTX_set_padding(ed_ctx, 0) != 1 ||
1018
      EVP_EncryptUpdate(ed_ctx, IV, &outli, priv->sm_session.enc_counter, 16) != 1 ||
1019
      EVP_EncryptFinal_ex(ed_ctx, discard, &outdl) != 1 ||
1020
      outdl != 0) {
1021
    sc_log_openssl(card->ctx);
1022
    sc_log(card->ctx, "SM encode failed in OpenSSL");
1023
    r = SC_ERROR_INTERNAL;
1024
    goto err;
1025
  }
1026
1027
  sm_apdu->cla = 0x0c;
1028
  sm_apdu->ins = plain->ins;
1029
  sm_apdu->p1 = plain->p1;
1030
  sm_apdu->p2 = plain->p2;
1031
1032
  /*
1033
   * All APDUs will be converted to case as SM data is always sent and received
1034
   * if plain->cse == SC_APDU_CASE_1 it never has the the 0x20 bit set
1035
   * which "let OpenSC decides whether to use short or extended APDUs"
1036
   * PIV SM data added for plain->cse == SC_APDU_CASE_1 will not need extended APDUs.
1037
   *
1038
   * NIST 800-73-4 does not say if cards can or must support extended APDUs
1039
   * they must support command chaining and multiple get response APDUs and
1040
   * all examples use short APDUs. The following keep the option open to use extended
1041
   * APDUs in future specifications or "PIV like" cards are know to
1042
   * support extended APDUs.
1043
   *
1044
   * Turn off the CASE bits, and set CASE 4 in sm_apdu.
1045
   */
1046
1047
  sm_apdu->cse = (plain->cse & ~SC_APDU_SHORT_MASK) | SC_APDU_CASE_4_SHORT;
1048
1049
  p = header; /* to be included in CMAC */
1050
  *p++ = 0x0c;
1051
  *p++ = plain->ins;
1052
  *p++ = plain->p1;
1053
  *p++ = plain->p2;
1054
  memcpy(p, pad, 12);
1055
1056
  /* 800-73-4 say padding is 1 to 16 bytes, with 0x80 0x00... */
1057
1058
  /* may not need enc_data for cse 1 or 2 */
1059
  if (plain->datalen == 0) {
1060
    enc_datalen = 0;
1061
    T87len = 0;
1062
    padlen = 0;
1063
  } else {
1064
    enc_datalen = (int)(((plain->datalen + 16) / 16) * 16); /* may add extra 16 bytes */
1065
    padlen = enc_datalen - (int)plain->datalen;
1066
    r = T87len = sc_asn1_put_tag(0x87, NULL, 1 + enc_datalen, NULL, 0, NULL);
1067
    if (r < 0)
1068
      goto err;
1069
  }
1070
1071
  if (plain->resplen == 0 || plain->le == 0)
1072
    T97len = 0;
1073
1074
  sbuflen = T87len + T97len + T8Elen;
1075
1076
  sbuf = calloc(1, sbuflen);
1077
  if (sbuf == NULL) {
1078
    r = SC_ERROR_OUT_OF_MEMORY;
1079
    goto err;
1080
  }
1081
1082
  p = sbuf;
1083
  if (T87len != 0) {
1084
    r = sc_asn1_put_tag(0x87, NULL, 1 + enc_datalen, sbuf, sbuflen, &p);
1085
    if (r != SC_SUCCESS)
1086
      goto err;
1087
1088
    *p++ = 0x01; /* padding context indicator */
1089
1090
    /* first round encryptes Enc counter with zero IV, and does not save the output */
1091
    if (EVP_CIPHER_CTX_reset(ed_ctx) != 1 ||
1092
        EVP_EncryptInit_ex(ed_ctx, (*cs->cipher_cbc)(), NULL, priv->sm_session.SKenc, IV) != 1 ||
1093
        EVP_CIPHER_CTX_set_padding(ed_ctx, 0) != 1 ||
1094
        EVP_EncryptUpdate(ed_ctx, p, &outl, plain->data, (int)plain->datalen) != 1 ||
1095
        EVP_EncryptUpdate(ed_ctx, p + outl, &outll, pad, padlen) != 1 ||
1096
        EVP_EncryptFinal_ex(ed_ctx, discard, &outdl) != 1 ||
1097
        outdl != 0) { /* should not happen */
1098
      sc_log_openssl(card->ctx);
1099
      sc_log(card->ctx, "SM _encode failed in OpenSSL");
1100
      r = SC_ERROR_INTERNAL;
1101
      goto err;
1102
    }
1103
    p += enc_datalen;
1104
  }
1105
1106
  if (T97len) {
1107
    *p++ = 0x97;
1108
    *p++ = 0x01;
1109
    *p++ = plain->le;
1110
  }
1111
  macdatalen = (int)(p - sbuf);
1112
1113
  memcpy(priv->sm_session.C_MCV_last, priv->sm_session.C_MCV, MCVlen); /* save is case fails */
1114
1115
#if OPENSSL_VERSION_NUMBER < 0x30000000L
1116
  if (CMAC_Init(cmac_ctx, priv->sm_session.SKmac, priv->sm_session.aes_size, (*cs->cipher_cbc)(), NULL) != 1 ||
1117
      CMAC_Update(cmac_ctx, priv->sm_session.C_MCV, MCVlen) != 1 ||
1118
      CMAC_Update(cmac_ctx, header, sizeof(header)) != 1 ||
1119
      CMAC_Update(cmac_ctx, sbuf, macdatalen) != 1 ||
1120
      CMAC_Final(cmac_ctx, priv->sm_session.C_MCV, &C_MCVlen) != 1) {
1121
    sc_log_openssl(card->ctx);
1122
    r = SC_ERROR_INTERNAL;
1123
    goto err;
1124
  }
1125
#else
1126
  if (!EVP_MAC_init(cmac_ctx, (const unsigned char *)priv->sm_session.SKmac,
1127
          priv->sm_session.aes_size, cmac_params) ||
1128
      !EVP_MAC_update(cmac_ctx, priv->sm_session.C_MCV, MCVlen) ||
1129
      !EVP_MAC_update(cmac_ctx, header, sizeof(header)) ||
1130
      !EVP_MAC_update(cmac_ctx, sbuf, macdatalen) ||
1131
      !EVP_MAC_final(cmac_ctx, priv->sm_session.C_MCV, &C_MCVlen, MCVlen)) {
1132
    sc_log_openssl(card->ctx);
1133
    r = SC_ERROR_INTERNAL;
1134
    goto err;
1135
  }
1136
#endif
1137
1138
  *p++ = 0x8E;
1139
  *p++ = 0x08;
1140
  memcpy(p, priv->sm_session.C_MCV, 8);
1141
  p += 8;
1142
  if (p != sbuf + sbuflen) { /* debugging */
1143
    r = SC_ERROR_INTERNAL;
1144
    goto err;
1145
  }
1146
  sm_apdu->data = sbuf;
1147
  sm_apdu->datalen = sbuflen;
1148
  sbuf = NULL;
1149
1150
  sm_apdu->lc = sm_apdu->datalen;
1151
  if (sm_apdu->datalen > 255)
1152
    sm_apdu->flags |= SC_APDU_FLAGS_CHAINING;
1153
1154
  sm_apdu->resplen = plain->resplen + 40; /* expect at least tagged status and rmac8 */
1155
  sm_apdu->resp = malloc(sm_apdu->resplen);
1156
  if (sm_apdu->resp == NULL) {
1157
    r = SC_ERROR_OUT_OF_MEMORY;
1158
    goto err;
1159
  }
1160
  sm_apdu->le = 256; /* always ask for 256 */
1161
1162
  memcpy(priv->sm_session.enc_counter_last, priv->sm_session.enc_counter, sizeof(priv->sm_session.enc_counter));
1163
  piv_inc(priv->sm_session.enc_counter, sizeof(priv->sm_session.enc_counter));
1164
1165
  r = SC_SUCCESS;
1166
err:
1167
1168
  free(sbuf);
1169
#if OPENSSL_VERSION_NUMBER < 0x30000000L
1170
  CMAC_CTX_free(cmac_ctx);
1171
#else
1172
  EVP_MAC_CTX_free(cmac_ctx);
1173
  EVP_MAC_free(mac);
1174
#endif
1175
1176
  EVP_CIPHER_CTX_free(ed_ctx);
1177
1178
  LOG_FUNC_RETURN(card->ctx, r);
1179
}
1180
1181
static int
1182
piv_get_sm_apdu(sc_card_t *card, sc_apdu_t *plain, sc_apdu_t **sm_apdu)
1183
{
1184
  int r = SC_SUCCESS;
1185
  piv_private_data_t *priv = PIV_DATA(card);
1186
  cipher_suite_t *cs = priv->cs;
1187
1188
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1189
1190
  if (!plain || !sm_apdu)
1191
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
1192
1193
  /* Does card support SM? Should not be here */
1194
  if (priv->csID == 0 || cs == NULL)
1195
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_SM_NOT_APPLIED);
1196
1197
  switch (plain->ins) {
1198
  case 0xCB: /* GET_DATA */
1199
    /* If not contactless, could read in clear */
1200
    /* Discovery object never has PIV_SM_GET_DATA_IN_CLEAR set */
1201
    sc_log(card->ctx, "init_flags:0x%8.8x sm_flags:0x%8.8lx", priv->init_flags, priv->sm_flags);
1202
    if (!(priv->init_flags & PIV_INIT_CONTACTLESS) &&
1203
        !(priv->init_flags & PIV_INIT_IN_READER_LOCK_OBTAINED) &&
1204
        (priv->sm_flags & PIV_SM_GET_DATA_IN_CLEAR)) {
1205
      priv->sm_flags &= ~PIV_SM_GET_DATA_IN_CLEAR;
1206
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_SM_NOT_APPLIED);
1207
    }
1208
    break;
1209
  case 0x20: /* VERIFY */
1210
    break;
1211
  case 0x24: /* CHANGE REFERENCE DATA */
1212
    break;
1213
  case 0x87: /* GENERAL AUTHENTICATE */
1214
    break;
1215
  default: /* just issue the plain apdu */
1216
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_SM_NOT_APPLIED);
1217
  }
1218
1219
  *sm_apdu = calloc(1, sizeof(sc_apdu_t));
1220
  if (*sm_apdu == NULL) {
1221
    return SC_ERROR_OUT_OF_MEMORY;
1222
  }
1223
1224
  r = piv_encode_apdu(card, plain, *sm_apdu);
1225
  if (r < 0 && *sm_apdu) {
1226
    piv_free_sm_apdu(card, NULL, sm_apdu);
1227
  }
1228
1229
  LOG_FUNC_RETURN(card->ctx, r);
1230
}
1231
1232
/* ASN1 callback to save address and len of the object */
1233
static int
1234
piv_get_asn1_obj(sc_context_t *ctx, void *arg, const u8 *obj, size_t len, int depth)
1235
{
1236
  struct sc_lv_data *al = arg;
1237
1238
  if (!arg)
1239
    return SC_ERROR_INTERNAL;
1240
1241
  al->value = (u8 *)obj;
1242
  al->len = len;
1243
  return SC_SUCCESS;
1244
}
1245
1246
static int
1247
piv_decode_apdu(sc_card_t *card, sc_apdu_t *plain, sc_apdu_t *sm_apdu)
1248
{
1249
  int r = SC_SUCCESS;
1250
  int i;
1251
  piv_private_data_t *priv = PIV_DATA(card);
1252
  cipher_suite_t *cs = priv->cs;
1253
  struct sc_lv_data ee = {NULL, 0};
1254
  struct sc_lv_data status = {NULL, 0};
1255
  struct sc_lv_data rmac8 = {NULL, 0};
1256
  u8 zeros[16] = {0};
1257
  u8 IV[16];
1258
  u8 *p;
1259
  int outl;
1260
  int outli;
1261
  int outll;
1262
  int outdl;
1263
  u8 lastb[16];
1264
  u8 discard[8];
1265
  u8 *q = NULL;
1266
  int inlen;
1267
  int macdatalen;
1268
1269
  size_t MCVlen = 16;
1270
  size_t R_MCVlen = 0;
1271
1272
  EVP_CIPHER_CTX *ed_ctx = NULL;
1273
#if OPENSSL_VERSION_NUMBER < 0x30000000L
1274
  CMAC_CTX *cmac_ctx = NULL;
1275
#else
1276
  EVP_MAC *mac = NULL;
1277
  EVP_MAC_CTX *cmac_ctx = NULL;
1278
  OSSL_PARAM cmac_params[2];
1279
  size_t cmac_params_n = 0;
1280
#endif
1281
1282
  struct sc_asn1_entry asn1_sm_response[C_ASN1_PIV_SM_RESPONSE_SIZE];
1283
1284
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1285
1286
  sc_copy_asn1_entry(c_asn1_sm_response, asn1_sm_response);
1287
1288
  sc_format_asn1_entry(asn1_sm_response + 0, piv_get_asn1_obj, &ee, 0);
1289
  sc_format_asn1_entry(asn1_sm_response + 1, piv_get_asn1_obj, &status, 0);
1290
  sc_format_asn1_entry(asn1_sm_response + 2, piv_get_asn1_obj, &rmac8, 0);
1291
1292
  r = sc_asn1_decode(card->ctx, asn1_sm_response, sm_apdu->resp, sm_apdu->resplen, NULL, NULL);
1293
1294
  if (r < 0) {
1295
    sc_log(card->ctx, "SM decode failed");
1296
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
1297
    goto err;
1298
  }
1299
1300
  if (asn1_sm_response[0].flags & SC_ASN1_PRESENT && /* optional */
1301
      (ee.value == NULL || ee.len <= 2)) {
1302
    sc_log(card->ctx, "SM BER-TLV not valid");
1303
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
1304
    goto err;
1305
  }
1306
1307
  if ((asn1_sm_response[1].flags & SC_ASN1_PRESENT) == 0 ||
1308
      (asn1_sm_response[2].flags & SC_ASN1_PRESENT) == 0) {
1309
    sc_log(card->ctx, "SM missing status or R-MAC");
1310
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
1311
    goto err;
1312
  }
1313
1314
  if (status.len != 2 ||
1315
      status.value == NULL ||
1316
      rmac8.len != 8 ||
1317
      rmac8.value == NULL) {
1318
    sc_log(card->ctx, "SM status or R-MAC length invalid");
1319
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
1320
    goto err;
1321
  }
1322
1323
#if OPENSSL_VERSION_NUMBER < 0x30000000L
1324
  cmac_ctx = CMAC_CTX_new();
1325
  if (cmac_ctx == NULL) {
1326
    sc_log_openssl(card->ctx);
1327
    r = SC_ERROR_INTERNAL;
1328
    goto err;
1329
  }
1330
#else
1331
  mac = EVP_MAC_fetch(PIV_LIBCTX, "cmac", NULL);
1332
  cmac_params[cmac_params_n++] = OSSL_PARAM_construct_utf8_string("cipher", cs->cipher_cbc_name, 0);
1333
  cmac_params[cmac_params_n] = OSSL_PARAM_construct_end();
1334
  if (mac == NULL || (cmac_ctx = EVP_MAC_CTX_new(mac)) == NULL) {
1335
    sc_log_openssl(card->ctx);
1336
    r = SC_ERROR_INTERNAL;
1337
    goto err;
1338
  }
1339
#endif
1340
1341
  /*  MCV is first, then BER TLV Encoded Encrypted PIV Data and Status */
1342
  macdatalen = (int)(status.value + status.len - sm_apdu->resp);
1343
1344
#if OPENSSL_VERSION_NUMBER < 0x30000000L
1345
  if (CMAC_Init(cmac_ctx, priv->sm_session.SKrmac, priv->sm_session.aes_size, (*cs->cipher_cbc)(), NULL) != 1 ||
1346
      CMAC_Update(cmac_ctx, priv->sm_session.R_MCV, MCVlen) != 1 ||
1347
      CMAC_Update(cmac_ctx, sm_apdu->resp, macdatalen) != 1 ||
1348
      CMAC_Final(cmac_ctx, priv->sm_session.R_MCV, &R_MCVlen) != 1) {
1349
    sc_log_openssl(card->ctx);
1350
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
1351
    goto err;
1352
  }
1353
#else
1354
  if (!EVP_MAC_init(cmac_ctx, (const unsigned char *)priv->sm_session.SKrmac,
1355
          priv->sm_session.aes_size, cmac_params) ||
1356
      !EVP_MAC_update(cmac_ctx, priv->sm_session.R_MCV, MCVlen) ||
1357
      !EVP_MAC_update(cmac_ctx, sm_apdu->resp, macdatalen) ||
1358
      !EVP_MAC_final(cmac_ctx, priv->sm_session.R_MCV, &R_MCVlen, MCVlen)) {
1359
    sc_log_openssl(card->ctx);
1360
    r = SC_ERROR_INTERNAL;
1361
    goto err;
1362
  }
1363
#endif
1364
1365
  if (memcmp(priv->sm_session.R_MCV, rmac8.value, 8) != 0) {
1366
    sc_log(card->ctx, "SM 8 bytes of R-MAC do not match received R-MAC");
1367
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
1368
    goto err;
1369
  }
1370
1371
  ed_ctx = EVP_CIPHER_CTX_new();
1372
  if (ed_ctx == NULL) {
1373
    r = SC_ERROR_INTERNAL;
1374
    goto err;
1375
  }
1376
1377
  /* generate same IV used to encrypt response on card */
1378
  if (EVP_EncryptInit_ex(ed_ctx, (*cs->cipher_ecb)(), NULL, priv->sm_session.SKenc, zeros) != 1 ||
1379
      EVP_CIPHER_CTX_set_padding(ed_ctx, 0) != 1 ||
1380
      EVP_EncryptUpdate(ed_ctx, IV, &outli, priv->sm_session.resp_enc_counter, 16) != 1 ||
1381
      EVP_EncryptFinal_ex(ed_ctx, discard, &outdl) != 1 ||
1382
      outdl != 0) {
1383
    sc_log_openssl(card->ctx);
1384
    sc_log(card->ctx, "SM encode failed in OpenSSL");
1385
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
1386
    goto err;
1387
  }
1388
1389
  /* some commands do not have response data */
1390
  if (ee.value == NULL) {
1391
    plain->resplen = 0;
1392
  } else {
1393
    p = ee.value;
1394
    inlen = (int)ee.len;
1395
    if (inlen < 17 || *p != 0x01) { /*padding and padding indicator are required */
1396
      sc_log(card->ctx, "SM padding indicator not 0x01");
1397
      r = SC_ERROR_SM_AUTHENTICATION_FAILED;
1398
      goto err;
1399
    }
1400
1401
    p++; /* skip padding indicator */
1402
    inlen--;
1403
1404
    if ((inlen % 16) != 0) {
1405
      sc_log(card->ctx, "SM encrypted data not multiple of 16");
1406
      r = SC_ERROR_SM_AUTHENTICATION_FAILED;
1407
      goto err;
1408
    }
1409
1410
    /*
1411
     * Encrypted data has 1 to 16 pad bytes, so may be 1 to 16 bytes longer
1412
     * then expected. i.e. plain->resp and resplen.So will do last block
1413
     * and recombine.
1414
     */
1415
1416
    inlen -= 16;
1417
    if (plain->resplen < (unsigned)inlen || plain->resp == NULL) {
1418
      sc_log(card->ctx, "SM response will not fit in resp,resplen");
1419
      r = SC_ERROR_SM_AUTHENTICATION_FAILED;
1420
      goto err;
1421
    }
1422
1423
    q = plain->resp;
1424
1425
    /* first round encryptes counter with zero IV, and does not save the output */
1426
    if (EVP_CIPHER_CTX_reset(ed_ctx) != 1 ||
1427
        EVP_DecryptInit_ex(ed_ctx, (*cs->cipher_cbc)(), NULL, priv->sm_session.SKenc, IV) != 1 ||
1428
        EVP_CIPHER_CTX_set_padding(ed_ctx, 0) != 1 ||
1429
        EVP_DecryptUpdate(ed_ctx, q, &outl, p, inlen) != 1 ||
1430
        EVP_DecryptUpdate(ed_ctx, lastb, &outll, p + inlen, 16) != 1 ||
1431
        EVP_DecryptFinal_ex(ed_ctx, discard, &outdl) != 1 ||
1432
        outdl != 0 ||
1433
        outll != 16) { /* should not happen */
1434
      sc_log_openssl(card->ctx);
1435
      sc_log(card->ctx, "SM _decode failed in OpenSSL");
1436
      r = SC_ERROR_SM_AUTHENTICATION_FAILED;
1437
      goto err;
1438
    }
1439
1440
    /* unpad last block and get bytes in last block */
1441
    for (i = 15; i > 0; i--) {
1442
      if (lastb[i] == 0x80)
1443
        break;
1444
      if (lastb[i] == 0x00)
1445
        continue;
1446
      sc_log(card->ctx, "SM Padding not correct");
1447
      r = SC_ERROR_SM_AUTHENTICATION_FAILED;
1448
      goto err;
1449
    }
1450
1451
    if (lastb[i] != 0x80) {
1452
      sc_log(card->ctx, "SM Padding not correct");
1453
      r = SC_ERROR_SM_AUTHENTICATION_FAILED;
1454
      goto err;
1455
    }
1456
1457
    /* will response fit in plain resp buffer */
1458
    if ((unsigned)inlen + i > plain->resplen || plain->resp == NULL) {
1459
      sc_log(card->ctx, "SM response bigger then resplen");
1460
      r = SC_ERROR_SM_AUTHENTICATION_FAILED;
1461
      goto err;
1462
    }
1463
1464
    /* copy bytes in last block  if any */
1465
    memcpy(plain->resp + inlen, lastb, i);
1466
    plain->resplen = inlen + i;
1467
  }
1468
1469
  plain->sw1 = *(status.value);
1470
  plain->sw2 = *(status.value + 1);
1471
1472
  piv_inc(priv->sm_session.resp_enc_counter, sizeof(priv->sm_session.resp_enc_counter));
1473
1474
  r = SC_SUCCESS;
1475
err:
1476
  if (r != 0 && plain) {
1477
    plain->sw1 = 0x69;
1478
    plain->sw2 = 0x88;
1479
  }
1480
1481
#if OPENSSL_VERSION_NUMBER < 0x30000000L
1482
  CMAC_CTX_free(cmac_ctx);
1483
#else
1484
  EVP_MAC_CTX_free(cmac_ctx);
1485
  EVP_MAC_free(mac);
1486
#endif
1487
1488
  EVP_CIPHER_CTX_free(ed_ctx);
1489
1490
  LOG_FUNC_RETURN(card->ctx, r);
1491
}
1492
1493
static int
1494
piv_free_sm_apdu(sc_card_t *card, sc_apdu_t *plain, sc_apdu_t **sm_apdu)
1495
{
1496
  int r = SC_SUCCESS;
1497
1498
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1499
1500
  if (!sm_apdu)
1501
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
1502
  if (!(*sm_apdu))
1503
    LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
1504
1505
  if (plain) {
1506
    plain->sw1 = (*sm_apdu)->sw1;
1507
    plain->sw2 = (*sm_apdu)->sw2;
1508
    if (((*sm_apdu)->sw1 == 0x90 && (*sm_apdu)->sw2 == 00) ||
1509
        (*sm_apdu)->sw1 == 61) {
1510
      r = piv_decode_apdu(card, plain, *sm_apdu);
1511
      goto err;
1512
    }
1513
    sc_log(card->ctx, "SM response sw1:0x%2.2x sw2:0x%2.2x", plain->sw1, plain->sw2);
1514
    if (plain->sw1 == 0x69 && plain->sw2 == 0x88) {
1515
      /* BUT plain->sw1 and sw2 are not passed back as expected */
1516
      r = SC_ERROR_SM_INVALID_CHECKSUM; /* will use this one one for now */
1517
      goto err;
1518
    } else {
1519
      r = SC_ERROR_SM;
1520
      goto err;
1521
    }
1522
  }
1523
1524
err:
1525
  free((unsigned char **)(*sm_apdu)->data);
1526
  free((*sm_apdu)->resp);
1527
  free(*sm_apdu);
1528
  *sm_apdu = NULL;
1529
1530
  LOG_FUNC_RETURN(card->ctx, r);
1531
}
1532
1533
static int
1534
piv_sm_close(sc_card_t *card)
1535
{
1536
  int r = 0;
1537
  piv_private_data_t *priv = PIV_DATA(card);
1538
1539
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1540
  sc_log(card->ctx, "priv->sm_flags: 0x%8.8lu", priv->sm_flags);
1541
1542
  /* sm.c tries to restart sm. Will defer */
1543
  if ((priv->sm_flags & PIV_SM_FLAGS_SM_IS_ACTIVE)) {
1544
    priv->sm_flags |= PIV_SM_FLAGS_DEFER_OPEN;
1545
    priv->sm_flags &= ~PIV_SM_FLAGS_SM_IS_ACTIVE;
1546
  }
1547
1548
  LOG_FUNC_RETURN(card->ctx, r);
1549
}
1550
1551
static void
1552
piv_clear_cvc_content(piv_cvc_t *cvc)
1553
{
1554
  if (!cvc)
1555
    return;
1556
  free(cvc->body);
1557
  free(cvc->signature);
1558
  free(cvc->publicPoint);
1559
  free(cvc->der.value);
1560
  memset(cvc, 0, sizeof(piv_cvc_t));
1561
  return;
1562
}
1563
1564
static void
1565
piv_clear_sm_session(piv_sm_session_t *session)
1566
{
1567
  if (!session)
1568
    return;
1569
  sc_mem_clear(session, sizeof(piv_sm_session_t));
1570
  return;
1571
}
1572
1573
/*
1574
 * Decode a card verifiable certificate as defined in NIST 800-73-4
1575
 */
1576
static int
1577
piv_decode_cvc(sc_card_t *card, u8 **buf, size_t *buflen,
1578
    piv_cvc_t *cvc)
1579
{
1580
  struct sc_asn1_entry asn1_piv_cvc[C_ASN1_PIV_CVC_SIZE];
1581
  struct sc_asn1_entry asn1_piv_cvc_body[C_ASN1_PIV_CVC_BODY_SIZE];
1582
  struct sc_asn1_entry asn1_piv_cvc_pubkey[C_ASN1_PIV_CVC_PUBKEY_SIZE];
1583
  struct sc_asn1_entry asn1_piv_cvc_dsobj[C_ASN1_PIV_CVC_DSOBJ_SIZE];
1584
  struct sc_asn1_entry asn1_piv_cvc_dssig[C_ASN1_PIV_CVC_DSSIG_SIZE];
1585
  struct sc_asn1_entry asn1_piv_cvc_alg_id[C_ASN1_PIV_CVC_ALG_ID_SIZE];
1586
  struct sc_lv_data roleIDder = {NULL, 0};
1587
  int r;
1588
  const u8 *buf_tmp;
1589
  unsigned int cla_out, tag_out;
1590
  size_t taglen;
1591
  size_t signaturebits;
1592
1593
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1594
1595
  if (buf == NULL || *buf == NULL || cvc == NULL) {
1596
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
1597
  }
1598
1599
  /* If already read and matches previous version return SC_SUCCESS */
1600
  if (cvc->der.value && (cvc->der.len == *buflen) && (memcmp(cvc->der.value, *buf, *buflen) == 0))
1601
    LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
1602
1603
  piv_clear_cvc_content(cvc);
1604
1605
  memset(cvc, 0, sizeof(piv_cvc_t));
1606
  cvc->issuerIDlen = sizeof(cvc->issuerID);
1607
  cvc->subjectIDlen = sizeof(cvc->subjectID);
1608
1609
  sc_copy_asn1_entry(c_asn1_piv_cvc, asn1_piv_cvc);
1610
  sc_copy_asn1_entry(c_asn1_piv_cvc_body, asn1_piv_cvc_body);
1611
  sc_copy_asn1_entry(c_asn1_piv_cvc_pubkey, asn1_piv_cvc_pubkey);
1612
  sc_copy_asn1_entry(c_asn1_piv_cvc_dsobj, asn1_piv_cvc_dsobj);
1613
  sc_copy_asn1_entry(c_asn1_piv_cvc_dssig, asn1_piv_cvc_dssig);
1614
  sc_copy_asn1_entry(c_asn1_piv_cvc_alg_id, asn1_piv_cvc_alg_id);
1615
1616
  sc_format_asn1_entry(asn1_piv_cvc_alg_id, &cvc->signatureAlgOID, NULL, 1);
1617
  sc_format_asn1_entry(asn1_piv_cvc_alg_id + 1, NULL, NULL, 1); /* NULL */
1618
1619
  sc_format_asn1_entry(asn1_piv_cvc_dssig, &asn1_piv_cvc_alg_id, NULL, 1);
1620
  sc_format_asn1_entry(asn1_piv_cvc_dssig + 1, &cvc->signature, &signaturebits, 1);
1621
1622
  sc_format_asn1_entry(asn1_piv_cvc_dsobj, &asn1_piv_cvc_dssig, NULL, 1);
1623
1624
  sc_format_asn1_entry(asn1_piv_cvc_pubkey, &cvc->pubKeyOID, NULL, 1);
1625
  sc_format_asn1_entry(asn1_piv_cvc_pubkey + 1, &cvc->publicPoint, &cvc->publicPointlen, 1);
1626
1627
  sc_format_asn1_entry(asn1_piv_cvc_body, &cvc->cpi, NULL, 1);
1628
  sc_format_asn1_entry(asn1_piv_cvc_body + 1, &cvc->issuerID, &cvc->issuerIDlen, 1);
1629
  sc_format_asn1_entry(asn1_piv_cvc_body + 2, &cvc->subjectID, &cvc->subjectIDlen, 1);
1630
  sc_format_asn1_entry(asn1_piv_cvc_body + 3, &asn1_piv_cvc_pubkey, NULL, 1);
1631
  sc_format_asn1_entry(asn1_piv_cvc_body + 4, piv_get_asn1_obj, &roleIDder, 1);
1632
  sc_format_asn1_entry(asn1_piv_cvc_body + 5, &asn1_piv_cvc_dsobj, NULL, 1);
1633
1634
  sc_format_asn1_entry(asn1_piv_cvc, &asn1_piv_cvc_body, NULL, 1);
1635
1636
  r = sc_asn1_decode(card->ctx, asn1_piv_cvc, *buf, *buflen, NULL, NULL); /*(const u8 **) &buf_tmp, &len);*/
1637
  if (r < 0) {
1638
    piv_clear_cvc_content(cvc);
1639
    sc_log(card->ctx, "Could not decode card verifiable certificate");
1640
    LOG_FUNC_RETURN(card->ctx, r);
1641
  }
1642
1643
  cvc->signaturelen = signaturebits / 8;
1644
1645
  if (roleIDder.len != 1)
1646
    LOG_TEST_RET(card->ctx, SC_ERROR_SM_AUTHENTICATION_FAILED, "roleID wrong length");
1647
1648
  cvc->roleID = *roleIDder.value;
1649
1650
  /* save body der for verification */
1651
  buf_tmp = *buf;
1652
  r = sc_asn1_read_tag(&buf_tmp, *buflen, &cla_out, &tag_out, &taglen);
1653
  LOG_TEST_RET(card->ctx, r, " failed to read tag");
1654
1655
  cvc->bodylen = (roleIDder.value + roleIDder.len) - buf_tmp;
1656
1657
  cvc->body = malloc(cvc->bodylen);
1658
  if (cvc->body == NULL)
1659
    return SC_ERROR_OUT_OF_MEMORY;
1660
  memcpy(cvc->body, buf_tmp, cvc->bodylen);
1661
1662
  /* save to reuse */
1663
  cvc->der.value = malloc(*buflen);
1664
  if (cvc->der.value == NULL) {
1665
    free(cvc->body);
1666
    return SC_ERROR_OUT_OF_MEMORY;
1667
  }
1668
  cvc->der.len = *buflen;
1669
  memcpy(cvc->der.value, *buf, cvc->der.len);
1670
1671
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
1672
}
1673
1674
static int
1675
piv_parse_pairing_code(sc_card_t *card, const char *option)
1676
{
1677
  size_t i;
1678
1679
  if (strlen(option) != PIV_PAIRING_CODE_LEN) {
1680
    sc_log(card->ctx, "pairing code length invalid must be %d", PIV_PAIRING_CODE_LEN);
1681
    return SC_ERROR_INVALID_ARGUMENTS;
1682
  }
1683
  for (i = 0; i < PIV_PAIRING_CODE_LEN; i++) {
1684
    if (!isdigit(option[i])) {
1685
      sc_log(card->ctx, "pairing code must be %d decimal digits", PIV_PAIRING_CODE_LEN);
1686
      return SC_ERROR_INVALID_ARGUMENTS;
1687
    }
1688
  }
1689
  return SC_SUCCESS;
1690
}
1691
#endif
1692
1693
static int
1694
piv_load_options(sc_card_t *card)
1695
2.01k
{
1696
2.01k
  int r;
1697
2.01k
  size_t i, j;
1698
2.01k
  scconf_block **found_blocks, *block;
1699
1700
#ifdef ENABLE_PIV_SM
1701
  piv_private_data_t *priv = PIV_DATA(card);
1702
  const char *option = NULL;
1703
  int piv_pairing_code_found = 0;
1704
  int piv_use_sm_found = 0;
1705
1706
  /* pairing code is 8 decimal digits and is card specific */
1707
  if ((option = getenv("PIV_PAIRING_CODE")) != NULL) {
1708
    sc_log(card->ctx, "getenv(\"PIV_PAIRING_CODE\") found");
1709
    if (piv_parse_pairing_code(card, option) == SC_SUCCESS) {
1710
      memcpy(priv->pairing_code, option, PIV_PAIRING_CODE_LEN);
1711
      piv_pairing_code_found = 1;
1712
    }
1713
  }
1714
1715
  if ((option = getenv("PIV_USE_SM")) != NULL) {
1716
    sc_log(card->ctx, "getenv(\"PIV_USE_SM\")=\"%s\"", option);
1717
    if (!strcmp(option, "never")) {
1718
      priv->sm_flags |= PIV_SM_FLAGS_NEVER;
1719
      piv_use_sm_found = 1;
1720
    } else if (!strcmp(option, "always")) {
1721
      priv->sm_flags |= PIV_SM_FLAGS_ALWAYS;
1722
      piv_use_sm_found = 1;
1723
    } else {
1724
      sc_log(card->ctx, "Invalid piv_use_sm: \"%s\"", option);
1725
    }
1726
  }
1727
#endif
1728
1729
4.03k
  for (i = 0; card->ctx->conf_blocks[i]; i++) {
1730
2.01k
    found_blocks = scconf_find_blocks(card->ctx->conf, card->ctx->conf_blocks[i],
1731
2.01k
        "card_driver", "PIV-II");
1732
2.01k
    if (!found_blocks)
1733
0
      continue;
1734
1735
2.01k
    for (j = 0, block = found_blocks[j]; block; j++, block = found_blocks[j]) {
1736
1737
#ifdef ENABLE_PIV_SM
1738
      /*
1739
       * "piv_use_sm" if card supports NIST sp800-73-4 sm, when should it be used
1740
       * never - use card like 800-73-3, i.e. contactless is very limited on
1741
       * true PIV cards. Some  PIV-like" card may allow this.
1742
       * this security risk
1743
       * always - Use even for contact interface.
1744
       * PINS, crypto and reading of object will not show up in logs
1745
       * or over network.
1746
       */
1747
1748
      if (piv_use_sm_found == 0) {
1749
        option = scconf_get_str(block, "piv_use_sm", "default");
1750
        sc_log(card->ctx, "conf: \"piv_use_sm\"=\"%s\"", option);
1751
        if (!strcmp(option, "default")) {
1752
          /* no new flags */
1753
        } else if (!strcmp(option, "never")) {
1754
          priv->sm_flags |= PIV_SM_FLAGS_NEVER;
1755
        } else if (!strcmp(option, "always")) {
1756
          priv->sm_flags |= PIV_SM_FLAGS_ALWAYS;
1757
        } else {
1758
          sc_log(card->ctx, "Invalid piv_use_sm: \"%s\"", option);
1759
        }
1760
      }
1761
1762
      /* This is really a card specific value and should not be in the conf file */
1763
      if (piv_pairing_code_found == 0) {
1764
        option = scconf_get_str(block, "piv_pairing_code", NULL);
1765
        if (option && piv_parse_pairing_code(card, option) == SC_SUCCESS) {
1766
          memcpy(priv->pairing_code, option, PIV_PAIRING_CODE_LEN);
1767
        }
1768
      }
1769
#endif
1770
0
    }
1771
2.01k
    free(found_blocks);
1772
2.01k
  }
1773
2.01k
  r = SC_SUCCESS;
1774
2.01k
  return r;
1775
2.01k
}
1776
1777
static int
1778
piv_find_obj_by_containerid(sc_card_t *card, const u8 *str)
1779
90
{
1780
90
  int i;
1781
1782
90
  LOG_FUNC_CALLED(card->ctx);
1783
90
  sc_log(card->ctx, "str=0x%02X%02X\n", str[0], str[1]);
1784
1785
615
  for (i = 0; piv_objects[i].enumtag < PIV_OBJ_LAST_ENUM; i++) {
1786
615
    if (str[0] == piv_objects[i].containerid[0] && str[1] == piv_objects[i].containerid[1])
1787
615
      LOG_FUNC_RETURN(card->ctx, i);
1788
615
  }
1789
1790
0
  LOG_FUNC_RETURN(card->ctx, -1);
1791
0
}
1792
1793
/*
1794
 * Send a command and receive data. There is always something to send.
1795
 * Used by  GET DATA, PUT DATA, GENERAL AUTHENTICATE
1796
 * and GENERATE ASYMMETRIC KEY PAIR.
1797
 */
1798
1799
static int
1800
piv_general_io(sc_card_t *card, int ins, int p1, int p2,
1801
    const u8 *sendbuf, size_t sendbuflen, u8 *recvbuf,
1802
    size_t recvbuflen)
1803
46.2k
{
1804
46.2k
  int r, cse;
1805
46.2k
  sc_apdu_t apdu;
1806
1807
46.2k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1808
1809
46.2k
  r = sc_lock(card);
1810
46.2k
  if (r != SC_SUCCESS)
1811
46.2k
    LOG_FUNC_RETURN(card->ctx, r);
1812
1813
46.2k
  cse = recvbuf ? (sendbuf ? SC_APDU_CASE_4_SHORT : SC_APDU_CASE_2_SHORT) :
1814
46.2k
      (sendbuf ? SC_APDU_CASE_3_SHORT : SC_APDU_CASE_1);
1815
1816
46.2k
  sc_format_apdu(card, &apdu, cse, ins, p1, p2);
1817
46.2k
  if (sendbuflen > 255) {
1818
91
    apdu.flags |= SC_APDU_FLAGS_CHAINING;
1819
#ifdef ENABLE_PIV_SM
1820
    if (card->sm_ctx.sm_mode != SM_MODE_NONE) {
1821
      /* tell apdu.c to not do the chaining, let the SM get_apdu do it */
1822
      apdu.flags |= SC_APDU_FLAGS_SM_CHAINING;
1823
    }
1824
#endif
1825
91
  }
1826
46.2k
  apdu.lc = sendbuflen;
1827
46.2k
  apdu.datalen = sendbuflen;
1828
46.2k
  apdu.data = sendbuf;
1829
1830
46.2k
  if (recvbuf && recvbuflen) {
1831
46.1k
    apdu.le = (recvbuflen > 256) ? 256 : recvbuflen;
1832
46.1k
    apdu.resplen = recvbuflen;
1833
46.1k
  } else {
1834
93
    apdu.le = 0;
1835
93
    apdu.resplen = 0;
1836
93
  }
1837
46.2k
  apdu.resp = recvbuf;
1838
1839
  /* with new adpu.c and chaining, this actually reads the whole object */
1840
46.2k
  r = sc_transmit_apdu(card, &apdu);
1841
1842
  /* adpu will not have sw1,sw2 set because sc_sm_single_transmit called sc_sm_stop, */
1843
46.2k
  if (r < 0) {
1844
7.92k
    sc_log(card->ctx, "Transmit failed");
1845
7.92k
    goto err;
1846
7.92k
  }
1847
1848
38.3k
  if (apdu.sw1 == 0x69 && apdu.sw2 == 0x88)
1849
35
    r = SC_ERROR_SM_INVALID_SESSION_KEY;
1850
38.2k
  else
1851
38.2k
    r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1852
1853
38.3k
  if (r < 0) {
1854
32.2k
    sc_log(card->ctx, "Card returned error ");
1855
32.2k
    goto err;
1856
32.2k
  }
1857
1858
6.07k
  r = (int)apdu.resplen;
1859
1860
46.2k
err:
1861
46.2k
  sc_unlock(card);
1862
46.2k
  LOG_FUNC_RETURN(card->ctx, r);
1863
46.2k
}
1864
1865
#ifdef ENABLE_PIV_SM
1866
/* convert q as 04||x||y used in standard point formats to expanded leading
1867
 * zeros and concatenated X||Y as specified in SP80056A Appendix C.2
1868
 * Field-Element-to-Byte-String Conversion which
1869
 * OpenSSL has already converted X and Y to big endian and skipped leading
1870
 * zero bytes.
1871
 */
1872
static int
1873
Q2OS(int fsize, u8 *Q, size_t Qlen, u8 *OS, size_t *OSlen)
1874
{
1875
  size_t i;
1876
  size_t f = fsize / 8;
1877
1878
  i = (Qlen - 1) / 2;
1879
1880
  if (!OS || *OSlen < f * 2 || !Q || i > f)
1881
    return SC_ERROR_INTERNAL;
1882
1883
  memset(OS, 0, f * 2);
1884
  /* Check this if x and y have leading zero bytes,
1885
   * In UNCOMPRESSED FORMAT, x and Y must be same length, to tell when
1886
   * one ends and the other starts */
1887
  memcpy(OS + f - i, Q + 1, i);
1888
  memcpy(OS + 2 * f - i, Q + f + 1, i);
1889
  *OSlen = f * 2;
1890
  return 0;
1891
}
1892
1893
/*
1894
 * if needed, send VCI pairing code to card just after the
1895
 * SM key establishment. Called from piv_sm_open under same lock
1896
 */
1897
static int
1898
piv_send_vci_pairing_code(struct sc_card *card, u8 *paring_code)
1899
{
1900
  int r;
1901
  piv_private_data_t *priv = PIV_DATA(card);
1902
  sc_apdu_t plain;
1903
  sc_apdu_t sm_apdu;
1904
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1905
1906
  if (priv->pin_policy & PIV_PP_VCI_WITHOUT_PC)
1907
    SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_SUCCESS); /* Not needed */
1908
1909
  if ((priv->pin_policy & PIV_PP_VCI_IMPL) == 0)
1910
    SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_NO_CARD_SUPPORT);
1911
1912
  sc_format_apdu(card, &plain, SC_APDU_CASE_3_SHORT, 0x20, 0x00, 0x98);
1913
  plain.datalen = plain.lc = 8;
1914
  plain.data = paring_code;
1915
  plain.resp = NULL;
1916
  plain.resplen = plain.le = 0;
1917
1918
  memset(&sm_apdu, 0, sizeof(sm_apdu));
1919
  /* build sm_apdu and set alloc sm_apdu.resp */
1920
  r = piv_encode_apdu(card, &plain, &sm_apdu);
1921
  if (r < 0) {
1922
    free(sm_apdu.resp);
1923
    sc_log(card->ctx, "piv_encode_apdu failed");
1924
    LOG_FUNC_RETURN(card->ctx, r);
1925
  }
1926
1927
  sm_apdu.flags += SC_APDU_FLAGS_NO_SM; /* run as is */
1928
  r = sc_transmit_apdu(card, &sm_apdu);
1929
  if (r < 0) {
1930
    free(sm_apdu.resp);
1931
    sc_log(card->ctx, "transmit failed");
1932
    LOG_FUNC_RETURN(card->ctx, r);
1933
  }
1934
1935
  r = piv_decode_apdu(card, &plain, &sm_apdu);
1936
  free(sm_apdu.resp);
1937
  LOG_TEST_RET(card->ctx, r, "piv_decode_apdu failed");
1938
1939
  r = sc_check_sw(card, plain.sw1, plain.sw2);
1940
  if (r < 0)
1941
    r = SC_ERROR_PIN_CODE_INCORRECT;
1942
1943
  LOG_FUNC_RETURN(card->ctx, r);
1944
}
1945
1946
/* Verify one signature using pubkey */
1947
static int
1948
piv_sm_verify_sig(struct sc_card *card, const EVP_MD *type,
1949
    EVP_PKEY *pkey,
1950
    u8 *data, size_t data_size,
1951
    unsigned char *sig, size_t siglen)
1952
{
1953
  piv_private_data_t *priv = PIV_DATA(card);
1954
  cipher_suite_t *cs = priv->cs;
1955
  int r = 0;
1956
  EVP_MD_CTX *md_ctx = NULL;
1957
1958
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1959
1960
  if (cs == NULL) {
1961
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
1962
    goto err;
1963
  }
1964
1965
  if ((md_ctx = EVP_MD_CTX_new()) == NULL ||
1966
      EVP_DigestVerifyInit(md_ctx, NULL, type, NULL, pkey) != 1 ||
1967
      EVP_DigestVerifyUpdate(md_ctx, data, data_size) != 1 ||
1968
      EVP_DigestVerifyFinal(md_ctx, sig, siglen) != 1) {
1969
    sc_log_openssl(card->ctx);
1970
    sc_log(card->ctx, "EVP_DigestVerifyFinal failed");
1971
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
1972
    goto err;
1973
  }
1974
  r = SC_SUCCESS;
1975
err:
1976
  EVP_MD_CTX_free(md_ctx);
1977
  LOG_FUNC_RETURN(card->ctx, r);
1978
}
1979
1980
/*
1981
 * If sm_in_cvc is present, verify PIV_OBJ_SM_CERT_SIGNER signed sm_in_cvc
1982
 * and sm_in_cvc signed sm_cvc.
1983
 * If sm_in_cvc is not present verify PIV_OBJ_SM_CERT_SIGNER signed sm_cvc.
1984
 */
1985
1986
static int
1987
piv_sm_verify_certs(struct sc_card *card)
1988
{
1989
  piv_private_data_t *priv = PIV_DATA(card);
1990
  cipher_suite_t *cs = priv->cs;
1991
  int r = 0;
1992
  u8 *cert_blob_unzipped = NULL; /* free */
1993
  u8 *cert_blob = NULL;        /* do not free */
1994
  size_t cert_bloblen = 0;
1995
1996
  u8 *rbuf; /* do not free*/
1997
  size_t rbuflen;
1998
  X509 *cert = NULL;
1999
  EVP_PKEY *cert_pkey = NULL; /* do not free */
2000
  EVP_PKEY *in_cvc_pkey = NULL;
2001
#if OPENSSL_VERSION_NUMBER < 0x30000000L
2002
  EC_GROUP *in_cvc_group = NULL;
2003
  EC_POINT *in_cvc_point = NULL;
2004
  EC_KEY *in_cvc_eckey = NULL;
2005
#else
2006
  EVP_PKEY_CTX *in_cvc_pkey_ctx = NULL;
2007
  OSSL_PARAM params[3];
2008
  size_t params_n;
2009
#endif
2010
2011
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
2012
2013
  if (cs == NULL) {
2014
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2015
    goto err;
2016
  }
2017
2018
  /*
2019
   * Get the PIV_OBJ_SM_CERT_SIGNER and optional sm_in_cvc in cache
2020
   * both are in same object. Rbuf, and rbuflen are needed but not used here
2021
   * sm_cvc and sm_in_cvc both have EC_keys sm_in_cvc may have RSA signature
2022
   */
2023
  r = piv_get_cached_data(card, PIV_OBJ_SM_CERT_SIGNER, &rbuf, &rbuflen);
2024
  if (r < 0) {
2025
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2026
    goto err;
2027
  }
2028
  r = piv_cache_internal_data(card, PIV_OBJ_SM_CERT_SIGNER);
2029
  if (r < 0) {
2030
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2031
    goto err;
2032
  }
2033
2034
  priv->sm_flags |= PIV_SM_FLAGS_SM_CERT_SIGNER_PRESENT; /* set for debugging */
2035
2036
  /* get PIV_OBJ_SM_CERT_SIGNER cert DER  from cache */
2037
  if (priv->obj_cache[PIV_OBJ_SM_CERT_SIGNER].flags & PIV_OBJ_CACHE_COMPRESSED) {
2038
#ifdef ENABLE_ZLIB
2039
    if (SC_SUCCESS != sc_decompress_alloc(&cert_blob_unzipped, &cert_bloblen,
2040
              priv->obj_cache[PIV_OBJ_SM_CERT_SIGNER].internal_obj_data,
2041
              priv->obj_cache[PIV_OBJ_SM_CERT_SIGNER].internal_obj_len,
2042
              COMPRESSION_AUTO)) {
2043
      sc_log(card->ctx, "PIV decompression of SM CERT_SIGNER failed");
2044
      r = SC_ERROR_OBJECT_NOT_VALID;
2045
      goto err;
2046
    }
2047
    cert_blob = cert_blob_unzipped;
2048
#else
2049
    sc_log(card->ctx, "PIV compression not supported, no zlib");
2050
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
2051
#endif
2052
2053
  } else {
2054
    cert_blob = priv->obj_cache[PIV_OBJ_SM_CERT_SIGNER].internal_obj_data;
2055
    cert_bloblen = priv->obj_cache[PIV_OBJ_SM_CERT_SIGNER].internal_obj_len;
2056
  }
2057
2058
  if (cert_blob == NULL || cert_bloblen == 0) {
2059
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2060
    goto err;
2061
  }
2062
2063
  if ((cert = d2i_X509(NULL, (const u8 **)&cert_blob, cert_bloblen)) == NULL ||
2064
      (cert_pkey = X509_get0_pubkey(cert)) == NULL) {
2065
    sc_log_openssl(card->ctx);
2066
    sc_log(card->ctx, "OpenSSL failed to get pubkey from SM_CERT_SIGNER");
2067
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2068
    goto err;
2069
  }
2070
2071
  /* if intermediate sm_in_cvc present, cert signed it and sm_cvc is signed by sm_in_cvc */
2072
  if (priv->sm_flags & PIV_SM_FLAGS_SM_IN_CVC_PRESENT) {
2073
    r = piv_sm_verify_sig(card, cs->kdf_md(), cert_pkey,
2074
        priv->sm_in_cvc.body, priv->sm_in_cvc.bodylen,
2075
        priv->sm_in_cvc.signature, priv->sm_in_cvc.signaturelen);
2076
    if (r < 0) {
2077
      sc_log(card->ctx, "sm_in_cvc signature invalid");
2078
      r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2079
      goto err;
2080
    }
2081
2082
#if OPENSSL_VERSION_NUMBER < 0x30000000L
2083
    if ((in_cvc_group = EC_GROUP_new_by_curve_name(cs->nid)) == NULL ||
2084
        (in_cvc_pkey = EVP_PKEY_new()) == NULL ||
2085
        (in_cvc_eckey = EC_KEY_new_by_curve_name(cs->nid)) == NULL ||
2086
        (in_cvc_point = EC_POINT_new(in_cvc_group)) == NULL ||
2087
        EC_POINT_oct2point(in_cvc_group, in_cvc_point,
2088
            priv->sm_in_cvc.publicPoint, priv->sm_in_cvc.publicPointlen, NULL) <= 0 ||
2089
        EC_KEY_set_public_key(in_cvc_eckey, in_cvc_point) <= 0 ||
2090
        EVP_PKEY_set1_EC_KEY(in_cvc_pkey, in_cvc_eckey) != 1) {
2091
      sc_log_openssl(card->ctx);
2092
      sc_log(card->ctx, "OpenSSL failed to set EC pubkey, during verify");
2093
      r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2094
      goto err;
2095
    }
2096
#else
2097
    params_n = 0;
2098
    params[params_n++] = OSSL_PARAM_construct_utf8_string("group", cs->curve_group, 0);
2099
    params[params_n++] = OSSL_PARAM_construct_octet_string("pub",
2100
        priv->sm_in_cvc.publicPoint, priv->sm_in_cvc.publicPointlen);
2101
    params[params_n] = OSSL_PARAM_construct_end();
2102
2103
    if (!(in_cvc_pkey_ctx = EVP_PKEY_CTX_new_from_name(PIV_LIBCTX, "EC", NULL)) ||
2104
        !EVP_PKEY_fromdata_init(in_cvc_pkey_ctx) ||
2105
        !EVP_PKEY_fromdata(in_cvc_pkey_ctx, &in_cvc_pkey, EVP_PKEY_PUBLIC_KEY, params) ||
2106
        !in_cvc_pkey) {
2107
      sc_log_openssl(card->ctx);
2108
      sc_log(card->ctx, "OpenSSL failed to set EC pubkey, during verify");
2109
      r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2110
      goto err;
2111
    }
2112
#endif
2113
    r = piv_sm_verify_sig(card, cs->kdf_md(), in_cvc_pkey,
2114
        priv->sm_cvc.body, priv->sm_cvc.bodylen,
2115
        priv->sm_cvc.signature, priv->sm_cvc.signaturelen);
2116
2117
  } else { /* cert signed  sm_cvc */
2118
    r = piv_sm_verify_sig(card, cs->kdf_md(), cert_pkey,
2119
        priv->sm_cvc.body, priv->sm_cvc.bodylen,
2120
        priv->sm_cvc.signature, priv->sm_cvc.signaturelen);
2121
  }
2122
  if (r < 0) {
2123
    sc_log(card->ctx, "sm_cvc signature invalid");
2124
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2125
    goto err;
2126
  }
2127
2128
  /* cert chain signatures match for oncard certs */
2129
2130
err:
2131
  X509_free(cert);
2132
  free(cert_blob_unzipped);
2133
2134
#if OPENSSL_VERSION_NUMBER < 0x30000000L
2135
  EC_GROUP_free(in_cvc_group);
2136
  EC_POINT_free(in_cvc_point);
2137
  EC_KEY_free(in_cvc_eckey);
2138
#else
2139
  EVP_PKEY_CTX_free(in_cvc_pkey_ctx);
2140
#endif
2141
  EVP_PKEY_free(in_cvc_pkey);
2142
  SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
2143
}
2144
2145
/*
2146
 * NIST SP800-73-4  4.1 The key Establishment Protocol
2147
 * Variable names and Steps  are based on Client Application (h)
2148
 * and PIV Card Application (icc)
2149
 * Capital leters used for variable, and lower case for subscript names
2150
 */
2151
static int
2152
piv_sm_open(struct sc_card *card)
2153
{
2154
  piv_private_data_t *priv = PIV_DATA(card);
2155
  cipher_suite_t *cs = priv->cs;
2156
  int r = 0;
2157
  int i;
2158
  int reps;
2159
  u8 CBh;
2160
  u8 CBicc;
2161
  u8 *p;
2162
2163
  /* ephemeral EC key */
2164
  EVP_PKEY_CTX *eph_ctx = NULL;
2165
  EVP_PKEY *eph_pkey = NULL;
2166
#if OPENSSL_VERSION_NUMBER < 0x30000000L
2167
  EC_KEY *eph_eckey = NULL;   /* don't free _get0_*/
2168
  const EC_GROUP *eph_group = NULL; /* don't free _get0_ */
2169
#else
2170
  OSSL_PARAM eph_params[5];
2171
  size_t eph_params_n;
2172
  size_t Qehxlen = 0;
2173
  u8 *Qehx = NULL;
2174
#endif
2175
  size_t Qehlen = 0;
2176
  u8 Qeh[2 * PIV_SM_MAX_FIELD_LENGTH / 8 + 1]; /*  big enough for 384 04||x||y  if x and y have leading zeros, length may be less */
2177
  size_t Qeh_OSlen = 0;
2178
  u8 Qeh_OS[2 * PIV_SM_MAX_FIELD_LENGTH / 8]; /* no leading 04, with leading zeros in X and Y */
2179
  size_t Qsicc_OSlen = 0;
2180
  u8 Qsicc_OS[2 * PIV_SM_MAX_FIELD_LENGTH / 8]; /* no leading 04, with leading zeros  in X and Y */
2181
2182
  /* pub EC key from card Cicc in sm_cvc */
2183
  EVP_PKEY_CTX *Cicc_ctx = NULL;
2184
  EVP_PKEY *Cicc_pkey = NULL;
2185
#if OPENSSL_VERSION_NUMBER < 0x30000000L
2186
  EC_KEY *Cicc_eckey = NULL;
2187
  EC_POINT *Cicc_point = NULL;
2188
  EC_GROUP *Cicc_group = NULL;
2189
#endif
2190
2191
  /* shared secret key Z */
2192
  EVP_PKEY_CTX *Z_ctx = NULL;
2193
  u8 *Z = NULL;
2194
  size_t Zlen = 0;
2195
2196
  u8 IDsh[8] = {0};
2197
  unsigned long pid;
2198
2199
  u8 *sbuf = NULL;
2200
  size_t sbuflen;
2201
  int len2a, len2b;
2202
2203
  u8 rbuf[4096];
2204
  size_t rbuflen = sizeof(rbuf);
2205
2206
  const u8 *body, *payload;
2207
  size_t bodylen, payloadlen;
2208
  u8 Nicc[24]; /* nonce */
2209
  u8 AuthCryptogram[16];
2210
2211
  u8 *cvcder = NULL;
2212
  size_t cvclen = 0;
2213
  size_t len; /* temp len */
2214
2215
  u8 *kdf_in = NULL;
2216
  size_t kdf_inlen = 0;
2217
  unsigned int hashlen = 0;
2218
  u8 aeskeys[SHA384_DIGEST_LENGTH * 3] = {0}; /*  4 keys, Hash function is run 2 or 3 times max is 3 * 384/8 see below */
2219
  EVP_MD_CTX *hash_ctx = NULL;
2220
#if OPENSSL_VERSION_NUMBER < 0x30000000L
2221
  CMAC_CTX *cmac_ctx = NULL;
2222
#else
2223
  EVP_MAC *mac = NULL;
2224
  EVP_MAC_CTX *cmac_ctx = NULL;
2225
  OSSL_PARAM cmac_params[2];
2226
  size_t cmac_params_n = 0;
2227
  OSSL_PARAM Cicc_params[3];
2228
  size_t Cicc_params_n = 0;
2229
#endif
2230
2231
  u8 IDsicc[8]; /* will only use 8 bytes for step H6 */
2232
2233
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
2234
2235
  /*
2236
   * The SM routines try and call this on their own.
2237
   * This routine should only be called by the card driver.
2238
   * which has set PIV_SM_FLAGS_DEFER_OPEN and unset in
2239
   * in reader_lock_obtained
2240
   * after testing PIC applet is active so SM is setup in same transaction
2241
   * as the command we are trying to run with SM.
2242
   * this avoids situation where the SM is established, and then reset by
2243
   * some other application without getting anything done or in
2244
   * a loop, each trying to reestablish a SM session and run command.
2245
   */
2246
  if (!(priv->sm_flags & PIV_SM_FLAGS_DEFER_OPEN)) {
2247
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ALLOWED);
2248
  }
2249
  if (cs == NULL)
2250
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
2251
2252
  r = sc_lock(card);
2253
  if (r != SC_SUCCESS) {
2254
    sc_log(card->ctx, "sc_lock failed");
2255
    return r;
2256
  }
2257
2258
  /* use for several hash operations */
2259
  if ((hash_ctx = EVP_MD_CTX_new()) == NULL) {
2260
    r = SC_ERROR_OUT_OF_MEMORY;
2261
    goto err;
2262
  }
2263
2264
  /* Step 1 set CBh = 0 */
2265
  CBh = 0;
2266
2267
  /* Step H2 generate ephemeral EC */
2268
2269
#if OPENSSL_VERSION_NUMBER < 0x30000000L
2270
  if ((eph_ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL)) == NULL ||
2271
      EVP_PKEY_keygen_init(eph_ctx) <= 0 ||
2272
      EVP_PKEY_CTX_set_ec_paramgen_curve_nid(eph_ctx, cs->nid) <= 0 ||
2273
      EVP_PKEY_keygen(eph_ctx, &eph_pkey) <= 0 ||
2274
      (eph_eckey = EVP_PKEY_get0_EC_KEY(eph_pkey)) == NULL ||
2275
      (eph_group = EC_KEY_get0_group(eph_eckey)) == NULL ||
2276
      (Qehlen = EC_POINT_point2oct(eph_group, EC_KEY_get0_public_key(eph_eckey),
2277
           POINT_CONVERSION_UNCOMPRESSED, NULL, Qehlen, NULL)) <= 0 || /* get length */
2278
      Qehlen > cs->Qlen ||
2279
      (Qehlen = EC_POINT_point2oct(eph_group, EC_KEY_get0_public_key(eph_eckey),
2280
           POINT_CONVERSION_UNCOMPRESSED, Qeh, Qehlen, NULL)) <= 0 ||
2281
      Qehlen > cs->Qlen) {
2282
    sc_log_openssl(card->ctx);
2283
    sc_log(card->ctx, "OpenSSL failed to create ephemeral EC key");
2284
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2285
    goto err;
2286
  }
2287
#else
2288
  /* generate Qeh */
2289
  eph_params_n = 0;
2290
  eph_params[eph_params_n++] = OSSL_PARAM_construct_utf8_string("group", cs->curve_group, 0);
2291
  eph_params[eph_params_n++] = OSSL_PARAM_construct_utf8_string("point-format", "uncompressed", 0);
2292
  eph_params[eph_params_n] = OSSL_PARAM_construct_end();
2293
  if (!(eph_ctx = EVP_PKEY_CTX_new_from_name(PIV_LIBCTX, "EC", NULL)) ||
2294
      !EVP_PKEY_keygen_init(eph_ctx) ||
2295
      !EVP_PKEY_CTX_set_params(eph_ctx, eph_params) ||
2296
      !EVP_PKEY_generate(eph_ctx, &eph_pkey) ||
2297
      !(Qehxlen = EVP_PKEY_get1_encoded_public_key(eph_pkey, &Qehx)) ||
2298
      !Qehx ||
2299
      Qehxlen > cs->Qlen) {
2300
    sc_log_openssl(card->ctx);
2301
    sc_log(card->ctx, "OpenSSL failed to create ephemeral EC key");
2302
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2303
    goto err;
2304
  }
2305
  memcpy(Qeh, Qehx, Qehxlen);
2306
  Qehlen = Qehxlen;
2307
#endif
2308
2309
  /* For later use, get  Qeh without 04 and full size  X || Y */
2310
  Qeh_OSlen = sizeof(Qeh_OS);
2311
  if (Q2OS(cs->field_length, Qeh, Qehlen, Qeh_OS, &Qeh_OSlen)) {
2312
    sc_log(card->ctx, "Q2OS for Qeh failed");
2313
    r = SC_ERROR_INTERNAL;
2314
    goto err;
2315
  }
2316
2317
  r = len2a = sc_asn1_put_tag(0x81, NULL, 1 + sizeof(IDsh) + Qehlen, NULL, 0, NULL);
2318
  if (r < 0)
2319
    goto err;
2320
  r = len2b = sc_asn1_put_tag(0x80, NULL, 0, NULL, 0, NULL);
2321
  if (r < 0)
2322
    goto err;
2323
  r = sc_asn1_put_tag(0x7C, NULL, len2a + len2b, NULL, 0, NULL);
2324
  if (r < 0)
2325
    goto err;
2326
  sbuflen = r;
2327
2328
  sbuf = malloc(sbuflen);
2329
  if (sbuf == NULL) {
2330
    r = SC_ERROR_OUT_OF_MEMORY;
2331
    goto err;
2332
  }
2333
  p = sbuf;
2334
2335
  r = sc_asn1_put_tag(0x7C, NULL, len2a + len2b, sbuf, sbuflen, &p);
2336
  if (r != SC_SUCCESS)
2337
    goto err;
2338
2339
  r = sc_asn1_put_tag(0x81, NULL, 1 + sizeof(IDsh) + Qehlen, p, sbuflen - (p - sbuf), &p);
2340
  if (r != SC_SUCCESS)
2341
    goto err;
2342
2343
  /* Step H1 set CBh to 0x00 */
2344
  *p++ = CBh;
2345
2346
#ifdef WIN32
2347
  pid = (unsigned long)GetCurrentProcessId();
2348
#else
2349
  pid = (unsigned long)getpid(); /* use PID as our ID so different from other processes */
2350
#endif
2351
  memcpy(IDsh, &pid, MIN(sizeof(pid), sizeof(IDsh)));
2352
  memcpy(p, IDsh, sizeof(IDsh));
2353
  p += sizeof(IDsh);
2354
  memcpy(p, Qeh, Qehlen);
2355
  p += Qehlen;
2356
2357
  r = sc_asn1_put_tag(0x82, NULL, 0, p, sbuflen - (p - sbuf), &p); /* null data */
2358
  if (r != SC_SUCCESS)
2359
    goto err;
2360
2361
  /* Step H3 send CBh||IDsh|| Qeh  Qeh in 04||x||y */
2362
  /* Or call sc_transmit directly */
2363
  r = piv_general_io(card, 0x87, cs->p1, 0x04, sbuf, (p - sbuf), rbuf, rbuflen);
2364
  if (r <= 0)
2365
    goto err;
2366
2367
  rbuflen = r;
2368
  p = rbuf;
2369
2370
  body = sc_asn1_find_tag(card->ctx, rbuf, rbuflen, 0x7C, &bodylen);
2371
  if (body == NULL || bodylen < 20 || rbuf[0] != 0x7C) {
2372
    sc_log(card->ctx, "SM response data to short");
2373
    r = SC_ERROR_SM_NO_SESSION_KEYS;
2374
    goto err;
2375
  }
2376
2377
  payload = sc_asn1_find_tag(card->ctx, body, bodylen, 0x82, &payloadlen);
2378
  if (payload == NULL || payloadlen < 1 + cs->Nicclen + cs->AuthCryptogramlen || *body != 0x82) {
2379
    sc_log(card->ctx, "SM response data to short");
2380
    r = SC_ERROR_SM_NO_SESSION_KEYS;
2381
    goto err;
2382
  }
2383
2384
  /* payload is CBicc (1) || Nicc (16 or 24) || AuthCryptogram (CMAC 16 or 16) ||Cicc (variable) */
2385
  p = (u8 *)payload;
2386
2387
  /* Step H4 check CBicc == 0x00 */
2388
  CBicc = *p++;
2389
  if (CBicc != 0x00) { /* CBicc must be  zero */
2390
    sc_log(card->ctx, "SM card did not accept request");
2391
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2392
    goto err;
2393
  }
2394
2395
  memcpy(Nicc, p, cs->Nicclen);
2396
  p += cs->Nicclen;
2397
2398
  memcpy(AuthCryptogram, p, cs->AuthCryptogramlen);
2399
  p += cs->AuthCryptogramlen;
2400
2401
  if (p > payload + payloadlen) {
2402
    sc_log(card->ctx, "SM card CVC is to short");
2403
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2404
    goto err;
2405
  }
2406
  cvclen = len = payloadlen - (p - payload);
2407
  if (len) {
2408
    cvcder = p; /* in rbuf */
2409
2410
    r = piv_decode_cvc(card, &p, &len, &priv->sm_cvc);
2411
    if (r != SC_SUCCESS) {
2412
      r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2413
      goto err;
2414
    }
2415
    priv->sm_flags |= PIV_SM_FLAGS_SM_CVC_PRESENT;
2416
  }
2417
2418
  /* Step H5 Verify Cicc CVC and pubkey */
2419
  /* Verify Cicc (sm_cvc) is signed by sm_in_cvc or PIV_OBJ_SM_CERT_SIGNER  */
2420
  /* sm_in_cvc is signed by PIV_OBJ_SM_CERT_SIGNER */
2421
2422
  /* Verify the cert chain is valid. */
2423
  r = piv_sm_verify_certs(card);
2424
  if (r < 0) {
2425
    sc_log(card->ctx, "SM  piv_sm_verify_certs r:%d", r);
2426
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2427
    goto err;
2428
  }
2429
2430
  /* Step H6  need left most 8 bytes of hash of sm_cvc */
2431
  {
2432
    u8 hash[SHA256_DIGEST_LENGTH] = {0};
2433
    const u8 *tag;
2434
    size_t taglen;
2435
    const u8 *tmpder;
2436
    size_t tmpderlen;
2437
2438
    if ((tag = sc_asn1_find_tag(card->ctx, cvcder, cvclen, 0x7F21, &taglen)) == NULL ||
2439
        *cvcder != 0x7F || *(cvcder + 1) != 0x21) {
2440
2441
      r = SC_ERROR_INTERNAL;
2442
      goto err;
2443
    }
2444
2445
    /* debug choice */
2446
    tmpder = cvcder;
2447
    tmpderlen = cvclen;
2448
2449
    if (EVP_DigestInit(hash_ctx, EVP_sha256()) != 1 ||
2450
        EVP_DigestUpdate(hash_ctx, tmpder, tmpderlen) != 1 ||
2451
        EVP_DigestFinal_ex(hash_ctx, hash, NULL) != 1) {
2452
      sc_log_openssl(card->ctx);
2453
      sc_log(card->ctx, "IDsicc hash failed");
2454
      r = SC_ERROR_INTERNAL;
2455
      goto err;
2456
    }
2457
    memcpy(IDsicc, hash, sizeof(IDsicc)); /* left 8 bytes */
2458
  }
2459
2460
  /* Step H7 get the cards public key Qsicc into OpenSSL Cicc_eckey */
2461
2462
#if OPENSSL_VERSION_NUMBER < 0x30000000L
2463
  if ((Cicc_ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL)) == NULL ||
2464
      (Cicc_group = EC_GROUP_new_by_curve_name(cs->nid)) == NULL ||
2465
      (Cicc_pkey = EVP_PKEY_new()) == NULL ||
2466
      (Cicc_eckey = EC_KEY_new_by_curve_name(cs->nid)) == NULL ||
2467
      (Cicc_point = EC_POINT_new(Cicc_group)) == NULL ||
2468
      EC_POINT_oct2point(Cicc_group, Cicc_point,
2469
          priv->sm_cvc.publicPoint, priv->sm_cvc.publicPointlen, NULL) <= 0 ||
2470
      EC_KEY_set_public_key(Cicc_eckey, Cicc_point) <= 0 ||
2471
      EVP_PKEY_set1_EC_KEY(Cicc_pkey, Cicc_eckey) <= 0) {
2472
    sc_log_openssl(card->ctx);
2473
    sc_log(card->ctx, "OpenSSL failed to get card's EC pubkey");
2474
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2475
    goto err;
2476
  }
2477
#else
2478
  Cicc_params_n = 0;
2479
  Cicc_params[Cicc_params_n++] = OSSL_PARAM_construct_utf8_string("group", cs->curve_group, 0);
2480
  Cicc_params[Cicc_params_n++] = OSSL_PARAM_construct_octet_string("pub",
2481
      priv->sm_cvc.publicPoint, priv->sm_cvc.publicPointlen);
2482
  Cicc_params[Cicc_params_n] = OSSL_PARAM_construct_end();
2483
2484
  if (!(Cicc_ctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL)) ||
2485
      !EVP_PKEY_fromdata_init(Cicc_ctx) ||
2486
      !EVP_PKEY_fromdata(Cicc_ctx, &Cicc_pkey, EVP_PKEY_PUBLIC_KEY, Cicc_params) ||
2487
      !Cicc_pkey) {
2488
    sc_log_openssl(card->ctx);
2489
    sc_log(card->ctx, "OpenSSL failed to set EC pubkey for Cicc");
2490
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2491
    goto err;
2492
  }
2493
#endif
2494
2495
  /* Qsicc without 04 and expanded x||y */
2496
  Qsicc_OSlen = sizeof(Qsicc_OS);
2497
  if (Q2OS(cs->field_length, priv->sm_cvc.publicPoint, priv->sm_cvc.publicPointlen, Qsicc_OS, &Qsicc_OSlen)) {
2498
    sc_log(card->ctx, "Q2OS for Qsicc failed");
2499
    r = SC_ERROR_INTERNAL;
2500
    goto err;
2501
  }
2502
2503
  /* Step H8 Compute the shared secret Z */
2504
  if ((Z_ctx = EVP_PKEY_CTX_new(eph_pkey, NULL)) == NULL ||
2505
      EVP_PKEY_derive_init(Z_ctx) <= 0 ||
2506
      EVP_PKEY_derive_set_peer(Z_ctx, Cicc_pkey) <= 0 ||
2507
      EVP_PKEY_derive(Z_ctx, NULL, &Zlen) <= 0 ||
2508
      Zlen != cs->Zlen ||
2509
      (Z = malloc(Zlen)) == NULL ||
2510
      EVP_PKEY_derive(Z_ctx, Z, &Zlen) <= 0 ||
2511
      Zlen != cs->Zlen) {
2512
    sc_log_openssl(card->ctx);
2513
    sc_log(card->ctx, "OpenSSL failed to create secret Z");
2514
    r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2515
    goto err;
2516
  }
2517
2518
  sc_log(card->ctx, "debug Zlen:%zu Z[0]:0x%2.2x", Zlen, Z[0]);
2519
2520
  /* Step H9 zeroize deh from step H2 */
2521
  EVP_PKEY_free(eph_pkey); /* OpenSSL  BN_clear_free calls OPENSSL_cleanse */
2522
  eph_pkey = NULL;
2523
2524
  /* Step H10 Create AES session Keys */
2525
  /* kdf in is 4byte counter || Z || otherinfo  800-56A 5.8.1 */
2526
2527
  kdf_inlen = 4 + Zlen + cs->otherinfolen;
2528
  kdf_in = malloc(kdf_inlen);
2529
  if (kdf_in == NULL) {
2530
    r = SC_ERROR_OUT_OF_MEMORY;
2531
    goto err;
2532
  }
2533
  p = kdf_in;
2534
  *p++ = 0x00;
2535
  *p++ = 0x00;
2536
  *p++ = 0x00;
2537
  *p++ = 0x01;
2538
  memcpy(p, Z, cs->Zlen);
2539
  p += Zlen;
2540
2541
  /* otherinfo */
2542
  *p++ = cs->o0len;
2543
  for (i = 0; i < cs->o0len; i++)
2544
    *p++ = cs->o0_char; /* 0x09 or 0x0d */
2545
2546
  *p++ = sizeof(IDsh);
2547
  memcpy(p, IDsh, sizeof(IDsh));
2548
  p += sizeof(IDsh);
2549
2550
  *p++ = cs->CBhlen;
2551
  memcpy(p, &CBh, cs->CBhlen);
2552
  p += cs->CBhlen;
2553
2554
  *p++ = cs->T16Qehlen;
2555
  /* First 16 bytes of Qeh without 04 800-56A Appendix C.2 */
2556
  memcpy(p, Qeh_OS, cs->T16Qehlen);
2557
  p += cs->T16Qehlen;
2558
2559
  *p++ = cs->IDsicclen;
2560
  memcpy(p, IDsicc, cs->IDsicclen);
2561
  p += cs->IDsicclen;
2562
2563
  *p++ = cs->Nicclen;
2564
  memcpy(p, Nicc, cs->Nicclen);
2565
  p += cs->Nicclen;
2566
2567
  *p++ = cs->CBicclen;
2568
  memcpy(p, &CBicc, cs->CBicclen);
2569
  p += cs->CBicclen;
2570
2571
  if (p != kdf_in + kdf_inlen) {
2572
    r = SC_ERROR_INTERNAL;
2573
    goto err;
2574
  }
2575
2576
  /* 4 keys needs reps =  ceil (naeskeys * aeskeylen) / kdf_hash_size) */
2577
  /* 800-56A-2007, 5.8.1 Process and 800-56C rev 3 2018 4.1 Process. */
2578
  /* so it is 2 times for 128 or 3 times for 256 bit AES keys */
2579
  p = aeskeys; /* 4 keys + overflow */
2580
  reps = (cs->naeskeys * cs->aeskeylen + cs->kdf_hash_size - 1) / (cs->kdf_hash_size);
2581
2582
  EVP_MD_CTX_reset(hash_ctx);
2583
  for (i = 0; i < reps; i++) {
2584
    if (EVP_DigestInit(hash_ctx, (*cs->kdf_md)()) != 1 ||
2585
        EVP_DigestUpdate(hash_ctx, kdf_in, kdf_inlen) != 1 ||
2586
        EVP_DigestFinal_ex(hash_ctx, p, &hashlen) != 1) {
2587
      sc_log_openssl(card->ctx);
2588
      sc_log(card->ctx, "KDF hash failed");
2589
      r = SC_ERROR_INTERNAL;
2590
      goto err;
2591
    }
2592
    kdf_in[3]++; /* inc the counter */
2593
    p += cs->kdf_hash_size;
2594
  }
2595
2596
  /* copy keys used for APDU */
2597
  memset(&priv->sm_session, 0, sizeof(piv_sm_session_t)); /* clear */
2598
  priv->sm_session.aes_size = cs->aeskeylen;
2599
  memcpy(&priv->sm_session.SKcfrm, &aeskeys[cs->aeskeylen * 0], cs->aeskeylen);
2600
  memcpy(&priv->sm_session.SKmac, &aeskeys[cs->aeskeylen * 1], cs->aeskeylen);
2601
  memcpy(&priv->sm_session.SKenc, &aeskeys[cs->aeskeylen * 2], cs->aeskeylen);
2602
  memcpy(&priv->sm_session.SKrmac, &aeskeys[cs->aeskeylen * 3], cs->aeskeylen);
2603
  sc_mem_clear(&aeskeys, sizeof(aeskeys));
2604
2605
  priv->sm_session.enc_counter[15] = 0x01;
2606
  priv->sm_session.resp_enc_counter[0] = 0x80;
2607
  priv->sm_session.resp_enc_counter[15] = 0x01;
2608
  /* C_MCV is zero */
2609
  /* R_MCV is zero */
2610
2611
  /*  Step H11 Zeroize Z (and kdf_in which has Z) */
2612
  if (Z && Zlen) {
2613
    sc_mem_clear(Z, Zlen);
2614
    free(Z);
2615
    Z = NULL;
2616
    Zlen = 0;
2617
  }
2618
  if (kdf_in && kdf_inlen) {
2619
    sc_mem_clear(kdf_in, kdf_inlen);
2620
    free(kdf_in);
2621
    kdf_in = NULL;
2622
    kdf_inlen = 0;
2623
  }
2624
2625
  /* Step H12 check AuthCryptogramting our version  */
2626
  /* Generate CMAC */
2627
2628
  {
2629
    u8 Check_AuthCryptogram[32];
2630
    size_t Check_Alen = 0;
2631
2632
    u8 MacData[200];
2633
    int MacDatalen;
2634
    memset(MacData, 0, sizeof(MacData));
2635
2636
    p = MacData;
2637
    memcpy(p, "\x4B\x43\x5f\x31\x5f\x56", 6);
2638
    p += 6;
2639
    memcpy(p, IDsicc, cs->IDsicclen);
2640
    p += cs->IDsicclen;
2641
    memcpy(p, IDsh, sizeof(IDsh));
2642
    p += sizeof(IDsh);
2643
2644
    memcpy(p, Qeh_OS, Qeh_OSlen);
2645
    p += Qeh_OSlen;
2646
    MacDatalen = (int)(p - MacData);
2647
2648
#if OPENSSL_VERSION_NUMBER < 0x30000000L
2649
    if ((cmac_ctx = CMAC_CTX_new()) == NULL ||
2650
        CMAC_Init(cmac_ctx, priv->sm_session.SKcfrm, cs->aeskeylen, (*cs->cipher_cbc)(), NULL) != 1 ||
2651
        CMAC_Update(cmac_ctx, MacData, MacDatalen) != 1 ||
2652
        CMAC_Final(cmac_ctx, Check_AuthCryptogram, &Check_Alen) != 1) {
2653
      r = SC_ERROR_INTERNAL;
2654
      sc_log_openssl(card->ctx);
2655
      sc_log(card->ctx, "AES_CMAC failed %d", r);
2656
      goto err;
2657
    }
2658
#else
2659
    mac = EVP_MAC_fetch(PIV_LIBCTX, "cmac", NULL);
2660
    cmac_params[cmac_params_n++] = OSSL_PARAM_construct_utf8_string("cipher", cs->cipher_cbc_name, 0);
2661
2662
    cmac_params[cmac_params_n] = OSSL_PARAM_construct_end();
2663
    if (mac == NULL ||
2664
        (cmac_ctx = EVP_MAC_CTX_new(mac)) == NULL ||
2665
        !EVP_MAC_init(cmac_ctx, priv->sm_session.SKcfrm,
2666
            priv->sm_session.aes_size, cmac_params) ||
2667
        !EVP_MAC_update(cmac_ctx, MacData, MacDatalen) ||
2668
        !EVP_MAC_final(cmac_ctx, Check_AuthCryptogram, &Check_Alen, cs->AuthCryptogramlen)) {
2669
      sc_log_openssl(card->ctx);
2670
      r = SC_ERROR_INTERNAL;
2671
      sc_log(card->ctx, "AES_CMAC failed %d", r);
2672
      goto err;
2673
    }
2674
#endif
2675
2676
    if (0 == memcmp(AuthCryptogram, Check_AuthCryptogram, cs->AuthCryptogramlen)) {
2677
      sc_log(card->ctx, "AuthCryptogram compare");
2678
      r = 0;
2679
    } else {
2680
      sc_log(card->ctx, "AuthCryptogram compare failed");
2681
      r = SC_ERROR_SM_AUTHENTICATION_FAILED;
2682
      goto err;
2683
    }
2684
  }
2685
2686
  /* VCI only needed for contactless */
2687
  if (priv->init_flags & PIV_INIT_CONTACTLESS) {
2688
    /* Is pairing code required? */
2689
    if (!(priv->pin_policy & PIV_PP_VCI_WITHOUT_PC)) {
2690
      r = piv_send_vci_pairing_code(card, priv->pairing_code);
2691
      if (r < 0)
2692
        goto err;
2693
    }
2694
  }
2695
2696
  r = 0;
2697
  priv->sm_flags |= PIV_SM_FLAGS_SM_IS_ACTIVE;
2698
  card->sm_ctx.sm_mode = SM_MODE_TRANSMIT;
2699
2700
err:
2701
  priv->sm_flags &= ~PIV_SM_FLAGS_DEFER_OPEN;
2702
  if (r != 0) {
2703
    memset(&priv->sm_session, 0, sizeof(piv_sm_session_t));
2704
    sc_log_openssl(card->ctx); /* catch any not logged above */
2705
  }
2706
2707
  sc_unlock(card);
2708
2709
  free(sbuf);
2710
  free(kdf_in);
2711
  free(Z);
2712
2713
#if OPENSSL_VERSION_NUMBER < 0x30000000L
2714
  EC_GROUP_free(Cicc_group);
2715
  EC_POINT_free(Cicc_point);
2716
  EC_KEY_free(Cicc_eckey);
2717
#endif
2718
2719
  EVP_PKEY_free(eph_pkey); /* in case not cleared in step H9 */
2720
  EVP_PKEY_CTX_free(eph_ctx);
2721
  EVP_PKEY_free(Cicc_pkey);
2722
  EVP_PKEY_CTX_free(Cicc_ctx);
2723
  EVP_PKEY_CTX_free(Z_ctx);
2724
  EVP_MD_CTX_free(hash_ctx);
2725
2726
#if OPENSSL_VERSION_NUMBER < 0x30000000L
2727
  CMAC_CTX_free(cmac_ctx);
2728
#else
2729
  EVP_MAC_CTX_free(cmac_ctx);
2730
  EVP_MAC_free(mac);
2731
  OPENSSL_free(Qehx);
2732
#endif
2733
2734
  LOG_FUNC_RETURN(card->ctx, r);
2735
}
2736
#endif /* ENABLE_PIV_SM */
2737
2738
/* Add the PIV-II operations */
2739
/* Should use our own keydata, actually should be common to all cards */
2740
/* RSA and EC are added. */
2741
2742
static int
2743
piv_generate_key(sc_card_t *card,
2744
    sc_cardctl_piv_genkey_info_t *keydata)
2745
130
{
2746
130
  int r;
2747
130
  u8 rbuf[4096];
2748
130
  u8 *p;
2749
130
  const u8 *tag;
2750
130
  u8 tagbuf[16];
2751
130
  u8 outdata[3]; /* we could also add tag 81 for exponent */
2752
130
  size_t taglen;
2753
130
  size_t out_len;
2754
130
  size_t in_len;
2755
130
  unsigned int cla_out, tag_out;
2756
2757
130
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
2758
2759
130
  keydata->exponent = NULL;
2760
130
  keydata->exponent_len = 0;
2761
130
  keydata->pubkey = NULL;
2762
130
  keydata->pubkey_len = 0;
2763
130
  keydata->ecparam = NULL; /* will show size as we only support 2 curves */
2764
130
  keydata->ecparam_len = 0;
2765
130
  keydata->ecpoint = NULL;
2766
130
  keydata->ecpoint_len = 0;
2767
2768
130
  out_len = 3;
2769
130
  outdata[0] = 0x80;
2770
130
  outdata[1] = 0x01;
2771
130
  outdata[2] = keydata->key_algid;
2772
130
  switch (keydata->key_algid) {
2773
15
  case 0x05:
2774
15
    keydata->key_bits = 3072;
2775
15
    break;
2776
8
  case 0x06:
2777
8
    keydata->key_bits = 1024;
2778
8
    break;
2779
46
  case 0x07:
2780
46
    keydata->key_bits = 2048;
2781
46
    break;
2782
0
  case 0x16: /* Yubico 5.7 support for 4096 */
2783
0
    keydata->key_bits = 4096;
2784
0
    break;
2785
19
  case 0x11:
2786
19
    keydata->key_bits = 0;
2787
19
    keydata->ecparam = 0; /* we only support prime256v1 */
2788
19
    keydata->ecparam_len = 0;
2789
19
    break;
2790
18
  case 0x14:
2791
18
    keydata->key_bits = 0;
2792
18
    keydata->ecparam = 0; /* we only support secp384r1 */
2793
18
    keydata->ecparam_len = 0;
2794
18
    break;
2795
19
  case 0xE0: /* Yubico 5.7 support for EDDSA 25519 */
2796
24
  case 0xE1: /* Yubico 5.7 support for XEDDSA 25519 */
2797
24
    keydata->key_bits = 0;
2798
24
    keydata->ecparam = 0;
2799
24
    keydata->ecparam_len = 0;
2800
24
    break;
2801
0
  default:
2802
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
2803
130
  }
2804
2805
130
  p = tagbuf;
2806
2807
130
  r = sc_asn1_put_tag(0xAC, outdata, out_len, tagbuf, sizeof(tagbuf), &p);
2808
130
  if (r != SC_SUCCESS) {
2809
0
    sc_log(card->ctx, "Failed to encode ASN1 tag");
2810
0
    goto err;
2811
0
  }
2812
2813
130
  r = piv_general_io(card, 0x47, 0x00, keydata->key_num,
2814
130
      tagbuf, p - tagbuf, rbuf, sizeof rbuf);
2815
2816
130
  if (r >= 0) {
2817
81
    const u8 *cp;
2818
2819
81
    cp = rbuf;
2820
81
    in_len = r;
2821
2822
    /* expected tag is 0x7f49,returned as cla_out == 0x60 and tag_out = 0x1F49 */
2823
81
    r = sc_asn1_read_tag(&cp, in_len, &cla_out, &tag_out, &in_len);
2824
81
    if (r < 0 || cp == NULL || in_len == 0 || cla_out != 0x60 || tag_out != 0x1f49) {
2825
47
      r = SC_ERROR_ASN1_OBJECT_NOT_FOUND;
2826
47
    }
2827
81
    if (r != SC_SUCCESS) {
2828
47
      sc_log(card->ctx, "Tag buffer not found");
2829
47
      goto err;
2830
47
    }
2831
2832
    /* if RSA vs EC, ED25519 or X25519 */
2833
34
    if (keydata->key_bits > 0) {
2834
26
      tag = sc_asn1_find_tag(card->ctx, cp, in_len, 0x82, &taglen);
2835
26
      if (tag != NULL && taglen <= 4) {
2836
23
        keydata->exponent = malloc(taglen);
2837
23
        if (keydata->exponent == NULL)
2838
23
          LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
2839
23
        keydata->exponent_len = taglen;
2840
23
        memcpy(keydata->exponent, tag, taglen);
2841
23
      } else {
2842
3
        sc_log(card->ctx, "Tag 0x82 not found");
2843
3
        r = SC_ERROR_UNKNOWN_DATA_RECEIVED;
2844
3
        goto err;
2845
3
      }
2846
2847
23
      tag = sc_asn1_find_tag(card->ctx, cp, in_len, 0x81, &taglen);
2848
23
      if (tag != NULL && taglen > 0) {
2849
21
        keydata->pubkey = malloc(taglen);
2850
21
        if (keydata->pubkey == NULL) {
2851
0
          free(keydata->exponent);
2852
0
          LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
2853
0
        }
2854
21
        keydata->pubkey_len = taglen;
2855
21
        memcpy(keydata->pubkey, tag, taglen);
2856
21
      } else {
2857
2
        sc_log(card->ctx, "Tag 0x81 not found");
2858
2
        r = SC_ERROR_UNKNOWN_DATA_RECEIVED;
2859
2
        goto err;
2860
2
      }
2861
23
    } else { /* must be EC, ED25519 or X25519 */
2862
8
      tag = sc_asn1_find_tag(card->ctx, cp, in_len, 0x86, &taglen);
2863
8
      if (tag != NULL && taglen > 0) {
2864
6
        keydata->ecpoint = malloc(taglen);
2865
6
        if (keydata->ecpoint == NULL)
2866
6
          LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
2867
6
        keydata->ecpoint_len = taglen;
2868
6
        memcpy(keydata->ecpoint, tag, taglen);
2869
6
      } else {
2870
2
        sc_log(card->ctx, "Tag 0x86 not found");
2871
2
        r = SC_ERROR_UNKNOWN_DATA_RECEIVED;
2872
2
        goto err;
2873
2
      }
2874
8
    }
2875
2876
    /* Could add key to cache so could use engine to generate key,
2877
     * and sign req in single operation or write temporary selfsigned
2878
     * certificate with new public key
2879
     */
2880
27
    r = 0;
2881
27
  }
2882
2883
130
err:
2884
130
  if (r < 0) {
2885
103
    free(keydata->exponent);
2886
103
    keydata->exponent = NULL;
2887
103
    free(keydata->pubkey);
2888
103
    keydata->pubkey = NULL;
2889
103
    free(keydata->ecpoint);
2890
103
    keydata->ecpoint = NULL;
2891
103
  }
2892
2893
130
  LOG_FUNC_RETURN(card->ctx, r);
2894
130
}
2895
2896
static int
2897
piv_ai_map_find_by_id(sc_card_t *card, u8 id)
2898
115
{
2899
  /* piv_private_data_t * priv = PIV_DATA(card); */
2900
115
  int i;
2901
2902
693
  for (i = 0; ai_map[i].ai_id != 0; i++) {
2903
642
    if (ai_map[i].ai_id == id)
2904
64
      return i;
2905
642
  }
2906
51
  return -1;
2907
115
}
2908
2909
/* find the PIV AID on the card. If card->type already filled in,
2910
 * then look for specific AID only
2911
 */
2912
2913
static int
2914
piv_find_aid(sc_card_t *card)
2915
4.44k
{
2916
4.44k
  piv_private_data_t *priv = PIV_DATA(card);
2917
4.44k
  u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
2918
4.44k
  int r, i, j;
2919
4.44k
  const u8 *tag;
2920
4.44k
  size_t taglen;
2921
4.44k
  const u8 *nextac;
2922
4.44k
  const u8 *next80;
2923
4.44k
  const u8 *pix;
2924
4.44k
  size_t pixlen;
2925
4.44k
  const u8 *al_label;
2926
4.44k
  size_t al_labellen;
2927
4.44k
  const u8 *actag; /* Cipher Suite */
2928
4.44k
  size_t actaglen;
2929
4.44k
  const u8 *csai; /* Cipher Suite Algorithm Identifier */
2930
4.44k
  size_t csailen;
2931
4.44k
  size_t resplen = sizeof(rbuf);
2932
#ifdef ENABLE_PIV_SM
2933
  int found_csai = 0;
2934
#endif
2935
2936
4.44k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
2937
2938
  /* first  see if the default application will return a template
2939
   * that we know about.
2940
   */
2941
2942
4.44k
  r = iso7816_select_aid(card, piv_aids[0].value, piv_aids[0].len_short, rbuf, &resplen);
2943
4.44k
  if (r > 0 && priv->aid_der.value && resplen == priv->aid_der.len && !memcmp(priv->aid_der.value, rbuf, resplen)) {
2944
0
    LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
2945
    /* no need to parse again, same as last time */
2946
0
  }
2947
4.44k
  if (r >= 0 && resplen > 2) {
2948
1.84k
    tag = sc_asn1_find_tag(card->ctx, rbuf, resplen, 0x61, &taglen);
2949
1.84k
    if (tag != NULL) {
2950
1.73k
      priv->init_flags |= PIV_INIT_AID_PARSED;
2951
      /* look for 800-73-4 0xAC for Cipher Suite Algorithm Identifier Table 14 */
2952
      /* 800-73-4 only expects 1 0xAC tag len 6 with a 80 01 xx 06 01 00
2953
       * where xx is the SM csID either 27 or 2E.
2954
       * Some vendors may include entries for supported Algorithms even when
2955
       * not required. We will use these if possible
2956
       * Will look for multiple 0x80 with in 0xAC value too.
2957
       */
2958
1.73k
      nextac = tag;
2959
2.21k
      while ((actag = sc_asn1_find_tag(card->ctx, nextac, taglen - (nextac - tag),
2960
2.21k
            0xAC, &actaglen)) != NULL) {
2961
484
        nextac = actag + actaglen;
2962
2963
484
        next80 = actag;
2964
680
        while ((csai = sc_asn1_find_tag(card->ctx, next80, actaglen - (next80 - actag),
2965
680
              0x80, &csailen)) != NULL) {
2966
196
          next80 = csai + csailen;
2967
196
          if (csailen == 1) {
2968
115
            sc_log(card->ctx, "0xAC 0x80 entry:0x%2.2x found", *csai);
2969
115
            j = piv_ai_map_find_by_id(card, *csai);
2970
115
            if (j >= 0) {
2971
64
              priv->alg_ids |= ai_map[j].ai_flag;
2972
64
              continue;
2973
64
            }
2974
#ifdef ENABLE_PIV_SM
2975
            /* check if id is NIST SM */
2976
            for (i = 0; i < PIV_CSS_SIZE; i++) {
2977
              if (*csai != css[i].id)
2978
                continue;
2979
              if (found_csai) {
2980
                sc_log(card->ctx, "found multiple csIDs, using first");
2981
              } else {
2982
                priv->cs = &css[i];
2983
                priv->csID = *csai;
2984
                found_csai++;
2985
                priv->init_flags |= PIV_INIT_AID_AC_SM;
2986
              }
2987
            }
2988
#endif /* ENABLE_PIV_SM */
2989
115
          }
2990
196
        }
2991
484
      }
2992
2993
      /* Last chance to distinguish card type based on Application Label '50' */
2994
1.73k
      al_label = sc_asn1_find_tag(card->ctx, tag, taglen, 0x50, &al_labellen);
2995
1.73k
      if (al_label != NULL) {
2996
37
        sc_log_hex(card->ctx, "Application Label", al_label, al_labellen);
2997
37
        free(priv->al_label);
2998
37
        if ((priv->al_label = malloc(al_labellen)) == NULL) {
2999
0
          LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
3000
0
        }
3001
37
        memcpy(priv->al_label, al_label, al_labellen);
3002
37
        priv->al_labellen = (int)al_labellen;
3003
37
      }
3004
3005
1.73k
      pix = sc_asn1_find_tag(card->ctx, tag, taglen, 0x4F, &pixlen);
3006
1.73k
      if (pix != NULL) {
3007
1.62k
        sc_log(card->ctx, "found PIX");
3008
3009
        /* early cards returned full AID, rather then just the pix */
3010
1.70k
        for (i = 0; piv_aids[i].len_long != 0; i++) {
3011
1.66k
          if ((pixlen >= piv_aids[i].len_long - 5 &&
3012
1.65k
                  memcmp(pix, piv_aids[i].value + 5, piv_aids[i].len_long - 5) == 0) ||
3013
91
              ((pixlen >= piv_aids[i].len_short && memcmp(pix, piv_aids[i].value,
3014
1.58k
                               piv_aids[i].len_short) == 0))) {
3015
1.58k
            free(priv->aid_der.value); /* free previous value if any */
3016
1.58k
            if ((priv->aid_der.value = malloc(resplen)) == NULL) {
3017
0
              LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
3018
0
            }
3019
1.58k
            memcpy(priv->aid_der.value, rbuf, resplen);
3020
1.58k
            priv->aid_der.len = resplen;
3021
1.58k
            LOG_FUNC_RETURN(card->ctx, i);
3022
1.58k
          }
3023
1.66k
        }
3024
1.62k
      }
3025
1.73k
    }
3026
1.84k
  }
3027
3028
2.86k
  LOG_FUNC_RETURN(card->ctx, SC_ERROR_NO_CARD_SUPPORT);
3029
2.86k
}
3030
3031
/*
3032
 * Read a DER encoded object from a file. Allocate and return the buf.
3033
 * Used to read the file defined in offCardCertURL from a cache.
3034
 * Also used for testing of History and Discovery objects from a file
3035
 * when testing with a card that does not support these new objects.
3036
 */
3037
static int
3038
piv_read_obj_from_file(sc_card_t *card, char *filename,
3039
    u8 **buf, size_t *buf_len)
3040
2
{
3041
2
  int r;
3042
2
  int r_tag;
3043
2
  int f = -1;
3044
2
  size_t len;
3045
2
  u8 tagbuf[16];
3046
2
  size_t rbuflen;
3047
2
  const u8 *body;
3048
2
  unsigned int cla_out, tag_out;
3049
2
  size_t bodylen;
3050
3051
2
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
3052
3053
2
  *buf = NULL;
3054
2
  *buf_len = 0;
3055
2
  f = open(filename, O_RDONLY);
3056
2
  if (f < 0) {
3057
2
    sc_log(card->ctx, "Unable to load PIV off card file: \"%s\"", filename);
3058
2
    r = SC_ERROR_FILE_NOT_FOUND;
3059
2
    goto err;
3060
2
  }
3061
0
  len = read(f, tagbuf, sizeof(tagbuf)); /* get tag and length */
3062
0
  if (len < 2 || len > sizeof(tagbuf)) {
3063
0
    sc_log(card->ctx, "Problem with \"%s\"", filename);
3064
0
    r = SC_ERROR_DATA_OBJECT_NOT_FOUND;
3065
0
    goto err;
3066
0
  }
3067
0
  body = tagbuf;
3068
  /* accept any tag for now, just get length */
3069
0
  r_tag = sc_asn1_read_tag(&body, len, &cla_out, &tag_out, &bodylen);
3070
0
  if ((r_tag != SC_SUCCESS && r_tag != SC_ERROR_ASN1_END_OF_CONTENTS) ||
3071
0
      body == NULL) {
3072
0
    sc_log(card->ctx, "DER problem");
3073
0
    r = SC_ERROR_FILE_NOT_FOUND;
3074
0
    goto err;
3075
0
  }
3076
0
  rbuflen = body - tagbuf + bodylen;
3077
0
  *buf = malloc(rbuflen);
3078
0
  if (!*buf) {
3079
0
    r = SC_ERROR_OUT_OF_MEMORY;
3080
0
    goto err;
3081
0
  }
3082
0
  memcpy(*buf, tagbuf, MIN(len, rbuflen)); /* copy first or only part */
3083
  /* read rest of file */
3084
0
  if (rbuflen > len + sizeof(tagbuf)) {
3085
0
    len = read(f, *buf + sizeof(tagbuf), rbuflen - sizeof(tagbuf)); /* read rest */
3086
0
    if (len != rbuflen - sizeof(tagbuf)) {
3087
0
      r = SC_ERROR_INVALID_ASN1_OBJECT;
3088
0
      free(*buf);
3089
0
      *buf = NULL;
3090
0
      goto err;
3091
0
    }
3092
0
  }
3093
0
  r = (int)rbuflen;
3094
0
  *buf_len = rbuflen;
3095
2
err:
3096
2
  if (f >= 0)
3097
0
    close(f);
3098
2
  LOG_FUNC_RETURN(card->ctx, r);
3099
2
}
3100
3101
/* the tag is the PIV_OBJ_*  */
3102
static int
3103
piv_get_data(sc_card_t *card, int enumtag, u8 **buf, size_t *buf_len)
3104
45.8k
{
3105
45.8k
  piv_private_data_t *priv = PIV_DATA(card);
3106
45.8k
  u8 *p;
3107
45.8k
  u8 *tbuf;
3108
45.8k
  int r = 0;
3109
45.8k
  u8 tagbuf[8];
3110
45.8k
  size_t tag_len;
3111
45.8k
  int alloc_buf = 0;
3112
3113
45.8k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
3114
3115
45.8k
  sc_log(card->ctx, "#%d, %s", enumtag, piv_objects[enumtag].name);
3116
3117
45.8k
  r = sc_lock(card); /* do check len and get data in same transaction */
3118
45.8k
  if (r != SC_SUCCESS) {
3119
0
    sc_log(card->ctx, "sc_lock failed");
3120
0
    return r;
3121
0
  }
3122
3123
45.8k
  tag_len = piv_objects[enumtag].tag_len;
3124
3125
45.8k
  p = tagbuf;
3126
45.8k
  r = sc_asn1_put_tag(0x5c, piv_objects[enumtag].tag_value, tag_len, tagbuf, sizeof(tagbuf), &p);
3127
45.8k
  if (r != SC_SUCCESS) {
3128
0
    sc_log(card->ctx, "Failed to encode ASN1 tag");
3129
0
    goto err;
3130
0
  }
3131
3132
45.8k
  if (*buf_len == 1 && *buf == NULL) {
3133
45.8k
    *buf_len = priv->max_object_size; /* will allocate below */
3134
45.8k
    alloc_buf = 1;
3135
45.8k
  }
3136
3137
45.8k
  sc_log(card->ctx, "buffer for #%d *buf=0x%p len=%zu", enumtag, *buf, *buf_len);
3138
45.8k
  if (*buf == NULL && *buf_len > 0) {
3139
45.8k
    if (*buf_len > MAX_FILE_SIZE) {
3140
0
      r = SC_ERROR_INTERNAL;
3141
0
      goto err;
3142
0
    }
3143
45.8k
    *buf = malloc(*buf_len);
3144
45.8k
    if (*buf == NULL) {
3145
0
      r = SC_ERROR_OUT_OF_MEMORY;
3146
0
      goto err;
3147
0
    }
3148
45.8k
  }
3149
3150
#ifdef ENABLE_PIV_SM
3151
  /*
3152
   * Over contact reader, OK to read non sensitive object in clear even when SM is active
3153
   * but only if using default policy and we are not in reader_lock_obtained
3154
   * Discovery object will use SM from reader_lock_obtained to catch if SM is still valid
3155
   * i.e. no interference from other applications
3156
   */
3157
  sc_log(card->ctx, "enumtag:%d sm_ctx.sm_mode:%d piv_objects[enumtag].flags:0x%8.8x sm_flags:0x%8.8lx it_flags:0x%8.8x",
3158
      enumtag, card->sm_ctx.sm_mode, piv_objects[enumtag].flags, priv->sm_flags, priv->init_flags);
3159
  if (priv->sm_flags & PIV_SM_FLAGS_SM_IS_ACTIVE &&
3160
      enumtag != PIV_OBJ_DISCOVERY &&
3161
      card->sm_ctx.sm_mode == SM_MODE_TRANSMIT &&
3162
      !(piv_objects[enumtag].flags & PIV_OBJECT_NEEDS_PIN) &&
3163
      !(priv->sm_flags & (PIV_SM_FLAGS_NEVER | PIV_SM_FLAGS_ALWAYS)) &&
3164
      !(priv->init_flags & (PIV_INIT_CONTACTLESS | PIV_INIT_IN_READER_LOCK_OBTAINED))) {
3165
    sc_log(card->ctx, "Set PIV_SM_GET_DATA_IN_CLEAR");
3166
    priv->sm_flags |= PIV_SM_GET_DATA_IN_CLEAR;
3167
  }
3168
3169
#endif /* ENABLE_PIV_SM */
3170
45.8k
  r = piv_general_io(card, 0xCB, 0x3F, 0xFF, tagbuf, p - tagbuf, *buf, *buf_len);
3171
45.8k
  if (r > 0) {
3172
4.68k
    int r_tag;
3173
4.68k
    unsigned int cla_out, tag_out;
3174
4.68k
    size_t bodylen = 0;
3175
4.68k
    const u8 *body = *buf;
3176
4.68k
    r_tag = sc_asn1_read_tag(&body, r, &cla_out, &tag_out, &bodylen);
3177
4.68k
    if (r_tag != SC_SUCCESS || body == NULL ||
3178
3.95k
        ((cla_out << 24 | tag_out) != piv_objects[enumtag].resp_tag)) {
3179
1.07k
      sc_log(card->ctx, "invalid tag or length r_tag:%d body:%p", r_tag, body);
3180
1.07k
      r = SC_ERROR_FILE_NOT_FOUND;
3181
1.07k
      goto err;
3182
1.07k
    }
3183
3.61k
    *buf_len = (body - *buf) + bodylen;
3184
41.1k
  } else if (r == 0) {
3185
1.15k
    r = SC_ERROR_FILE_NOT_FOUND;
3186
1.15k
    goto err;
3187
40.0k
  } else {
3188
40.0k
    goto err;
3189
40.0k
  }
3190
3191
3.61k
  if (alloc_buf && *buf) {
3192
3.61k
    tbuf = malloc(r);
3193
3.61k
    if (tbuf == NULL) {
3194
0
      r = SC_ERROR_OUT_OF_MEMORY;
3195
0
      goto err;
3196
0
    }
3197
3.61k
    memcpy(tbuf, *buf, r);
3198
3.61k
    free(*buf);
3199
3.61k
    alloc_buf = 0;
3200
3.61k
    *buf = tbuf;
3201
3.61k
  }
3202
3203
45.8k
err:
3204
45.8k
  if (alloc_buf) {
3205
42.2k
    free(*buf);
3206
42.2k
    *buf = NULL;
3207
42.2k
  }
3208
45.8k
  sc_unlock(card);
3209
45.8k
  LOG_FUNC_RETURN(card->ctx, r);
3210
45.8k
}
3211
3212
static int
3213
piv_get_cached_data(sc_card_t *card, int enumtag, u8 **buf, size_t *buf_len)
3214
6.36k
{
3215
3216
6.36k
  piv_private_data_t *priv = PIV_DATA(card);
3217
6.36k
  int r;
3218
6.36k
  u8 *rbuf = NULL;
3219
6.36k
  size_t rbuflen;
3220
3221
6.36k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
3222
3223
6.36k
  if (enumtag < 0 || enumtag >= PIV_OBJ_LAST_ENUM)
3224
0
    return SC_ERROR_INTERNAL;
3225
3226
6.36k
  sc_log(card->ctx, "#%d, %s", enumtag, piv_objects[enumtag].name);
3227
3228
  /* see if we have it cached */
3229
6.36k
  if (priv->obj_cache[enumtag].flags & PIV_OBJ_CACHE_VALID) {
3230
3231
0
    sc_log(card->ctx, "found #%d %p:%zu %p:%zu",
3232
0
        enumtag,
3233
0
        priv->obj_cache[enumtag].obj_data,
3234
0
        priv->obj_cache[enumtag].obj_len,
3235
0
        priv->obj_cache[enumtag].internal_obj_data,
3236
0
        priv->obj_cache[enumtag].internal_obj_len);
3237
3238
0
    if (priv->obj_cache[enumtag].obj_len == 0) {
3239
0
      r = SC_ERROR_FILE_NOT_FOUND;
3240
0
      sc_log(card->ctx, "#%d found but len=0", enumtag);
3241
0
      goto err;
3242
0
    }
3243
0
    *buf = priv->obj_cache[enumtag].obj_data;
3244
0
    *buf_len = priv->obj_cache[enumtag].obj_len;
3245
0
    r = (int)*buf_len;
3246
0
    goto ok;
3247
0
  }
3248
3249
  /*
3250
   * If we know it can not be on the card  i.e. History object
3251
   * has been read, and we know what other certs may or
3252
   * may not be on the card. We can avoid extra overhead
3253
   * Also used if object on card was not parsable
3254
   */
3255
3256
6.36k
  if (priv->obj_cache[enumtag].flags & PIV_OBJ_CACHE_NOT_PRESENT) {
3257
0
    sc_log(card->ctx, "no_obj #%d", enumtag);
3258
0
    r = SC_ERROR_FILE_NOT_FOUND;
3259
0
    goto err;
3260
0
  }
3261
3262
  /* Not cached, try to get it, piv_get_data will allocate a buf */
3263
6.36k
  sc_log(card->ctx, "get #%d", enumtag);
3264
6.36k
  rbuflen = 1;
3265
6.36k
  r = piv_get_data(card, enumtag, &rbuf, &rbuflen);
3266
6.36k
  if (r > 0) {
3267
973
    priv->obj_cache[enumtag].flags |= PIV_OBJ_CACHE_VALID;
3268
973
    priv->obj_cache[enumtag].obj_len = r;
3269
973
    priv->obj_cache[enumtag].obj_data = rbuf;
3270
973
    *buf = rbuf;
3271
973
    *buf_len = r;
3272
3273
973
    sc_log(card->ctx, "added #%d  %p:%zu %p:%zu",
3274
973
        enumtag,
3275
973
        priv->obj_cache[enumtag].obj_data,
3276
973
        priv->obj_cache[enumtag].obj_len,
3277
973
        priv->obj_cache[enumtag].internal_obj_data,
3278
973
        priv->obj_cache[enumtag].internal_obj_len);
3279
3280
5.39k
  } else {
3281
5.39k
    free(rbuf);
3282
5.39k
    if (r == 0 || r == SC_ERROR_FILE_NOT_FOUND) {
3283
216
      r = SC_ERROR_FILE_NOT_FOUND;
3284
216
      priv->obj_cache[enumtag].flags |= PIV_OBJ_CACHE_VALID;
3285
216
      priv->obj_cache[enumtag].obj_len = 0;
3286
5.17k
    } else {
3287
5.17k
      goto err;
3288
5.17k
    }
3289
5.39k
  }
3290
1.18k
ok:
3291
3292
6.36k
err:
3293
6.36k
  LOG_FUNC_RETURN(card->ctx, r);
3294
6.36k
}
3295
3296
static int
3297
piv_cache_internal_data(sc_card_t *card, int enumtag)
3298
0
{
3299
0
  piv_private_data_t *priv = PIV_DATA(card);
3300
0
  const u8 *tag;
3301
0
  const u8 *body;
3302
0
  size_t taglen;
3303
0
  size_t bodylen;
3304
0
  int compressed = 0;
3305
0
  int r = SC_SUCCESS;
3306
#ifdef ENABLE_PIV_SM
3307
  u8 *cvc_start = NULL;
3308
  size_t cvc_len = 0;
3309
#endif
3310
3311
  /* if already cached */
3312
0
  if (priv->obj_cache[enumtag].internal_obj_data && priv->obj_cache[enumtag].internal_obj_len) {
3313
0
    sc_log(card->ctx, "#%d found internal %p:%zu",
3314
0
        enumtag,
3315
0
        priv->obj_cache[enumtag].internal_obj_data,
3316
0
        priv->obj_cache[enumtag].internal_obj_len);
3317
0
    LOG_FUNC_RETURN(card->ctx, r);
3318
0
  }
3319
3320
0
  body = sc_asn1_find_tag(card->ctx,
3321
0
      priv->obj_cache[enumtag].obj_data,
3322
0
      priv->obj_cache[enumtag].obj_len,
3323
0
      0x53, &bodylen);
3324
3325
0
  if (body == NULL || priv->obj_cache[enumtag].obj_data[0] != 0x53)
3326
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_OBJECT_NOT_VALID);
3327
3328
  /* get the certificate out */
3329
0
  if (piv_objects[enumtag].flags & PIV_OBJECT_TYPE_CERT) {
3330
3331
0
    tag = sc_asn1_find_tag(card->ctx, body, bodylen, 0x71, &taglen);
3332
    /* 800-72-1 not clear if this is 80 or 01 Sent comment to NIST for 800-72-2 */
3333
    /* 800-73-3 says it is 01, keep dual test so old cards still work */
3334
0
    if (tag && taglen > 0 && (((*tag) & 0x80) || ((*tag) & 0x01)))
3335
0
      compressed = 1;
3336
3337
#ifdef ENABLE_PIV_SM
3338
    cvc_start = (u8 *)tag + taglen; /* save for later as cvs (if present) follows  0x71 */
3339
#endif
3340
3341
0
    tag = sc_asn1_find_tag(card->ctx, body, bodylen, 0x70, &taglen);
3342
0
    if (tag == NULL)
3343
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_OBJECT_NOT_VALID);
3344
3345
0
    if (taglen == 0)
3346
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND);
3347
3348
0
    if (compressed) {
3349
0
      priv->obj_cache[enumtag].flags |= PIV_OBJ_CACHE_COMPRESSED;
3350
0
    }
3351
    /* internal certificate remains compressed */
3352
0
    if (!(priv->obj_cache[enumtag].internal_obj_data = malloc(taglen)))
3353
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
3354
3355
0
    memcpy(priv->obj_cache[enumtag].internal_obj_data, tag, taglen);
3356
0
    priv->obj_cache[enumtag].internal_obj_len = taglen;
3357
3358
#ifdef ENABLE_PIV_SM
3359
    /* PIV_OBJ_SM_CERT_SIGNER  CERT OBJECT may also have a intermediate CVC */
3360
    if (piv_objects[enumtag].flags & PIV_OBJECT_TYPE_CVC) {
3361
      /* cvc if present should be at cvc_start.
3362
       * find the tag(T) and get value(V) and len(L) from TLV.
3363
       * Could reconstruct ASN1 of (T)(L) stating location from length and known tag.
3364
       * as the size of (L) depends on the length of value
3365
       */
3366
      if ((tag = sc_asn1_find_tag(card->ctx, body, bodylen, 0x7F21, &taglen)) != NULL &&
3367
          cvc_start &&
3368
          cvc_start < tag &&
3369
          cvc_start[0] == 0x7f && cvc_start[1] == 0x21) {
3370
        cvc_len = tag - cvc_start + taglen;
3371
        /* decode the intermediate CVC */
3372
        r = piv_decode_cvc(card, &cvc_start, &cvc_len, &priv->sm_in_cvc);
3373
        if (r < 0) {
3374
          sc_log(card->ctx, "unable to parse intermediate CVC: %d skipping", r);
3375
        }
3376
        priv->sm_flags |= PIV_SM_FLAGS_SM_IN_CVC_PRESENT;
3377
      }
3378
    }
3379
#endif /* ENABLE_PIV_SM */
3380
3381
    /* convert pub key to internal */
3382
0
  } else if (piv_objects[enumtag].flags & PIV_OBJECT_TYPE_PUBKEY) {
3383
0
    tag = sc_asn1_find_tag(card->ctx, body, bodylen, *body, &taglen);
3384
0
    if (tag == NULL)
3385
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_OBJECT_NOT_VALID);
3386
3387
0
    if (taglen == 0)
3388
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND);
3389
3390
0
    if (!(priv->obj_cache[enumtag].internal_obj_data = malloc(taglen)))
3391
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
3392
3393
0
    memcpy(priv->obj_cache[enumtag].internal_obj_data, tag, taglen);
3394
0
    priv->obj_cache[enumtag].internal_obj_len = taglen;
3395
0
  } else {
3396
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
3397
0
  }
3398
3399
0
  sc_log(card->ctx, "added #%d internal %p:%zu",
3400
0
      enumtag,
3401
0
      priv->obj_cache[enumtag].internal_obj_data,
3402
0
      priv->obj_cache[enumtag].internal_obj_len);
3403
3404
0
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
3405
0
}
3406
3407
/*
3408
 * Callers of this may be expecting a certificate,
3409
 * select file will have saved the object type for us
3410
 * as well as set that we want the cert from the object.
3411
 */
3412
static int
3413
piv_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long *flags)
3414
0
{
3415
0
  piv_private_data_t *priv = PIV_DATA(card);
3416
0
  int enumtag;
3417
0
  int r;
3418
0
  u8 *rbuf = NULL;
3419
0
  size_t rbuflen = 0;
3420
0
  const u8 *body;
3421
0
  size_t bodylen;
3422
3423
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
3424
0
  if (priv->selected_obj < 0)
3425
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
3426
0
  enumtag = piv_objects[priv->selected_obj].enumtag;
3427
3428
0
  if (priv->rwb_state == -1) {
3429
0
    r = piv_get_cached_data(card, enumtag, &rbuf, &rbuflen);
3430
3431
0
    if (r >= 0) {
3432
      /* an object with no data will be considered not found */
3433
      /* Discovery tag = 0x73, all others are 0x53 */
3434
0
      if (!rbuf || rbuf[0] == 0x00 || ((rbuf[0] & 0xDF) == 0x53 && rbuf[1] == 0x00)) {
3435
0
        r = SC_ERROR_FILE_NOT_FOUND;
3436
0
        goto err;
3437
0
      }
3438
3439
0
      body = sc_asn1_find_tag(card->ctx, rbuf, rbuflen, rbuf[0], &bodylen);
3440
0
      if (body == NULL) {
3441
        /* if missing, assume its the body */
3442
        /* DEE bug in the beta card */
3443
0
        sc_log(card->ctx, " ***** tag 0x53 MISSING");
3444
0
        r = SC_ERROR_INVALID_DATA;
3445
0
        goto err;
3446
0
      }
3447
0
      if (bodylen > body - rbuf + rbuflen) {
3448
0
        sc_log(card->ctx, " ***** tag length > then data: %zu>%zu+%zu",
3449
0
            bodylen, body - rbuf, rbuflen);
3450
0
        r = SC_ERROR_INVALID_DATA;
3451
0
        goto err;
3452
0
      }
3453
      /* if cached obj has internal interesting data (cert or pub key) */
3454
0
      if (priv->return_only_cert || piv_objects[enumtag].flags & PIV_OBJECT_TYPE_PUBKEY) {
3455
0
        r = piv_cache_internal_data(card, enumtag);
3456
0
        if (r < 0)
3457
0
          goto err;
3458
0
      }
3459
0
    }
3460
0
    priv->rwb_state = 0;
3461
0
  }
3462
3463
0
  if (priv->return_only_cert || piv_objects[enumtag].flags & PIV_OBJECT_TYPE_PUBKEY) {
3464
0
    rbuf = priv->obj_cache[enumtag].internal_obj_data;
3465
0
    rbuflen = priv->obj_cache[enumtag].internal_obj_len;
3466
0
    if ((priv->obj_cache[enumtag].flags & PIV_OBJ_CACHE_COMPRESSED) && flags) {
3467
0
      *flags |= SC_FILE_FLAG_COMPRESSED_AUTO;
3468
0
    }
3469
0
  } else {
3470
0
    rbuf = priv->obj_cache[enumtag].obj_data;
3471
0
    rbuflen = priv->obj_cache[enumtag].obj_len;
3472
0
  }
3473
  /* rbuf rbuflen has pointer and length to cached data */
3474
3475
0
  if (rbuflen < idx + count)
3476
0
    count = rbuflen - idx;
3477
0
  if (count <= 0) {
3478
0
    r = 0;
3479
0
    priv->rwb_state = 1;
3480
0
  } else {
3481
0
    memcpy(buf, rbuf + idx, count);
3482
0
    r = (int)count;
3483
0
  }
3484
3485
0
err:
3486
0
  LOG_FUNC_RETURN(card->ctx, r);
3487
0
}
3488
3489
/*
3490
 * the tag is the PIV_OBJ_*
3491
 * The buf should have the 0x53 tag+len+tags and data
3492
 */
3493
3494
static int
3495
piv_put_data(sc_card_t *card, int tag, const u8 *buf, size_t buf_len)
3496
90
{
3497
90
  int r;
3498
90
  u8 *sbuf;
3499
90
  size_t sbuflen;
3500
90
  u8 *p;
3501
90
  size_t tag_len;
3502
3503
90
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
3504
3505
90
  tag_len = piv_objects[tag].tag_len;
3506
90
  r = sc_asn1_put_tag(0x5c, piv_objects[tag].tag_value, tag_len, NULL, 0, NULL);
3507
90
  if (r <= 0) {
3508
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
3509
0
  }
3510
90
  sbuflen = r + buf_len;
3511
90
  if (!(sbuf = malloc(sbuflen))) {
3512
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
3513
0
  }
3514
3515
90
  p = sbuf;
3516
90
  r = sc_asn1_put_tag(0x5c, piv_objects[tag].tag_value, tag_len, sbuf, sbuflen, &p);
3517
90
  if (r != SC_SUCCESS) {
3518
0
    LOG_FUNC_RETURN(card->ctx, r);
3519
0
  }
3520
3521
  /* This is safe as we calculated the size of buffer above */
3522
90
  memcpy(p, buf, buf_len);
3523
90
  p += buf_len;
3524
3525
90
  r = piv_general_io(card, 0xDB, 0x3F, 0xFF, sbuf, p - sbuf, NULL, 0);
3526
3527
90
  if (sbuf)
3528
90
    free(sbuf);
3529
90
  LOG_FUNC_RETURN(card->ctx, r);
3530
90
}
3531
3532
static int
3533
piv_write_certificate(sc_card_t *card, const u8 *buf, size_t count, unsigned long flags)
3534
90
{
3535
90
  piv_private_data_t *priv = PIV_DATA(card);
3536
90
  int enumtag, tmplen, tmplen2, tmplen3;
3537
90
  int r = SC_SUCCESS;
3538
90
  u8 *sbuf = NULL;
3539
90
  u8 *p;
3540
90
  size_t sbuflen;
3541
90
  size_t taglen;
3542
3543
90
  if ((tmplen = sc_asn1_put_tag(0x70, buf, count, NULL, 0, NULL)) <= 0 ||
3544
90
      (tmplen2 = sc_asn1_put_tag(0x71, NULL, 1, NULL, 0, NULL)) <= 0 ||
3545
90
      (tmplen3 = sc_asn1_put_tag(0xFE, NULL, 0, NULL, 0, NULL)) <= 0) {
3546
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
3547
0
  }
3548
3549
90
  taglen = tmplen + tmplen2 + tmplen3;
3550
90
  tmplen = sc_asn1_put_tag(0x53, NULL, taglen, NULL, 0, NULL);
3551
90
  if (tmplen <= 0) {
3552
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
3553
0
  }
3554
3555
90
  sbuflen = tmplen;
3556
90
  sbuf = malloc(sbuflen);
3557
90
  if (sbuf == NULL)
3558
90
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
3559
90
  p = sbuf;
3560
90
  if ((r = sc_asn1_put_tag(0x53, NULL, taglen, sbuf, sbuflen, &p)) != SC_SUCCESS ||
3561
90
      (r = sc_asn1_put_tag(0x70, buf, count, p, sbuflen - (p - sbuf), &p)) != SC_SUCCESS ||
3562
90
      (r = sc_asn1_put_tag(0x71, NULL, 1, p, sbuflen - (p - sbuf), &p)) != SC_SUCCESS) {
3563
0
    goto out;
3564
0
  }
3565
  /* Use 01 as per NIST 800-73-3 */
3566
90
  *p++ = (flags) ? 0x01 : 0x00; /* certinfo, i.e. gzipped? */
3567
90
  r = sc_asn1_put_tag(0xFE, NULL, 0, p, sbuflen - (p - sbuf), &p);
3568
90
  if (r != SC_SUCCESS) {
3569
0
    goto out;
3570
0
  }
3571
3572
90
  enumtag = piv_objects[priv->selected_obj].enumtag;
3573
90
  r = piv_put_data(card, enumtag, sbuf, sbuflen);
3574
3575
90
out:
3576
90
  free(sbuf);
3577
90
  LOG_FUNC_RETURN(card->ctx, r);
3578
90
}
3579
3580
/*
3581
 * For certs we need to add the 0x53 tag and other specific tags,
3582
 * and call the piv_put_data
3583
 * Note: the select file will have saved the object type for us
3584
 * Write is used by piv-tool, so we will use flags:
3585
 *  length << 8 | 8bits:
3586
 * object            xxxx0000
3587
 * uncompressed cert xxx00001
3588
 * compressed cert   xxx10001
3589
 * pubkey            xxxx0010
3590
 *
3591
 * to indicate we are writing a cert and if is compressed
3592
 * or if we are writing a pubkey in to the cache.
3593
 * if its not a cert or pubkey its an object.
3594
 *
3595
 * Therefore when idx=0, we will get the length of the object
3596
 * and allocate a buffer, so we can support partial writes.
3597
 * When the last chuck of the data is sent, we will write it.
3598
 */
3599
3600
static int
3601
piv_write_binary(sc_card_t *card, unsigned int idx,
3602
    const u8 *buf, size_t count, unsigned long flags)
3603
159k
{
3604
159k
  piv_private_data_t *priv = PIV_DATA(card);
3605
159k
  int r;
3606
159k
  int enumtag;
3607
3608
159k
  LOG_FUNC_CALLED(card->ctx);
3609
3610
159k
  if (priv->selected_obj < 0)
3611
159k
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
3612
3613
159k
  enumtag = piv_objects[priv->selected_obj].enumtag;
3614
3615
159k
  if (priv->rwb_state == 1) /* trying to write at end */
3616
159k
    LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
3617
3618
159k
  if (priv->rwb_state == -1) {
3619
3620
    /* if  cached, remove old entry */
3621
90
    if (priv->obj_cache[enumtag].flags & PIV_OBJ_CACHE_VALID) {
3622
0
      piv_obj_cache_free_entry(card, enumtag, 0);
3623
0
    }
3624
3625
90
    if (idx != 0)
3626
90
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_NO_CARD_SUPPORT);
3627
3628
90
    priv->w_buf_len = flags >> 8;
3629
90
    if (priv->w_buf_len == 0)
3630
90
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
3631
3632
90
    priv->w_buf = malloc(priv->w_buf_len);
3633
90
    priv->rwb_state = 0;
3634
90
  }
3635
3636
  /* on each pass make sure we have w_buf */
3637
159k
  if (priv->w_buf == NULL)
3638
159k
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
3639
3640
159k
  if (idx + count > priv->w_buf_len)
3641
159k
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_OBJECT_NOT_VALID);
3642
3643
159k
  memcpy(priv->w_buf + idx, buf, count); /* copy one chunk */
3644
3645
  /* if this was not the last chunk, return to get rest */
3646
159k
  if (idx + count < priv->w_buf_len)
3647
159k
    LOG_FUNC_RETURN(card->ctx, (int)count);
3648
3649
90
  priv->rwb_state = 1; /* at end of object */
3650
3651
90
  switch (flags & 0x0f) {
3652
90
  case 1:
3653
90
    r = piv_write_certificate(card, priv->w_buf, priv->w_buf_len, flags & 0x10);
3654
90
    break;
3655
0
  case 2: /* pubkey to be added to cache, it should have 0x53 and 0x99 tags. */
3656
0
    r = (int)priv->w_buf_len;
3657
0
    break;
3658
0
  default:
3659
0
    r = piv_put_data(card, enumtag, priv->w_buf, priv->w_buf_len);
3660
0
    break;
3661
90
  }
3662
  /* if it worked, will cache it */
3663
90
  if (r >= 0 && priv->w_buf) {
3664
5
    priv->obj_cache[enumtag].flags |= PIV_OBJ_CACHE_VALID;
3665
5
    priv->obj_cache[enumtag].obj_data = priv->w_buf;
3666
5
    priv->obj_cache[enumtag].obj_len = priv->w_buf_len;
3667
85
  } else {
3668
85
    if (priv->w_buf)
3669
85
      free(priv->w_buf);
3670
85
  }
3671
90
  priv->w_buf = NULL;
3672
90
  priv->w_buf_len = 0;
3673
90
  LOG_FUNC_RETURN(card->ctx, (r < 0) ? r : (int)count);
3674
90
}
3675
3676
/*
3677
 * Card initialization is NOT standard.
3678
 * Some cards use mutual or external authentication using 3des or aes key. We
3679
 * will read in the key from a file either binary or hex encoded.
3680
 * This is only needed during initialization/personalization of the card
3681
 */
3682
3683
#ifdef ENABLE_OPENSSL
3684
static EVP_CIPHER *
3685
get_cipher_for_algo(sc_card_t *card, int alg_id)
3686
166
{
3687
166
  const char *algo;
3688
166
  switch (alg_id) {
3689
9
  case 0x0:
3690
14
  case 0x1: /* 2TDES */
3691
17
  case 0x3:
3692
17
    algo = "DES-EDE3-ECB";
3693
17
    break;
3694
136
  case 0x8:
3695
136
    algo = "AES-128-ECB";
3696
136
    break;
3697
5
  case 0xA:
3698
5
    algo = "AES-192-ECB";
3699
5
    break;
3700
6
  case 0xC:
3701
6
    algo = "AES-256-ECB";
3702
6
    break;
3703
2
  default:
3704
2
    return NULL;
3705
166
  }
3706
164
  return sc_evp_cipher(card->ctx, algo);
3707
166
}
3708
3709
static int
3710
get_keylen(unsigned int alg_id, size_t *size)
3711
164
{
3712
164
  switch (alg_id) {
3713
5
  case 0x01:
3714
5
    *size = 192 / 8; /* 2TDES still has 3 single des keys  phase out by 12/31/2010 */
3715
5
    break;
3716
9
  case 0x00:
3717
12
  case 0x03:
3718
12
    *size = 192 / 8;
3719
12
    break;
3720
136
  case 0x08:
3721
136
    *size = 128 / 8;
3722
136
    break;
3723
5
  case 0x0A:
3724
5
    *size = 192 / 8;
3725
5
    break;
3726
6
  case 0x0C:
3727
6
    *size = 256 / 8;
3728
6
    break;
3729
0
  default:
3730
0
    return SC_ERROR_INVALID_ARGUMENTS;
3731
164
  }
3732
164
  return SC_SUCCESS;
3733
164
}
3734
3735
static int
3736
piv_get_key(sc_card_t *card, unsigned int alg_id, u8 **key, size_t *len)
3737
164
{
3738
3739
164
  int r;
3740
164
  size_t fsize;
3741
164
  FILE *f = NULL;
3742
164
  char *keyfilename = NULL;
3743
164
  size_t expected_keylen;
3744
164
  size_t keylen, readlen;
3745
164
  u8 *keybuf = NULL;
3746
164
  u8 *tkey = NULL;
3747
3748
164
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
3749
3750
164
  keyfilename = (char *)getenv("PIV_EXT_AUTH_KEY");
3751
3752
164
  if (keyfilename == NULL) {
3753
0
    sc_log(card->ctx,
3754
0
        "Unable to get PIV_EXT_AUTH_KEY=(null) for general_external_authenticate");
3755
0
    r = SC_ERROR_FILE_NOT_FOUND;
3756
0
    goto err;
3757
0
  }
3758
3759
164
  r = get_keylen(alg_id, &expected_keylen);
3760
164
  if (r) {
3761
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid cipher selector, none found for:  %02x", alg_id);
3762
0
    r = SC_ERROR_INVALID_ARGUMENTS;
3763
0
    goto err;
3764
0
  }
3765
3766
164
  f = fopen(keyfilename, "rb");
3767
164
  if (!f) {
3768
0
    sc_log(card->ctx, " Unable to load key from file\n");
3769
0
    r = SC_ERROR_FILE_NOT_FOUND;
3770
0
    goto err;
3771
0
  }
3772
3773
164
  if (0 > fseek(f, 0L, SEEK_END))
3774
0
    r = SC_ERROR_INTERNAL;
3775
164
  fsize = ftell(f);
3776
164
  if (0 > (long)fsize)
3777
0
    r = SC_ERROR_INTERNAL;
3778
164
  if (0 > fseek(f, 0L, SEEK_SET))
3779
0
    r = SC_ERROR_INTERNAL;
3780
164
  if (r) {
3781
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not read %s\n", keyfilename);
3782
0
    goto err;
3783
0
  }
3784
3785
164
  keybuf = malloc(fsize + 1); /* if not binary, need null to make it a string */
3786
164
  if (!keybuf) {
3787
0
    sc_log(card->ctx, " Unable to allocate key memory");
3788
0
    r = SC_ERROR_OUT_OF_MEMORY;
3789
0
    goto err;
3790
0
  }
3791
164
  keybuf[fsize] = 0x00; /* in case it is text need null */
3792
3793
164
  if ((readlen = fread(keybuf, 1, fsize, f)) != fsize) {
3794
0
    sc_log(card->ctx, " Unable to read key\n");
3795
0
    r = SC_ERROR_WRONG_LENGTH;
3796
0
    goto err;
3797
0
  }
3798
164
  keybuf[readlen] = '\0';
3799
3800
164
  tkey = malloc(expected_keylen);
3801
164
  if (!tkey) {
3802
0
    sc_log(card->ctx, " Unable to allocate key memory");
3803
0
    r = SC_ERROR_OUT_OF_MEMORY;
3804
0
    goto err;
3805
0
  }
3806
3807
164
  if (fsize == expected_keylen) { /* it must be binary */
3808
117
    memcpy(tkey, keybuf, expected_keylen);
3809
117
  } else {
3810
    /* if the key-length is larger then binary length, we assume hex encoded */
3811
47
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Treating key as hex-encoded!\n");
3812
47
    sc_right_trim(keybuf, fsize);
3813
47
    keylen = expected_keylen;
3814
47
    r = sc_hex_to_bin((char *)keybuf, tkey, &keylen);
3815
47
    if (keylen != expected_keylen || r != 0) {
3816
46
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Error formatting key\n");
3817
46
      if (r == 0)
3818
20
        r = SC_ERROR_INCOMPATIBLE_KEY;
3819
46
      goto err;
3820
46
    }
3821
47
  }
3822
118
  *key = tkey;
3823
118
  tkey = NULL;
3824
118
  *len = expected_keylen;
3825
118
  r = SC_SUCCESS;
3826
3827
164
err:
3828
164
  if (f)
3829
164
    fclose(f);
3830
164
  if (keybuf) {
3831
164
    free(keybuf);
3832
164
  }
3833
164
  if (tkey) {
3834
46
    free(tkey);
3835
46
  }
3836
3837
164
  LOG_FUNC_RETURN(card->ctx, r);
3838
0
  return r;
3839
164
}
3840
#endif
3841
3842
/*
3843
 * will only deal with 3des for now
3844
 * assumptions include:
3845
 *  size of encrypted data is same as unencrypted
3846
 *  challenges, nonces etc  from card are less then 114 (keeps tags simple)
3847
 */
3848
3849
static int
3850
piv_general_mutual_authenticate(sc_card_t *card,
3851
    unsigned int key_ref, unsigned int alg_id)
3852
90
{
3853
90
  int r;
3854
90
#ifdef ENABLE_OPENSSL
3855
90
  int N;
3856
90
  int locked = 0;
3857
90
  u8 rbuf[4096];
3858
90
  u8 *nonce = NULL;
3859
90
  size_t nonce_len;
3860
90
  u8 *p;
3861
90
  u8 *key = NULL;
3862
90
  size_t keylen;
3863
90
  u8 *plain_text = NULL;
3864
90
  size_t plain_text_len = 0;
3865
90
  u8 *tmp;
3866
90
  size_t tmplen, tmplen2;
3867
90
  u8 *built = NULL;
3868
90
  size_t built_len;
3869
90
  const u8 *body = NULL;
3870
90
  size_t body_len;
3871
90
  const u8 *witness_data = NULL;
3872
90
  size_t witness_len;
3873
90
  const u8 *challenge_response = NULL;
3874
90
  size_t challenge_response_len;
3875
90
  u8 *decrypted_reponse = NULL;
3876
90
  size_t decrypted_reponse_len;
3877
90
  EVP_CIPHER_CTX *ctx = NULL;
3878
3879
90
  u8 sbuf[255];
3880
90
  EVP_CIPHER *cipher = NULL;
3881
3882
90
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
3883
3884
90
  ctx = EVP_CIPHER_CTX_new();
3885
90
  if (ctx == NULL) {
3886
0
    sc_log_openssl(card->ctx);
3887
0
    r = SC_ERROR_OUT_OF_MEMORY;
3888
0
    goto err;
3889
0
  }
3890
3891
90
  cipher = get_cipher_for_algo(card, alg_id);
3892
90
  if (!cipher) {
3893
1
    sc_log_openssl(card->ctx);
3894
1
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid cipher selector, none found for:  %02x\n", alg_id);
3895
1
    r = SC_ERROR_INVALID_ARGUMENTS;
3896
1
    goto err;
3897
1
  }
3898
3899
89
  r = piv_get_key(card, alg_id, &key, &keylen);
3900
89
  if (r) {
3901
11
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Error getting General Auth key\n");
3902
11
    goto err;
3903
11
  }
3904
3905
78
  r = sc_lock(card);
3906
78
  if (r != SC_SUCCESS) {
3907
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "sc_lock failed\n");
3908
0
    goto err; /* cleanup */
3909
0
  }
3910
78
  locked = 1;
3911
3912
78
  p = sbuf;
3913
78
  *p++ = 0x7C;
3914
78
  *p++ = 0x02;
3915
78
  *p++ = 0x80;
3916
78
  *p++ = 0x00;
3917
3918
  /* get the encrypted nonce */
3919
78
  r = piv_general_io(card, 0x87, alg_id, key_ref, sbuf, p - sbuf, rbuf, sizeof rbuf);
3920
3921
78
  if (r < 0)
3922
7
    goto err;
3923
3924
  /* Remove the encompassing outer TLV of 0x7C and get the data */
3925
71
  body = sc_asn1_find_tag(card->ctx, rbuf,
3926
71
      r, 0x7C, &body_len);
3927
71
  if (!body || rbuf[0] != 0x7C) {
3928
10
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid Witness Data response of NULL\n");
3929
10
    r = SC_ERROR_INVALID_DATA;
3930
10
    goto err;
3931
10
  }
3932
3933
  /* Get the witness data indicated by the TAG 0x80 */
3934
61
  witness_data = sc_asn1_find_tag(card->ctx, body,
3935
61
      body_len, 0x80, &witness_len);
3936
61
  if (!witness_len || body_len == 0 || body[0] != 0x80) {
3937
14
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid Challenge Data none found in TLV\n");
3938
14
    r = SC_ERROR_INVALID_DATA;
3939
14
    goto err;
3940
14
  }
3941
3942
  /* Allocate an output buffer for openssl */
3943
47
  plain_text = malloc(witness_len);
3944
47
  if (!plain_text) {
3945
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not allocate buffer for plain text\n");
3946
0
    r = SC_ERROR_INTERNAL;
3947
0
    goto err;
3948
0
  }
3949
3950
  /* decrypt the data from the card */
3951
47
  if (!EVP_DecryptInit(ctx, cipher, key, NULL)) {
3952
    /* may fail if des parity of key is wrong. depends on OpenSSL options */
3953
0
    sc_log_openssl(card->ctx);
3954
0
    r = SC_ERROR_INTERNAL;
3955
0
    goto err;
3956
0
  }
3957
47
  EVP_CIPHER_CTX_set_padding(ctx, 0);
3958
3959
47
  p = plain_text;
3960
47
  if (!EVP_DecryptUpdate(ctx, p, &N, witness_data, (int)witness_len)) {
3961
0
    sc_log_openssl(card->ctx);
3962
0
    r = SC_ERROR_INTERNAL;
3963
0
    goto err;
3964
0
  }
3965
47
  plain_text_len = tmplen = N;
3966
47
  p += tmplen;
3967
3968
47
  if (!EVP_DecryptFinal(ctx, p, &N)) {
3969
1
    sc_log_openssl(card->ctx);
3970
1
    r = SC_ERROR_INTERNAL;
3971
1
    goto err;
3972
1
  }
3973
46
  tmplen = N;
3974
46
  plain_text_len += tmplen;
3975
3976
46
  if (plain_text_len != witness_len) {
3977
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
3978
0
        "Encrypted and decrypted lengths do not match: %zu:%zu\n",
3979
0
        witness_len, plain_text_len);
3980
0
    r = SC_ERROR_INTERNAL;
3981
0
    goto err;
3982
0
  }
3983
3984
  /* Build a response to the card of:
3985
   * [GEN AUTH][ 80<decrypted witness>81 <challenge> ]
3986
   * Start by computing the nonce for <challenge> the
3987
   * nonce length should match the witness length of
3988
   * the card.
3989
   */
3990
46
  nonce = malloc(witness_len);
3991
46
  if (!nonce) {
3992
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
3993
0
        "OOM allocating nonce (%zu : %zu)\n",
3994
0
        witness_len, plain_text_len);
3995
0
    r = SC_ERROR_INTERNAL;
3996
0
    goto err;
3997
0
  }
3998
46
  nonce_len = witness_len;
3999
4000
46
  r = RAND_bytes(nonce, (int)witness_len);
4001
46
  if (!r) {
4002
0
    sc_log_openssl(card->ctx);
4003
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
4004
0
        "Generating random for nonce (%zu : %zu)\n",
4005
0
        witness_len, plain_text_len);
4006
0
    r = SC_ERROR_INTERNAL;
4007
0
    goto err;
4008
0
  }
4009
4010
  /* nonce for challenge */
4011
46
  r = sc_asn1_put_tag(0x81, NULL, witness_len, NULL, 0, NULL);
4012
46
  if (r <= 0) {
4013
0
    r = SC_ERROR_INTERNAL;
4014
0
    goto err;
4015
0
  }
4016
46
  tmplen = r;
4017
4018
  /* plain text witness keep a length separate for the 0x7C tag */
4019
46
  r = sc_asn1_put_tag(0x80, NULL, witness_len, NULL, 0, NULL);
4020
46
  if (r <= 0) {
4021
0
    r = SC_ERROR_INTERNAL;
4022
0
    goto err;
4023
0
  }
4024
46
  tmplen += r;
4025
46
  tmplen2 = tmplen;
4026
4027
  /* outside 7C tag with 81:80 as innards */
4028
46
  r = sc_asn1_put_tag(0x7C, NULL, tmplen, NULL, 0, NULL);
4029
46
  if (r <= 0) {
4030
0
    r = SC_ERROR_INTERNAL;
4031
0
    goto err;
4032
0
  }
4033
4034
46
  built_len = r;
4035
4036
  /* Build the response buffer */
4037
46
  p = built = malloc(built_len);
4038
46
  if (!built) {
4039
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "OOM Building witness response and challenge\n");
4040
0
    r = SC_ERROR_INTERNAL;
4041
0
    goto err;
4042
0
  }
4043
4044
46
  p = built;
4045
4046
  /* Start with the 7C Tag */
4047
46
  r = sc_asn1_put_tag(0x7C, NULL, tmplen2, p, built_len, &p);
4048
46
  if (r != SC_SUCCESS) {
4049
0
    goto err;
4050
0
  }
4051
4052
  /* Add the DECRYPTED witness, tag 0x80 */
4053
46
  r = sc_asn1_put_tag(0x80, plain_text, witness_len, p, built_len - (p - built), &p);
4054
46
  if (r != SC_SUCCESS) {
4055
0
    goto err;
4056
0
  }
4057
4058
  /* Add the challenge, tag 0x81 */
4059
46
  r = sc_asn1_put_tag(0x81, nonce, witness_len, p, built_len - (p - built), &p);
4060
46
  if (r != SC_SUCCESS) {
4061
0
    goto err;
4062
0
  }
4063
4064
  /* Send constructed data */
4065
46
  r = piv_general_io(card, 0x87, alg_id, key_ref, built, built_len, rbuf, sizeof rbuf);
4066
46
  if (r < 0) {
4067
13
    goto err;
4068
13
  }
4069
4070
  /* Remove the encompassing outer TLV of 0x7C and get the data */
4071
33
  body = sc_asn1_find_tag(card->ctx, rbuf,
4072
33
      r, 0x7C, &body_len);
4073
33
  if (!body || rbuf[0] != 0x7C) {
4074
10
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not find outer tag 0x7C in response");
4075
10
    r = SC_ERROR_INVALID_DATA;
4076
10
    goto err;
4077
10
  }
4078
4079
  /* SP800-73 not clear if  80 or 82 */
4080
23
  challenge_response = sc_asn1_find_tag(card->ctx, body,
4081
23
      body_len, 0x82, &challenge_response_len);
4082
23
  if (!challenge_response) {
4083
19
    challenge_response = sc_asn1_find_tag(card->ctx, body,
4084
19
        body_len, 0x80, &challenge_response_len);
4085
19
    if (!challenge_response) {
4086
3
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not find tag 0x82 or 0x80 in response");
4087
3
      r = SC_ERROR_INVALID_DATA;
4088
3
      goto err;
4089
3
    }
4090
19
  }
4091
4092
  /* Decrypt challenge and check against nonce */
4093
20
  decrypted_reponse = malloc(challenge_response_len);
4094
20
  if (!decrypted_reponse) {
4095
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "OOM Allocating decryption buffer");
4096
0
    r = SC_ERROR_INVALID_DATA;
4097
0
    goto err;
4098
0
  }
4099
4100
20
  EVP_CIPHER_CTX_reset(ctx);
4101
4102
20
  if (!EVP_DecryptInit(ctx, cipher, key, NULL)) {
4103
0
    sc_log_openssl(card->ctx);
4104
0
    r = SC_ERROR_INTERNAL;
4105
0
    goto err;
4106
0
  }
4107
20
  EVP_CIPHER_CTX_set_padding(ctx, 0);
4108
4109
20
  tmp = decrypted_reponse;
4110
20
  if (!EVP_DecryptUpdate(ctx, tmp, &N, challenge_response, (int)challenge_response_len)) {
4111
0
    sc_log_openssl(card->ctx);
4112
0
    r = SC_ERROR_INTERNAL;
4113
0
    goto err;
4114
0
  }
4115
20
  decrypted_reponse_len = tmplen = N;
4116
20
  tmp += tmplen;
4117
4118
20
  if (!EVP_DecryptFinal(ctx, tmp, &N)) {
4119
2
    sc_log_openssl(card->ctx);
4120
2
    r = SC_ERROR_INTERNAL;
4121
2
    goto err;
4122
2
  }
4123
18
  tmplen = N;
4124
18
  decrypted_reponse_len += tmplen;
4125
4126
18
  if (decrypted_reponse_len != nonce_len || memcmp(nonce, decrypted_reponse, nonce_len) != 0) {
4127
18
    sc_log(card->ctx,
4128
18
        "mutual authentication failed, card returned wrong value %zu:%zu",
4129
18
        decrypted_reponse_len, nonce_len);
4130
18
    r = SC_ERROR_DECRYPT_FAILED;
4131
18
    goto err;
4132
18
  }
4133
0
  r = SC_SUCCESS;
4134
4135
90
err:
4136
90
  sc_evp_cipher_free(cipher);
4137
90
  if (ctx)
4138
90
    EVP_CIPHER_CTX_free(ctx);
4139
90
  if (locked)
4140
78
    sc_unlock(card);
4141
90
  if (decrypted_reponse)
4142
20
    free(decrypted_reponse);
4143
90
  if (built)
4144
46
    free(built);
4145
90
  if (plain_text)
4146
47
    free(plain_text);
4147
90
  if (nonce)
4148
46
    free(nonce);
4149
90
  if (key)
4150
78
    free(key);
4151
4152
#else
4153
  sc_log(card->ctx, "OpenSSL Required");
4154
  r = SC_ERROR_NOT_SUPPORTED;
4155
#endif /* ENABLE_OPENSSL */
4156
4157
90
  LOG_FUNC_RETURN(card->ctx, r);
4158
90
}
4159
4160
/* Currently only used for card administration */
4161
static int
4162
piv_general_external_authenticate(sc_card_t *card,
4163
    unsigned int key_ref, unsigned int alg_id)
4164
76
{
4165
76
  int r;
4166
76
#ifdef ENABLE_OPENSSL
4167
76
  size_t tmplen;
4168
76
  int outlen;
4169
76
  int locked = 0;
4170
76
  u8 *p;
4171
76
  u8 rbuf[4096];
4172
76
  u8 *key = NULL;
4173
76
  u8 *cipher_text = NULL;
4174
76
  u8 *output_buf = NULL;
4175
76
  const u8 *body = NULL;
4176
76
  const u8 *challenge_data = NULL;
4177
76
  size_t body_len;
4178
76
  size_t output_len;
4179
76
  size_t challenge_len;
4180
76
  size_t keylen = 0;
4181
76
  size_t cipher_text_len = 0;
4182
76
  u8 sbuf[255];
4183
76
  EVP_CIPHER_CTX *ctx = NULL;
4184
76
  EVP_CIPHER *cipher = NULL;
4185
4186
76
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
4187
4188
76
  ctx = EVP_CIPHER_CTX_new();
4189
76
  if (ctx == NULL) {
4190
0
    sc_log_openssl(card->ctx);
4191
0
    r = SC_ERROR_OUT_OF_MEMORY;
4192
0
    goto err;
4193
0
  }
4194
4195
76
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Selected cipher for algorithm id: %02x\n", alg_id);
4196
4197
76
  cipher = get_cipher_for_algo(card, alg_id);
4198
76
  if (!cipher) {
4199
1
    sc_log_openssl(card->ctx);
4200
1
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid cipher selector, none found for:  %02x\n", alg_id);
4201
1
    r = SC_ERROR_INVALID_ARGUMENTS;
4202
1
    goto err;
4203
1
  }
4204
4205
75
  r = piv_get_key(card, alg_id, &key, &keylen);
4206
75
  if (r) {
4207
35
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Error getting General Auth key\n");
4208
35
    goto err;
4209
35
  }
4210
4211
40
  r = sc_lock(card);
4212
40
  if (r != SC_SUCCESS) {
4213
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "sc_lock failed\n");
4214
0
    goto err; /* cleanup */
4215
0
  }
4216
40
  locked = 1;
4217
4218
40
  p = sbuf;
4219
40
  *p++ = 0x7C;
4220
40
  *p++ = 0x02;
4221
40
  *p++ = 0x81;
4222
40
  *p++ = 0x00;
4223
4224
  /* get a challenge */
4225
40
  r = piv_general_io(card, 0x87, alg_id, key_ref, sbuf, p - sbuf, rbuf, sizeof rbuf);
4226
40
  if (r < 0) {
4227
6
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Error getting Challenge\n");
4228
6
    goto err;
4229
6
  }
4230
4231
  /*
4232
   * the value here corresponds with the response size, so we use this
4233
   * to alloc the response buffer, rather than re-computing it.
4234
   */
4235
34
  output_len = r;
4236
4237
  /* Remove the encompassing outer TLV of 0x7C and get the data */
4238
34
  body = sc_asn1_find_tag(card->ctx, rbuf,
4239
34
      r, 0x7C, &body_len);
4240
34
  if (!body || rbuf[0] != 0x7C) {
4241
11
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid Challenge Data response of NULL\n");
4242
11
    r = SC_ERROR_INVALID_DATA;
4243
11
    goto err;
4244
11
  }
4245
4246
  /* Get the challenge data indicated by the TAG 0x81 */
4247
23
  challenge_data = sc_asn1_find_tag(card->ctx, body,
4248
23
      body_len, 0x81, &challenge_len);
4249
23
  if (!challenge_data) {
4250
2
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Invalid Challenge Data none found in TLV\n");
4251
2
    r = SC_ERROR_INVALID_DATA;
4252
2
    goto err;
4253
2
  }
4254
4255
  /* Store this to sanity check that plaintext length and ciphertext lengths match */
4256
21
  tmplen = challenge_len;
4257
4258
  /* Encrypt the challenge with the secret */
4259
21
  if (!EVP_EncryptInit(ctx, cipher, key, NULL)) {
4260
0
    sc_log_openssl(card->ctx);
4261
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Encrypt fail\n");
4262
0
    r = SC_ERROR_INTERNAL;
4263
0
    goto err;
4264
0
  }
4265
4266
21
  cipher_text = malloc(challenge_len);
4267
21
  if (!cipher_text) {
4268
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not allocate buffer for cipher text\n");
4269
0
    r = SC_ERROR_INTERNAL;
4270
0
    goto err;
4271
0
  }
4272
4273
21
  EVP_CIPHER_CTX_set_padding(ctx, 0);
4274
21
  if (!EVP_EncryptUpdate(ctx, cipher_text, &outlen, challenge_data, (int)challenge_len)) {
4275
0
    sc_log_openssl(card->ctx);
4276
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Encrypt update fail\n");
4277
0
    r = SC_ERROR_INTERNAL;
4278
0
    goto err;
4279
0
  }
4280
21
  cipher_text_len += outlen;
4281
4282
21
  if (!EVP_EncryptFinal(ctx, cipher_text + cipher_text_len, &outlen)) {
4283
1
    sc_log_openssl(card->ctx);
4284
1
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Final fail\n");
4285
1
    r = SC_ERROR_INTERNAL;
4286
1
    goto err;
4287
1
  }
4288
20
  cipher_text_len += outlen;
4289
4290
  /*
4291
   * Actually perform the sanity check on lengths plaintext length vs
4292
   * encrypted length
4293
   */
4294
20
  if (cipher_text_len != tmplen) {
4295
0
    sc_log_openssl(card->ctx);
4296
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Length test fail\n");
4297
0
    r = SC_ERROR_INTERNAL;
4298
0
    goto err;
4299
0
  }
4300
4301
20
  output_buf = malloc(output_len);
4302
20
  if (!output_buf) {
4303
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not allocate output buffer: %s\n",
4304
0
        strerror(errno));
4305
0
    r = SC_ERROR_INTERNAL;
4306
0
    goto err;
4307
0
  }
4308
4309
20
  p = output_buf;
4310
4311
  /*
4312
   * Build: 7C<len>[82<len><challenge>]
4313
   * Start off by capturing the data of the response:
4314
   *     - 82<len><encrypted challenege response>
4315
   * Build the outside TLV (7C)
4316
   * Advance past that tag + len
4317
   * Build the body (82)
4318
   * memcopy the body past the 7C<len> portion
4319
   * Transmit
4320
   */
4321
20
  tmplen = sc_asn1_put_tag(0x82, NULL, cipher_text_len, NULL, 0, NULL);
4322
20
  if (tmplen <= 0) {
4323
0
    r = SC_ERROR_INTERNAL;
4324
0
    goto err;
4325
0
  }
4326
4327
20
  r = sc_asn1_put_tag(0x7C, NULL, tmplen, p, output_len, &p);
4328
20
  if (r != SC_SUCCESS) {
4329
0
    goto err;
4330
0
  }
4331
4332
  /* Build the 0x82 TLV and append to the 7C<len> tag */
4333
20
  r = sc_asn1_put_tag(0x82, cipher_text, cipher_text_len, p, output_len - (p - output_buf), &p);
4334
20
  if (r != SC_SUCCESS) {
4335
0
    goto err;
4336
0
  }
4337
4338
  /* Sanity check the lengths again */
4339
20
  tmplen = sc_asn1_put_tag(0x7C, NULL, tmplen, NULL, 0, NULL);
4340
20
  if (output_len != (size_t)tmplen) {
4341
17
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Allocated and computed lengths do not match! "
4342
17
                "Expected %zd, found: %zu\n",
4343
17
        output_len, tmplen);
4344
17
    r = SC_ERROR_INTERNAL;
4345
17
    goto err;
4346
17
  }
4347
4348
3
  r = piv_general_io(card, 0x87, alg_id, key_ref, output_buf, output_len, NULL, 0);
4349
3
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Got response  challenge\n");
4350
4351
76
err:
4352
76
  sc_evp_cipher_free(cipher);
4353
76
  if (ctx)
4354
76
    EVP_CIPHER_CTX_free(ctx);
4355
4356
76
  if (locked)
4357
40
    sc_unlock(card);
4358
4359
76
  if (key) {
4360
40
    sc_mem_clear(key, keylen);
4361
40
    free(key);
4362
40
  }
4363
4364
76
  if (cipher_text)
4365
21
    free(cipher_text);
4366
4367
76
  if (output_buf)
4368
20
    free(output_buf);
4369
#else
4370
  sc_log(card->ctx, "OpenSSL Required");
4371
  r = SC_ERROR_NOT_SUPPORTED;
4372
#endif /* ENABLE_OPENSSL */
4373
4374
76
  LOG_FUNC_RETURN(card->ctx, r);
4375
76
}
4376
4377
/*
4378
 * with sp800-73-4 and SM GUID is also in sm_cvc.subjectID
4379
 */
4380
static int
4381
piv_get_serial_nr_from_CHUI(sc_card_t *card, sc_serial_number_t *serial)
4382
263
{
4383
263
  int r;
4384
263
  int i;
4385
263
  u8 gbits = 0; /* 0 not present or wrong length or all zeros */
4386
263
  u8 fbits = 0; /* 0 not present or wrong length or all zeros */
4387
263
  u8 *rbuf = NULL;
4388
263
  const u8 *body;
4389
263
  const u8 *fascn;
4390
263
  const u8 *guid;
4391
263
  size_t rbuflen = 0, bodylen, fascnlen, guidlen;
4392
4393
263
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
4394
263
  if (card->serialnr.len) {
4395
0
    *serial = card->serialnr;
4396
0
    LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
4397
0
  }
4398
4399
  /*
4400
   * 800-73-3 Part 1 and CIO Council docs say for PIV Compatible cards
4401
   * the FASC-N Agency code should be 9999 and there should be a GUID
4402
   * based on RFC 4122. If GUID present and not zero
4403
   * we will use the GUID as the serial number.
4404
   */
4405
4406
263
  r = piv_get_cached_data(card, PIV_OBJ_CHUI, &rbuf, &rbuflen);
4407
263
  LOG_TEST_RET(card->ctx, r, "Failure retrieving CHUI");
4408
4409
106
  r = SC_ERROR_INTERNAL;
4410
106
  if (rbuflen != 0) {
4411
106
    body = sc_asn1_find_tag(card->ctx, rbuf, rbuflen, 0x53, &bodylen); /* Pass the outer wrapper asn1 */
4412
106
    if (body != NULL && bodylen != 0 && rbuf[0] == 0x53) {
4413
103
      fascn = sc_asn1_find_tag(card->ctx, body, bodylen, 0x30, &fascnlen); /* Find the FASC-N data */
4414
4415
103
      if (fascn && fascnlen == 25) {
4416
1.32k
        for (i = 0; i < 25; i++) {
4417
1.27k
          fbits = fbits || fascn[i]; /* if all are zero, gbits will be zero */
4418
1.27k
        }
4419
51
      }
4420
4421
103
      guid = sc_asn1_find_tag(card->ctx, body, bodylen, 0x34, &guidlen);
4422
4423
103
      if (guid && guidlen == 16) {
4424
697
        for (i = 0; i < 16; i++) {
4425
656
          gbits = gbits | guid[i]; /* if all are zero, gbits will be zero */
4426
656
        }
4427
41
      }
4428
103
      sc_log(card->ctx, "fascn=%p,fascnlen=%zu,guid=%p,guidlen=%zu,gbits=%2.2x",
4429
103
          fascn, fascnlen, guid, guidlen, gbits);
4430
4431
103
      if (fascn && fascnlen == 25 && fbits) {
4432
        /* test if guid and the fascn starts with ;9999 (in ISO 4bit + parity code) */
4433
        /* ;9999 is non-gov issued FASC-N, will use FASC-N for gov issued if no guid */
4434
49
        if (!(gbits && fascn[0] == 0xD4 && fascn[1] == 0xE7 &&
4435
48
                fascn[2] == 0x39 && (fascn[3] | 0x7F) == 0xFF)) {
4436
          /* fascnlen is 25 */
4437
48
          serial->len = fascnlen;
4438
48
          memcpy(serial->value, fascn, serial->len);
4439
48
          r = SC_SUCCESS;
4440
48
          gbits = 0; /* set to skip using guid below */
4441
48
        }
4442
49
      }
4443
103
      if (guid && guidlen == 16 && gbits) {
4444
9
        serial->len = guidlen;
4445
9
        memcpy(serial->value, guid, serial->len);
4446
9
        r = SC_SUCCESS;
4447
9
      }
4448
103
    }
4449
106
  }
4450
4451
106
  if (fbits == 0 && gbits == 0) { /* were not able to set the serial number */
4452
49
    serial->len = 16;
4453
49
    memset(serial->value, 0x00, serial->len);
4454
49
    r = SC_ERROR_INTERNAL;
4455
49
  }
4456
4457
106
  card->serialnr = *serial;
4458
106
  LOG_FUNC_RETURN(card->ctx, r);
4459
106
}
4460
4461
/*
4462
 * If the object can not be present on the card, because the History
4463
 * object is not present or the History object says its not present,
4464
 * return 1. If object may be present return 0.
4465
 * Cuts down on overhead, by not showing non existent objects to pkcs11
4466
 * The path for the object is passed in and the first 2 bytes are used.
4467
 * Note: If the History or Discovery object is not found the
4468
 * PIV_OBJ_CACHE_NOT_PRESENT is set, as older cards do not have these.
4469
 * pkcs15-piv.c calls this via cardctl.
4470
 */
4471
4472
static int
4473
piv_is_object_present(sc_card_t *card, u8 *ptr)
4474
0
{
4475
0
  piv_private_data_t *priv = PIV_DATA(card);
4476
0
  int r = 0;
4477
0
  int enumtag;
4478
4479
0
  enumtag = piv_find_obj_by_containerid(card, ptr);
4480
0
  if (enumtag >= 0 && priv->obj_cache[enumtag].flags & PIV_OBJ_CACHE_NOT_PRESENT)
4481
0
    r = 1;
4482
4483
0
  LOG_FUNC_RETURN(card->ctx, r);
4484
0
}
4485
4486
/*
4487
 * NIST 800-73-3 allows the default pin to be the PIV application 0x80
4488
 * or the global pin for the card 0x00. Look at Discovery object to get this.
4489
 * called by pkcs15-piv.c  via cardctl when setting up the pins.
4490
 */
4491
static int
4492
piv_get_pin_preference(sc_card_t *card, int *pin_ref)
4493
0
{
4494
0
  piv_private_data_t *priv = PIV_DATA(card);
4495
4496
0
  *pin_ref = priv->pin_preference;
4497
0
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
4498
0
}
4499
4500
static int
4501
piv_yk_metadata_get_policy(sc_context_t *ctx, u8 *buf, size_t buflen, u8 *pin, u8 *touch)
4502
0
{
4503
0
  size_t policylen;
4504
0
  const u8 *policy = sc_asn1_find_tag(ctx, buf, buflen, 0x02, &policylen);
4505
0
  if (policy && policylen == 2) {
4506
0
    *pin = policy[0];
4507
0
    *touch = policy[1];
4508
0
    return SC_SUCCESS;
4509
0
  } else {
4510
0
    sc_log(ctx, "Yubikey PIN policy not found");
4511
0
    return SC_ERROR_DATA_OBJECT_NOT_FOUND;
4512
0
  }
4513
0
}
4514
4515
static int
4516
piv_yk_metadata_get_pubkey_info(sc_context_t *ctx, u8 *buf, size_t buflen, yk_slot_info_t *info)
4517
0
{
4518
0
  size_t tag_len = 0;
4519
0
  const u8 *pk = NULL;
4520
4521
  /*  Tag 0x01: Algorithm/type of key */
4522
0
  pk = sc_asn1_find_tag(ctx, buf, buflen, 0x01, &tag_len);
4523
0
  if (pk && tag_len == 1) {
4524
0
    info->algorithm = pk[0];
4525
0
  } else {
4526
0
    sc_log(ctx, "Yubikey algorithm not found");
4527
0
    return SC_ERROR_DATA_OBJECT_NOT_FOUND;
4528
0
  }
4529
4530
  /*  Tag 0x04: Public key */
4531
0
  pk = sc_asn1_find_tag(ctx, buf, buflen, 0x04, &tag_len);
4532
0
  if (pk && tag_len > 0) {
4533
0
    info->pubkey.value = malloc(tag_len);
4534
0
    if (info->pubkey.value == NULL) {
4535
0
      return SC_ERROR_MEMORY_FAILURE;
4536
0
    }
4537
0
    memcpy(info->pubkey.value, pk, tag_len);
4538
0
    info->pubkey.len = tag_len;
4539
0
  } else {
4540
0
    sc_log(ctx, "Yubikey public key not found");
4541
0
    return SC_ERROR_DATA_OBJECT_NOT_FOUND;
4542
0
  }
4543
4544
0
  return SC_SUCCESS;
4545
0
}
4546
4547
static int
4548
piv_yk_get_metadata(sc_card_t *card, u8 slot, u8 *pin_policy, u8 *touch_policy, sc_cardctl_piv_pubkey_info_t *info)
4549
0
{
4550
0
  u8 resp[3072]; /* Should be enough to fit ML-DSA-87 key */
4551
0
  int resplen = 0;
4552
0
  size_t i;
4553
0
  piv_private_data_t *priv = PIV_DATA(card);
4554
0
  int rc;
4555
4556
  /* initialize with the default behaviour */
4557
0
  if (pin_policy)
4558
0
    *pin_policy = 0x00; /* i.e. use NIST defined */
4559
0
  if (touch_policy)
4560
0
    *touch_policy = 0x00;
4561
0
  if (info) {
4562
0
    info->algorithm = 0;
4563
0
    info->pubkey.value = NULL;
4564
0
    info->pubkey.len = 0;
4565
0
  }
4566
4567
0
  if (priv->yubico_version < 0x00050300) {
4568
0
    if (priv->yubico_version != 0)
4569
0
      sc_log(card->ctx, "Yubikey's Get metadata extension not available");
4570
0
    return SC_ERROR_NOT_SUPPORTED;
4571
0
  }
4572
4573
0
  for (i = 0; i < (PIV_NUM_YK_SLOT_INFO - 1); i++) {
4574
0
    if (priv->yk_slot_info[i].slot == 0x00)
4575
      /* reached the last initialized entry */
4576
0
      break;
4577
4578
0
    if (priv->yk_slot_info[i].slot == slot) {
4579
      /* metadata already initialized */
4580
0
      if (priv->yk_slot_info[i].invalid)
4581
        /* already failed don't try again */
4582
0
        return SC_ERROR_NOT_SUPPORTED;
4583
0
      break;
4584
0
    }
4585
0
  }
4586
4587
0
  if (priv->yk_slot_info[i].slot == 0x00) {
4588
    /* initialize this entry */
4589
0
    rc = piv_general_io(card, 0xF7, 0x00, slot, NULL, 0, resp, sizeof(resp));
4590
4591
0
    if (rc >= 0) { /* set defaults */
4592
0
      priv->yk_slot_info[i].slot = slot;
4593
0
    }
4594
4595
0
    if (rc > 2) { /* at least 1 TLV */
4596
0
      resplen = rc;
4597
0
      rc = piv_yk_metadata_get_policy(card->ctx, resp, resplen,
4598
0
          &priv->yk_slot_info[i].policy, &priv->yk_slot_info[i].touch);
4599
0
      if (SC_SUCCESS == rc) {
4600
0
        sc_log(card->ctx, "PIN policy for slot 0x%02X: 0x%02X (touch 0x%02X)",
4601
0
            slot, priv->yk_slot_info[i].policy, priv->yk_slot_info[i].touch);
4602
0
      }
4603
0
      rc = piv_yk_metadata_get_pubkey_info(card->ctx, resp, resplen, &priv->yk_slot_info[i]);
4604
0
      if (SC_SUCCESS == rc) {
4605
0
        sc_log(card->ctx, "Public key for slot 0x%02X: present", slot);
4606
0
      }
4607
0
    } else {
4608
0
      sc_log(card->ctx, "Could not get Yubikey's PIN and touch policy");
4609
0
      priv->yk_slot_info[i].invalid = 1;
4610
0
      return SC_ERROR_NOT_SUPPORTED;
4611
0
    }
4612
0
  } else if (priv->yk_slot_info[i].slot != slot) {
4613
0
    sc_log(card->ctx, "No free slot found");
4614
0
    return SC_ERROR_INTERNAL;
4615
0
  }
4616
4617
0
  if (pin_policy)
4618
0
    *pin_policy = priv->yk_slot_info[i].policy;
4619
0
  if (touch_policy)
4620
0
    *touch_policy = priv->yk_slot_info[i].touch;
4621
0
  if (info) {
4622
0
    info->algorithm = priv->yk_slot_info[i].algorithm;
4623
0
    info->pubkey.value = priv->yk_slot_info[i].pubkey.value;
4624
0
    info->pubkey.len = priv->yk_slot_info[i].pubkey.len;
4625
0
  }
4626
4627
0
  return SC_SUCCESS;
4628
0
}
4629
4630
static int
4631
piv_yk_pin_policy(sc_card_t *card, u8 *ptr)
4632
0
{
4633
0
  u8 slot = *ptr;
4634
0
  LOG_FUNC_RETURN(card->ctx, piv_yk_get_metadata(card, slot, ptr, NULL, NULL));
4635
0
}
4636
4637
static int
4638
piv_yk_get_pubkey(sc_card_t *card, sc_cardctl_piv_pubkey_info_t *info)
4639
0
{
4640
0
  int rc;
4641
0
  u8 slot = info->slot;
4642
4643
0
  rc = piv_yk_get_metadata(card, slot, NULL, NULL, info);
4644
0
  LOG_TEST_RET(card->ctx, rc, "piv_yk_get_metadata failed");
4645
0
  if (info->pubkey.value == NULL || info->pubkey.len == 0 || info->algorithm == 0) {
4646
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_DATA_OBJECT_NOT_FOUND);
4647
0
  }
4648
4649
0
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
4650
0
}
4651
4652
static int
4653
piv_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
4654
559
{
4655
559
  piv_private_data_t *priv = PIV_DATA(card);
4656
559
  u8 *opts; /*  A or M, key_ref, alg_id */
4657
4658
559
  LOG_FUNC_CALLED(card->ctx);
4659
4660
559
  if (priv == NULL) {
4661
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
4662
0
  }
4663
559
  switch (cmd) {
4664
166
  case SC_CARDCTL_PIV_AUTHENTICATE:
4665
166
    opts = (u8 *)ptr;
4666
166
    switch (*opts) {
4667
76
    case 'A':
4668
76
      return piv_general_external_authenticate(card,
4669
76
          *(opts + 1), *(opts + 2));
4670
0
      break;
4671
90
    case 'M':
4672
90
      return piv_general_mutual_authenticate(card,
4673
90
          *(opts + 1), *(opts + 2));
4674
0
      break;
4675
166
    }
4676
0
    break;
4677
130
  case SC_CARDCTL_PIV_GENERATE_KEY:
4678
130
    return piv_generate_key(card,
4679
130
        (sc_cardctl_piv_genkey_info_t *)ptr);
4680
0
    break;
4681
263
  case SC_CARDCTL_GET_SERIALNR:
4682
263
    return piv_get_serial_nr_from_CHUI(card, (sc_serial_number_t *)ptr);
4683
0
    break;
4684
0
  case SC_CARDCTL_PIV_PIN_PREFERENCE:
4685
0
    return piv_get_pin_preference(card, ptr);
4686
0
    break;
4687
0
  case SC_CARDCTL_PIV_OBJECT_PRESENT:
4688
0
    return piv_is_object_present(card, ptr);
4689
0
    break;
4690
0
  case SC_CARDCTL_PIV_YK_PIN_POLICY:
4691
0
    return piv_yk_pin_policy(card, ptr);
4692
0
    break;
4693
0
  case SC_CARDCTL_PIV_YK_GET_PUBKEY_INFO:
4694
0
    return piv_yk_get_pubkey(card, ptr);
4695
0
    break;
4696
559
  }
4697
4698
0
  LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
4699
0
}
4700
4701
static int
4702
piv_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
4703
0
{
4704
  /* Dynamic Authentication Template (Challenge) */
4705
0
  u8 sbuf[] = {0x7c, 0x02, 0x81, 0x00};
4706
0
  u8 rbuf[4096];
4707
0
  const u8 *p;
4708
0
  size_t out_len = 0;
4709
0
  int r;
4710
0
  unsigned int tag_out = 0, cla_out = 0;
4711
0
  piv_private_data_t *priv = PIV_DATA(card);
4712
4713
0
  LOG_FUNC_CALLED(card->ctx);
4714
4715
0
  if (priv->card_issues & CI_NO_RANDOM) {
4716
0
    r = SC_ERROR_NOT_SUPPORTED;
4717
0
    LOG_TEST_GOTO_ERR(card->ctx, r, "No support for random data");
4718
0
  }
4719
4720
  /* NIST 800-73-3 says use 9B, previous versions used 00 */
4721
0
  r = piv_general_io(card, 0x87, 0x00, 0x9B, sbuf, sizeof sbuf, rbuf, sizeof rbuf);
4722
  /*
4723
   * piv_get_challenge is called in a loop.
4724
   * some cards may allow 1 challenge expecting it to be part of
4725
   * NIST 800-73-3 part 2 "Authentication of PIV Card Application Administrator"
4726
   * and return "6A 80" if last command was a get_challenge.
4727
   * Now that the card returned error, we can try one more time.
4728
   */
4729
0
  if (r == SC_ERROR_INCORRECT_PARAMETERS) {
4730
0
    r = piv_general_io(card, 0x87, 0x00, 0x9B, sbuf, sizeof sbuf, rbuf, sizeof rbuf);
4731
0
    if (r == SC_ERROR_INCORRECT_PARAMETERS) {
4732
0
      r = SC_ERROR_NOT_SUPPORTED;
4733
0
    }
4734
0
  }
4735
0
  LOG_TEST_GOTO_ERR(card->ctx, r, "GENERAL AUTHENTICATE failed");
4736
4737
0
  p = rbuf;
4738
0
  r = sc_asn1_read_tag(&p, r, &cla_out, &tag_out, &out_len);
4739
0
  if (r < 0 || (cla_out | tag_out) != 0x7C) {
4740
0
    r = SC_ERROR_INVALID_DATA;
4741
0
    LOG_TEST_GOTO_ERR(card->ctx, r, "Can't find Dynamic Authentication Template");
4742
0
  }
4743
4744
0
  r = sc_asn1_read_tag(&p, out_len, &cla_out, &tag_out, &out_len);
4745
0
  if (r < 0 || (cla_out | tag_out) != 0x81) {
4746
0
    r = SC_ERROR_INVALID_DATA;
4747
0
    LOG_TEST_GOTO_ERR(card->ctx, r, "Can't find Challenge");
4748
0
  }
4749
4750
0
  if (len < out_len) {
4751
0
    out_len = len;
4752
0
  }
4753
0
  memcpy(rnd, p, out_len);
4754
4755
0
  r = (int)out_len;
4756
4757
0
err:
4758
0
  LOG_FUNC_RETURN(card->ctx, r);
4759
0
}
4760
4761
static int
4762
piv_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
4763
0
{
4764
0
  piv_private_data_t *priv = PIV_DATA(card);
4765
0
  int r = 0;
4766
4767
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
4768
4769
0
  sc_log(card->ctx, "flags=%08lx op=%d alg=%lu algf=%08lx algr=%08lx kr0=%02x, krfl=%zu",
4770
0
      env->flags, env->operation, env->algorithm, env->algorithm_flags,
4771
0
      env->algorithm_ref, env->key_ref[0], env->key_ref_len);
4772
4773
0
  priv->operation = env->operation;
4774
0
  priv->algorithm = env->algorithm;
4775
4776
0
  if (env->algorithm == SC_ALGORITHM_RSA) {
4777
0
    priv->alg_id = 0x06; /* Say it is RSA, set 5, 6, 7 later */
4778
0
  } else if (env->algorithm == SC_ALGORITHM_EC) {
4779
0
    if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) {
4780
0
      switch (env->algorithm_ref) {
4781
0
      case 256:
4782
0
        priv->alg_id = 0x11; /* Say it is EC 256 */
4783
0
        priv->key_size = 256;
4784
0
        break;
4785
0
      case 384:
4786
0
        priv->alg_id = 0x14;
4787
0
        priv->key_size = 384;
4788
0
        break;
4789
0
      default:
4790
0
        r = SC_ERROR_NO_CARD_SUPPORT;
4791
0
      }
4792
0
    } else
4793
0
      r = SC_ERROR_NO_CARD_SUPPORT;
4794
0
  } else if (env->algorithm == SC_ALGORITHM_EDDSA) {
4795
0
    priv->alg_id = 0xE0;
4796
0
    priv->key_size = 255;
4797
0
  } else if (env->algorithm == SC_ALGORITHM_XEDDSA) {
4798
0
    priv->alg_id = 0xE1;
4799
0
    priv->key_size = 255;
4800
0
  } else
4801
0
    r = SC_ERROR_NO_CARD_SUPPORT;
4802
0
  priv->key_ref = env->key_ref[0];
4803
4804
0
  LOG_FUNC_RETURN(card->ctx, r);
4805
0
}
4806
4807
static int
4808
piv_restore_security_env(sc_card_t *card, int se_num)
4809
0
{
4810
0
  LOG_FUNC_CALLED(card->ctx);
4811
4812
0
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
4813
0
}
4814
4815
static void
4816
piv_yk_notify_touch_policy(sc_card_t *card, u8 key_ref)
4817
0
{
4818
0
  u8 touch_policy;
4819
0
  const char *title = "Touch your Yubikey to continue";
4820
4821
0
  piv_yk_get_metadata(card, key_ref, NULL, &touch_policy, NULL);
4822
0
  switch (touch_policy) {
4823
0
  case 0x02:
4824
0
    sc_notify(title, "Touching the token is required for unlocking the key");
4825
0
    break;
4826
0
  case 0x03:
4827
0
    sc_notify(title, "Touching the token is required unlocking the key (needed again after 15 seconds)");
4828
0
    break;
4829
0
  }
4830
0
}
4831
4832
static int
4833
piv_validate_general_authentication(sc_card_t *card,
4834
    const u8 *data, size_t datalen,
4835
    u8 *out, size_t outlen)
4836
0
{
4837
0
  piv_private_data_t *priv = PIV_DATA(card);
4838
0
  int r, tmplen, tmplen2;
4839
0
  u8 *p;
4840
0
  const unsigned char *p2;
4841
0
  size_t taglen;
4842
0
  size_t bodylen;
4843
0
  unsigned int cla, tag;
4844
0
  unsigned int real_alg_id, op_tag;
4845
4846
0
  u8 sbuf[4096]; /* needs work. for 4096 needs 512+10 or so */
4847
0
  size_t sbuflen = sizeof(sbuf);
4848
0
  u8 rbuf[4096];
4849
4850
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
4851
4852
  /* should assume large send data */
4853
0
  p = sbuf;
4854
0
  tmplen = sc_asn1_put_tag(0xff, NULL, datalen, NULL, 0, NULL);
4855
0
  tmplen2 = sc_asn1_put_tag(0x82, NULL, 0, NULL, 0, NULL);
4856
0
  if (tmplen <= 0 || tmplen2 <= 0) {
4857
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
4858
0
  }
4859
0
  tmplen += tmplen2;
4860
0
  if ((r = sc_asn1_put_tag(0x7c, NULL, tmplen, p, sbuflen, &p)) != SC_SUCCESS ||
4861
0
      (r = sc_asn1_put_tag(0x82, NULL, 0, p, sbuflen - (p - sbuf), &p)) != SC_SUCCESS) {
4862
0
    LOG_FUNC_RETURN(card->ctx, r);
4863
0
  }
4864
0
  if (priv->operation == SC_SEC_OPERATION_DERIVE && (priv->algorithm == SC_ALGORITHM_EC || priv->algorithm == SC_ALGORITHM_XEDDSA)) {
4865
0
    op_tag = 0x85;
4866
0
  } else {
4867
0
    op_tag = 0x81;
4868
0
  }
4869
0
  r = sc_asn1_put_tag(op_tag, data, datalen, p, sbuflen - (p - sbuf), &p);
4870
0
  if (r != SC_SUCCESS) {
4871
0
    LOG_FUNC_RETURN(card->ctx, r);
4872
0
  }
4873
4874
  /*
4875
   * alg_id=06 is a place holder for all RSA keys.
4876
   * Derive the real alg_id based on the size of the
4877
   * the data, as we are always using raw mode.
4878
   * Non RSA keys needs some work in this area.
4879
   */
4880
4881
0
  real_alg_id = priv->alg_id;
4882
0
  if (priv->alg_id == 0x06) {
4883
0
    switch (datalen) {
4884
0
    case 128:
4885
0
      real_alg_id = 0x06;
4886
0
      break;
4887
0
    case 256:
4888
0
      real_alg_id = 0x07;
4889
0
      break;
4890
0
    case 384:
4891
0
      real_alg_id = 0x05;
4892
0
      break;
4893
0
    case 512:
4894
0
      real_alg_id = 0x16;
4895
0
      break;
4896
0
    default:
4897
0
      SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_NO_CARD_SUPPORT);
4898
0
    }
4899
0
  }
4900
  /* EC and ED alg_id was already set */
4901
4902
0
  piv_yk_notify_touch_policy(card, priv->key_ref);
4903
0
  r = piv_general_io(card, 0x87, real_alg_id, priv->key_ref,
4904
0
      sbuf, p - sbuf, rbuf, sizeof rbuf);
4905
0
  if (r < 0)
4906
0
    goto err;
4907
4908
0
  p2 = rbuf;
4909
0
  r = sc_asn1_read_tag(&p2, r, &cla, &tag, &bodylen);
4910
0
  if (p2 == NULL || r < 0 || bodylen == 0 || (cla | tag) != 0x7C) {
4911
0
    r = SC_ERROR_INVALID_DATA;
4912
0
    LOG_TEST_GOTO_ERR(card->ctx, r, "Can't find 0x7C");
4913
0
  }
4914
4915
0
  r = sc_asn1_read_tag(&p2, bodylen, &cla, &tag, &taglen);
4916
0
  if (p2 == NULL || r < 0 || taglen == 0 || (cla | tag) != 0x82) {
4917
0
    r = SC_ERROR_INVALID_DATA;
4918
0
    LOG_TEST_GOTO_ERR(card->ctx, r, "Can't find 0x82");
4919
0
  }
4920
4921
0
  if (taglen > outlen) {
4922
0
    r = SC_ERROR_INVALID_DATA;
4923
0
    LOG_TEST_GOTO_ERR(card->ctx, r, "data read longer then buffer");
4924
0
  }
4925
4926
0
  memcpy(out, p2, taglen);
4927
0
  r = (int)taglen;
4928
4929
0
err:
4930
0
  LOG_FUNC_RETURN(card->ctx, r);
4931
0
}
4932
4933
static int
4934
piv_compute_signature(sc_card_t *card, const u8 *data, size_t datalen,
4935
    u8 *out, size_t outlen)
4936
0
{
4937
0
  piv_private_data_t *priv = PIV_DATA(card);
4938
0
  int r;
4939
0
  u8 *ecdata = NULL;
4940
0
  size_t ecdatalen = 0;
4941
0
  size_t ecpadlen = 0;
4942
0
  size_t nLen;
4943
0
  u8 rbuf[128]; /* For EC conversions  384 will fit */
4944
4945
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
4946
4947
  /* The PIV returns a DER SEQUENCE{INTEGER, INTEGER}
4948
   * Which may have leading 00 to force a positive integer
4949
   * But PKCS11 just wants 2* field_length in bytes
4950
   * So we have to strip out the integers
4951
   * and pad on left if too short.
4952
   */
4953
4954
0
  if (priv->alg_id == 0x11 || priv->alg_id == 0x14) {
4955
0
    nLen = BYTES4BITS(priv->key_size);
4956
4957
    /* One applet is known to enforce the hash size
4958
     * must match the field_length in bytes. But Windows
4959
     * may try ECDSA without a hash when offline
4960
     * So we will pad input to hash size.
4961
     */
4962
0
    if (priv->card_issues & CI_ENFORCES_EC_HASH_EQ_KEYSIZE &&
4963
0
        !strcmp(card->ctx->app_name, "cardmod") &&
4964
0
        (datalen < nLen)) {
4965
0
      ecpadlen = nLen - datalen;
4966
0
    } else {
4967
0
      ecpadlen = 0;
4968
0
    }
4969
4970
0
    ecdatalen = datalen + ecpadlen;
4971
0
    ecdata = calloc(ecdatalen, sizeof(u8));
4972
0
    if (ecdata == NULL) {
4973
0
      r = SC_ERROR_OUT_OF_MEMORY;
4974
0
      goto err;
4975
0
    }
4976
0
    memcpy(ecdata + ecpadlen, data, datalen);
4977
4978
0
    if (outlen < 2 * nLen) {
4979
0
      sc_log(card->ctx, " output too small for EC signature %zu < %zu",
4980
0
          outlen, 2 * nLen);
4981
0
      r = SC_ERROR_INVALID_DATA;
4982
0
      goto err;
4983
0
    }
4984
4985
0
    r = piv_validate_general_authentication(card, ecdata, ecdatalen, rbuf, sizeof rbuf);
4986
0
    if (r < 0)
4987
0
      goto err;
4988
4989
0
    r = sc_asn1_decode_ecdsa_signature(card->ctx, rbuf, r, nLen, &out, outlen);
4990
    /* Yubikey 5.7.x supports ED25519 */
4991
0
  } else if (priv->alg_id == 0xE0) {
4992
0
    nLen = BYTES4BITS(priv->key_size);
4993
0
    if (outlen < nLen) {
4994
0
      sc_log(card->ctx, " output too small for ED signature %zu < %zu",
4995
0
          outlen, nLen);
4996
0
      r = SC_ERROR_INVALID_DATA;
4997
0
      goto err;
4998
0
    }
4999
0
    r = piv_validate_general_authentication(card, data, datalen, out, outlen);
5000
5001
0
  } else { /* RSA is all set */
5002
0
    r = piv_validate_general_authentication(card, data, datalen, out, outlen);
5003
0
  }
5004
5005
0
err:
5006
0
  free(ecdata);
5007
0
  SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
5008
0
}
5009
5010
static int
5011
piv_decipher(sc_card_t *card, const u8 *data, size_t datalen, u8 *out, size_t outlen)
5012
0
{
5013
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
5014
5015
0
  SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, piv_validate_general_authentication(card, data, datalen, out, outlen));
5016
0
}
5017
5018
/*
5019
 * the PIV-II does not always support files, but we will simulate
5020
 * files and reading/writing using get/put_data
5021
 * The path is the containerID number
5022
 * We can use this to determine the type of data requested, like a cert
5023
 * or pub key.
5024
 * We only support write from the piv_tool with file_out==NULL
5025
 * All other requests should be to read.
5026
 * Only if file_out != null, will we read to get length.
5027
 */
5028
static int
5029
piv_select_file(sc_card_t *card, const sc_path_t *in_path,
5030
    sc_file_t **file_out)
5031
90
{
5032
90
  piv_private_data_t *priv = PIV_DATA(card);
5033
90
  int r;
5034
90
  int i;
5035
90
  const u8 *path;
5036
90
  size_t pathlen;
5037
90
  sc_file_t *file = NULL;
5038
90
  u8 *rbuf = NULL;
5039
90
  size_t rbuflen = 0;
5040
5041
90
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
5042
5043
90
  path = in_path->value;
5044
90
  pathlen = in_path->len;
5045
5046
  /* only support single EF in current application */
5047
  /*
5048
   * PIV emulates files, and only does so because sc_pkcs15_* uses
5049
   * select_file and read_binary. The emulation adds path emulated structures
5050
   * so piv_select_file will find it.
5051
   * there is no dir. Only direct access to emulated files
5052
   * thus opensc-tool and opensc-explorer can not read the emulated files
5053
   */
5054
5055
90
  if (memcmp(path, "\x3F\x00", 2) == 0) {
5056
0
    if (pathlen > 2) {
5057
0
      path += 2;
5058
0
      pathlen -= 2;
5059
0
    }
5060
0
  }
5061
5062
90
  i = piv_find_obj_by_containerid(card, path);
5063
5064
90
  if (i < 0)
5065
90
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND);
5066
5067
  /*
5068
   * pkcs15 will use a 2 byte path or a 4 byte path
5069
   * with cece added to path to request only the cert from the cert obj
5070
   * PIV "Container ID" is used as the path, and are two bytes long
5071
   */
5072
90
  priv->return_only_cert = (pathlen == 4 && path[2] == 0xce && path[3] == 0xce);
5073
5074
90
  priv->selected_obj = i;
5075
90
  priv->rwb_state = -1;
5076
5077
  /* make it look like the file was found. */
5078
  /* We don't want to read it now  unless we need the length */
5079
5080
90
  if (file_out) {
5081
    /* we need to read it now, to get length into cache */
5082
0
    r = piv_get_cached_data(card, i, &rbuf, &rbuflen);
5083
5084
0
    if (r < 0)
5085
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND);
5086
5087
    /* get the cert or the pub key out and into the cache too */
5088
0
    if (priv->return_only_cert || piv_objects[i].flags & PIV_OBJECT_TYPE_PUBKEY) {
5089
0
      r = piv_cache_internal_data(card, i);
5090
0
      if (r < 0)
5091
0
        LOG_FUNC_RETURN(card->ctx, r);
5092
0
    }
5093
5094
0
    file = sc_file_new();
5095
0
    if (file == NULL)
5096
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
5097
5098
0
    file->path = *in_path;
5099
    /* this could be like the FCI */
5100
0
    file->type = SC_FILE_TYPE_DF;
5101
0
    file->shareable = 0;
5102
0
    file->ef_structure = 0;
5103
0
    if (priv->return_only_cert)
5104
0
      file->size = priv->obj_cache[i].internal_obj_len;
5105
0
    else
5106
0
      file->size = priv->obj_cache[i].obj_len;
5107
5108
0
    file->id = (piv_objects[i].containerid[0] << 8) + piv_objects[i].containerid[1];
5109
5110
0
    *file_out = file;
5111
0
  }
5112
5113
90
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
5114
90
}
5115
5116
static int
5117
piv_parse_discovery(sc_card_t *card, u8 *rbuf, size_t rbuflen, int aid_only)
5118
519
{
5119
519
  piv_private_data_t *priv = PIV_DATA(card);
5120
519
  int r = 0;
5121
519
  const u8 *body;
5122
519
  size_t bodylen;
5123
519
  const u8 *aid;
5124
519
  size_t aidlen;
5125
519
  const u8 *pinp;
5126
519
  size_t pinplen;
5127
519
  unsigned int cla_out, tag_out;
5128
5129
519
  if (rbuflen != 0) {
5130
519
    body = rbuf;
5131
519
    if ((r = sc_asn1_read_tag(&body, rbuflen, &cla_out, &tag_out, &bodylen)) != SC_SUCCESS ||
5132
519
        body == NULL ||
5133
519
        bodylen == 0 ||
5134
509
        ((cla_out | tag_out) != 0x7E)) {
5135
10
      sc_log(card->ctx, "DER problem %d", r);
5136
10
      r = SC_ERROR_INVALID_ASN1_OBJECT;
5137
10
      goto err;
5138
10
    }
5139
5140
509
    sc_log(card->ctx, "Discovery 0x%2.2x 0x%2.2x %p:%zu",
5141
509
        cla_out, tag_out, body, bodylen);
5142
509
    aidlen = 0;
5143
509
    aid = sc_asn1_find_tag(card->ctx, body, bodylen, 0x4F, &aidlen);
5144
509
    if (aid == NULL || aidlen < piv_aids[0].len_short ||
5145
475
        memcmp(aid, piv_aids[0].value, piv_aids[0].len_short) != 0) {
5146
72
      sc_log(card->ctx, "Discovery object not PIV");
5147
72
      r = SC_ERROR_INVALID_CARD; /* This is an error */
5148
72
      goto err;
5149
72
    }
5150
437
    if (aid_only == 0) {
5151
437
      pinp = sc_asn1_find_tag(card->ctx, body, bodylen, 0x5F2F, &pinplen);
5152
437
      if (pinp && pinplen == 2) {
5153
108
        priv->init_flags |= PIV_INIT_DISCOVERY_PP;
5154
108
        priv->pin_policy = (*pinp << 8) + *(pinp + 1);
5155
108
        sc_log(card->ctx, "Discovery pinp flags=0x%2.2x 0x%2.2x", *pinp, *(pinp + 1));
5156
108
        if ((priv->pin_policy & (PIV_PP_PIN | PIV_PP_GLOBAL)) == (PIV_PP_PIN | PIV_PP_GLOBAL) &&
5157
3
            priv->pin_policy & PIV_PP_GLOBAL_PRIMARY) {
5158
1
          sc_log(card->ctx, "Pin Preference - Global");
5159
1
          priv->pin_preference = 0x00;
5160
1
        }
5161
108
      }
5162
437
    }
5163
437
    r = SC_SUCCESS;
5164
437
    priv->init_flags |= PIV_INIT_DISCOVERY_PARSED;
5165
437
  }
5166
5167
519
err:
5168
519
  LOG_FUNC_RETURN(card->ctx, r);
5169
519
}
5170
5171
/* normal way to get the discovery object via cache */
5172
static int
5173
piv_process_discovery(sc_card_t *card)
5174
2.61k
{
5175
2.61k
  int r;
5176
2.61k
  u8 *rbuf = NULL;
5177
2.61k
  size_t rbuflen = 0;
5178
5179
2.61k
  r = piv_get_cached_data(card, PIV_OBJ_DISCOVERY, &rbuf, &rbuflen);
5180
  /* Note rbuf and rbuflen are now pointers into cache */
5181
2.61k
  if (r < 0)
5182
2.09k
    goto err;
5183
5184
  /* the object is now cached, see what we have */
5185
519
  r = piv_parse_discovery(card, rbuf, rbuflen, 0);
5186
5187
2.61k
err:
5188
2.61k
  LOG_FUNC_RETURN(card->ctx, r);
5189
2.61k
}
5190
5191
/*
5192
 * parse a CCC to test  if this is a Dual CAC/PIV
5193
 * We read the CCC using the PIV API.
5194
 * Look for CAC RID=A0 00 00 00 79
5195
 */
5196
static int
5197
piv_parse_ccc(sc_card_t *card, u8 *rbuf, size_t rbuflen)
5198
159
{
5199
159
  int r = 0;
5200
159
  const u8 *body;
5201
159
  size_t bodylen;
5202
159
  unsigned int cla_out, tag_out;
5203
5204
159
  u8 tag;
5205
159
  const u8 *end;
5206
159
  size_t len;
5207
5208
159
  piv_private_data_t *priv = PIV_DATA(card);
5209
5210
159
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
5211
5212
159
  if (rbuf == NULL || rbuflen == 0) {
5213
0
    r = SC_ERROR_WRONG_LENGTH;
5214
0
    goto err;
5215
0
  }
5216
5217
  /* Outer layer is a DER tlv */
5218
159
  body = rbuf;
5219
159
  if ((r = sc_asn1_read_tag(&body, rbuflen, &cla_out, &tag_out, &bodylen)) != SC_SUCCESS ||
5220
159
      body == NULL ||
5221
159
      bodylen == 0 ||
5222
155
      ((cla_out << 24 | tag_out) != piv_objects[PIV_OBJ_CCC].resp_tag)) {
5223
4
    sc_log(card->ctx, "DER problem %d", r);
5224
4
    r = SC_ERROR_INVALID_ASN1_OBJECT;
5225
4
    goto err;
5226
4
  }
5227
5228
155
  priv->ccc_flags |= PIV_CCC_FOUND;
5229
5230
  /* CCC  entries are simple tlv */
5231
155
  end = body + bodylen;
5232
11.8k
  for (; (body < end); body += len) {
5233
11.8k
    r = sc_simpletlv_read_tag(&body, end - body, &tag, &len);
5234
11.8k
    if (r < 0)
5235
128
      goto err;
5236
11.6k
    switch (tag) {
5237
1.62k
    case PIV_CCC_TAG_F0:
5238
1.62k
      if (len == 0x15) {
5239
1.37k
        if (memcmp(body, "\xA0\x00\x00\x03\08", 5) == 0)
5240
439
          priv->ccc_flags |= PIV_CCC_F0_PIV;
5241
939
        else if (memcmp(body, "\xA0\x00\x00\x00\x79", 5) == 0)
5242
466
          priv->ccc_flags |= PIV_CCC_F0_CAC;
5243
1.37k
        if (*(body + 6) == 0x02)
5244
247
          priv->ccc_flags |= PIV_CCC_F0_JAVA;
5245
1.37k
      }
5246
1.62k
      break;
5247
960
    case PIV_CCC_TAG_F3:
5248
960
      if (len == 0x10) {
5249
491
        if (memcmp(body, "\xA0\x00\x00\x00\x79\x04", 6) == 0)
5250
237
          priv->ccc_flags |= PIV_CCC_F3_CAC_PKI;
5251
491
      }
5252
960
      break;
5253
11.6k
    }
5254
11.6k
  }
5255
5256
159
err:
5257
159
  LOG_FUNC_RETURN(card->ctx, r);
5258
159
}
5259
5260
static int
5261
piv_process_ccc(sc_card_t *card)
5262
1.46k
{
5263
1.46k
  int r = 0;
5264
1.46k
  u8 *rbuf = NULL;
5265
1.46k
  size_t rbuflen = 0;
5266
5267
1.46k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
5268
1.46k
  r = piv_get_cached_data(card, PIV_OBJ_CCC, &rbuf, &rbuflen);
5269
5270
1.46k
  if (r < 0)
5271
1.30k
    goto err;
5272
5273
  /* the object is now cached, see what we have */
5274
159
  r = piv_parse_ccc(card, rbuf, rbuflen);
5275
1.46k
err:
5276
1.46k
  LOG_FUNC_RETURN(card->ctx, r);
5277
1.46k
}
5278
5279
static int
5280
piv_find_discovery(sc_card_t *card)
5281
42.1k
{
5282
42.1k
  int r = 0;
5283
42.1k
  size_t rbuflen;
5284
42.1k
  u8 *rbuf = NULL;
5285
42.1k
  piv_private_data_t *priv = PIV_DATA(card);
5286
5287
42.1k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
5288
5289
  /*
5290
   * During piv_card_reader_lock_obtained,
5291
   * we use the discovery object to test if card present, and
5292
   * if PIV AID is active.
5293
   */
5294
42.1k
  if (priv->obj_cache[PIV_OBJ_DISCOVERY].flags & PIV_OBJ_CACHE_NOT_PRESENT) {
5295
0
    r = SC_ERROR_DATA_OBJECT_NOT_FOUND;
5296
0
    goto end;
5297
0
  }
5298
5299
  /* If not valid: read, test,  cache */
5300
42.1k
  if (!(priv->obj_cache[PIV_OBJ_DISCOVERY].flags & PIV_OBJ_CACHE_VALID)) {
5301
2.61k
    r = piv_process_discovery(card);
5302
39.4k
  } else {
5303
    /* if already in cache,force read */
5304
39.4k
    rbuflen = 1;
5305
39.4k
    r = piv_get_data(card, PIV_OBJ_DISCOVERY, &rbuf, &rbuflen);
5306
    /* if same response as last, no need to parse */
5307
39.4k
    if (r == 0 && priv->obj_cache[PIV_OBJ_DISCOVERY].obj_len == 0)
5308
0
      goto end;
5309
5310
39.4k
    if (r >= 0 && priv->obj_cache[PIV_OBJ_DISCOVERY].obj_len == rbuflen &&
5311
2.42k
        priv->obj_cache[PIV_OBJ_DISCOVERY].obj_data &&
5312
2.42k
        !memcmp(rbuf, priv->obj_cache[PIV_OBJ_DISCOVERY].obj_data, rbuflen)) {
5313
213
      goto end;
5314
213
    }
5315
    /* This should not happen  bad card */
5316
39.2k
    sc_log(card->ctx, "Discovery not the same as previously read object");
5317
39.2k
    r = SC_ERROR_CORRUPTED_DATA;
5318
39.2k
    goto end;
5319
39.4k
  }
5320
5321
42.1k
end:
5322
42.1k
  free(rbuf);
5323
42.1k
  LOG_FUNC_RETURN(card->ctx, r);
5324
42.1k
}
5325
5326
/*
5327
 * The history object lists what retired keys and certs are on the card
5328
 * or listed in the offCardCertURL. The user will need to download the
5329
 * the offCardURL file.
5330
 * If the offCardCertURL is not cached by the user it will not be used.
5331
 */
5332
static int
5333
piv_process_history(sc_card_t *card)
5334
2.01k
{
5335
2.01k
  piv_private_data_t *priv = PIV_DATA(card);
5336
2.01k
  int r;
5337
2.01k
  int i, tmplen, tmplen2, tmplen3;
5338
2.01k
  int enumtag;
5339
2.01k
  u8 *rbuf = NULL;
5340
2.01k
  size_t rbuflen = 0;
5341
2.01k
  const u8 *body;
5342
2.01k
  size_t bodylen;
5343
2.01k
  const u8 *num;
5344
2.01k
  size_t numlen;
5345
2.01k
  const u8 *url = NULL;
5346
2.01k
  size_t urllen;
5347
2.01k
  u8 *ocfhfbuf = NULL;
5348
2.01k
  unsigned int cla_out, tag_out;
5349
2.01k
  size_t ocfhflen;
5350
2.01k
  const u8 *seq;
5351
2.01k
  const u8 *seqtag;
5352
2.01k
  size_t seqlen;
5353
2.01k
  const u8 *keyref;
5354
2.01k
  size_t keyreflen;
5355
2.01k
  const u8 *cert;
5356
2.01k
  size_t certlen;
5357
2.01k
  size_t certobjlen, i2;
5358
2.01k
  u8 *certobj;
5359
2.01k
  u8 *cp;
5360
5361
2.01k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
5362
5363
2.01k
  r = piv_get_cached_data(card, PIV_OBJ_HISTORY, &rbuf, &rbuflen);
5364
2.01k
  if (r == SC_ERROR_FILE_NOT_FOUND)
5365
94
    r = 0; /* OK if not found */
5366
2.01k
  if (r <= 0) {
5367
1.83k
    priv->obj_cache[PIV_OBJ_HISTORY].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
5368
1.83k
    goto err; /* no file, must be pre 800-73-3 card and not on card */
5369
1.83k
  }
5370
5371
  /* the object is now cached, see what we have */
5372
189
  if (rbuflen != 0) {
5373
189
    body = rbuf;
5374
189
    if ((r = sc_asn1_read_tag(&body, rbuflen, &cla_out, &tag_out, &bodylen)) != SC_SUCCESS ||
5375
189
        ((cla_out << 24 | tag_out) != piv_objects[PIV_OBJ_HISTORY].resp_tag)) {
5376
0
      sc_log(card->ctx, "DER problem %d", r);
5377
0
      r = SC_ERROR_INVALID_ASN1_OBJECT;
5378
0
      goto err;
5379
0
    }
5380
5381
189
    if (body != NULL && bodylen != 0) {
5382
184
      numlen = 0;
5383
184
      num = sc_asn1_find_tag(card->ctx, body, bodylen, 0xC1, &numlen);
5384
184
      if (num) {
5385
21
        if (numlen != 1 || *num > PIV_OBJ_RETIRED_X509_20 - PIV_OBJ_RETIRED_X509_1 + 1) {
5386
9
          r = SC_ERROR_INVALID_ASN1_OBJECT;
5387
9
          goto err;
5388
9
        }
5389
5390
12
        priv->keysWithOnCardCerts = *num;
5391
12
      }
5392
5393
175
      numlen = 0;
5394
175
      num = sc_asn1_find_tag(card->ctx, body, bodylen, 0xC2, &numlen);
5395
175
      if (num) {
5396
21
        if (numlen != 1 || *num > PIV_OBJ_RETIRED_X509_20 - PIV_OBJ_RETIRED_X509_1 + 1) {
5397
13
          r = SC_ERROR_INVALID_ASN1_OBJECT;
5398
13
          goto err;
5399
13
        }
5400
5401
8
        priv->keysWithOffCardCerts = *num;
5402
8
      }
5403
5404
162
      url = sc_asn1_find_tag(card->ctx, body, bodylen, 0xF3, &urllen);
5405
162
      if (url) {
5406
125
        if (urllen > 118) {
5407
2
          r = SC_ERROR_INVALID_ASN1_OBJECT;
5408
2
          goto err;
5409
2
        }
5410
123
        priv->offCardCertURL = calloc(1, urllen + 1);
5411
123
        if (priv->offCardCertURL == NULL)
5412
123
          LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
5413
123
        memcpy(priv->offCardCertURL, url, urllen);
5414
123
      }
5415
162
    } else {
5416
5
      sc_log(card->ctx, "Problem with History object\n");
5417
5
      r = SC_SUCCESS; /* OK if not found */
5418
5
      goto err;
5419
5
    }
5420
189
  }
5421
160
  sc_log(card->ctx, "History on=%d off=%d URL=%s",
5422
160
      priv->keysWithOnCardCerts, priv->keysWithOffCardCerts,
5423
160
      priv->offCardCertURL ? priv->offCardCertURL : "NONE");
5424
5425
  /* now mark what objects are on the card */
5426
247
  for (i = 0; i < priv->keysWithOnCardCerts; i++)
5427
87
    priv->obj_cache[PIV_OBJ_RETIRED_X509_1 + i].flags &= ~PIV_OBJ_CACHE_NOT_PRESENT;
5428
5429
  /*
5430
   * If user has gotten copy of the file from the offCardCertsURL,
5431
   * we will read in and add the certs to the cache as listed on
5432
   * the card. some of the certs may be on the card as well.
5433
   *
5434
   * Get file name from url. verify that the filename is valid
5435
   * The URL ends in a SHA-256 string. We will use this as the filename
5436
   * in the directory used for the  PKCS15 cache
5437
   * "http://" <DNS name> "/" <ASCII-HEX encoded SHA-256 hash of OffCardKeyHistoryFile>
5438
   */
5439
5440
160
  r = 0;
5441
160
  if (priv->offCardCertURL) {
5442
123
    char *fp;
5443
123
    char filename[PATH_MAX];
5444
5445
123
    if (strncmp("http://", priv->offCardCertURL, 7)) {
5446
96
      r = SC_ERROR_INVALID_DATA;
5447
96
      goto err;
5448
96
    }
5449
    /* find the last /  so we have the filename part */
5450
27
    fp = strrchr(priv->offCardCertURL + 7, '/');
5451
27
    if (fp == NULL) {
5452
8
      r = SC_ERROR_INVALID_DATA;
5453
8
      goto err;
5454
8
    }
5455
19
    fp++;
5456
19
    if (strlen(fp) != 64) { /* ASCII-HEX encoded SHA-256 */
5457
10
      r = SC_ERROR_INVALID_DATA;
5458
10
      goto err;
5459
10
    }
5460
181
    for (i = 0; i < 64; i++) {
5461
179
      if (isxdigit((unsigned char)fp[i]) == 0) {
5462
7
        r = SC_ERROR_INVALID_DATA;
5463
7
        goto err;
5464
7
      }
5465
179
    }
5466
5467
    /* Use the same directory as used for other OpenSC cached items */
5468
2
    r = sc_get_cache_dir(card->ctx, filename, sizeof(filename) - strlen(fp) - 2);
5469
2
    if (r != SC_SUCCESS)
5470
0
      goto err;
5471
#ifdef _WIN32
5472
    strlcat(filename, "\\", PATH_MAX);
5473
#else
5474
2
    strlcat(filename, "/", PATH_MAX);
5475
2
#endif
5476
2
    strlcat(filename, fp, PATH_MAX);
5477
5478
2
    r = piv_read_obj_from_file(card, filename,
5479
2
        &ocfhfbuf, &ocfhflen);
5480
2
    if (r == SC_ERROR_FILE_NOT_FOUND) {
5481
2
      r = 0;
5482
2
      goto err;
5483
2
    }
5484
5485
    /*
5486
     * Its a seq of seq of a key ref and cert
5487
     */
5488
5489
0
    body = ocfhfbuf;
5490
0
    if (sc_asn1_read_tag(&body, ocfhflen, &cla_out, &tag_out, &bodylen) != SC_SUCCESS ||
5491
0
        body == NULL ||
5492
0
        bodylen == 0 ||
5493
0
        (cla_out | tag_out) != 0x30) {
5494
0
      sc_log(card->ctx, "DER problem");
5495
0
      r = SC_ERROR_INVALID_ASN1_OBJECT;
5496
0
      goto err;
5497
0
    }
5498
0
    seq = body;
5499
0
    while (bodylen > 0) {
5500
0
      seqtag = seq;
5501
0
      if (sc_asn1_read_tag(&seq, bodylen, &cla_out, &tag_out, &seqlen) != SC_SUCCESS ||
5502
0
          seq == 0 ||
5503
0
          seqlen == 0 ||
5504
0
          (cla_out | tag_out) != 0x30) {
5505
0
        sc_log(card->ctx, "DER problem");
5506
0
        r = SC_ERROR_INVALID_ASN1_OBJECT;
5507
0
        goto err;
5508
0
      }
5509
0
      keyref = sc_asn1_find_tag(card->ctx, seq, seqlen, 0x04, &keyreflen);
5510
0
      if (!keyref || keyreflen != 1 ||
5511
0
          (*keyref < 0x82 || *keyref > 0x95)) {
5512
0
        sc_log(card->ctx, "DER problem");
5513
0
        r = SC_ERROR_INVALID_ASN1_OBJECT;
5514
0
        goto err;
5515
0
      }
5516
0
      cert = keyref + keyreflen;
5517
0
      certlen = seqlen - (cert - seq);
5518
5519
0
      enumtag = PIV_OBJ_RETIRED_X509_1 + *keyref - 0x82;
5520
      /* now add the cert like another object */
5521
5522
0
      if ((tmplen = sc_asn1_put_tag(0x70, NULL, certlen, NULL, 0, NULL)) <= 0 ||
5523
0
          (tmplen2 = sc_asn1_put_tag(0x71, NULL, 1, NULL, 0, NULL)) <= 0 ||
5524
0
          (tmplen3 = sc_asn1_put_tag(0xFE, NULL, 0, NULL, 0, NULL)) <= 0) {
5525
0
        r = SC_ERROR_INVALID_ASN1_OBJECT;
5526
0
        goto err;
5527
0
      }
5528
0
      i2 = tmplen + tmplen2 + tmplen3;
5529
0
      tmplen = sc_asn1_put_tag(0x53, NULL, i2, NULL, 0, NULL);
5530
0
      if (tmplen <= 0) {
5531
0
        r = SC_ERROR_INVALID_ASN1_OBJECT;
5532
0
        goto err;
5533
0
      }
5534
5535
0
      certobjlen = tmplen;
5536
0
      certobj = malloc(certobjlen);
5537
0
      if (certobj == NULL) {
5538
0
        r = SC_ERROR_OUT_OF_MEMORY;
5539
0
        goto err;
5540
0
      }
5541
0
      cp = certobj;
5542
0
      if ((r = sc_asn1_put_tag(0x53, NULL, i2, cp, certobjlen, &cp)) != SC_SUCCESS ||
5543
0
          (r = sc_asn1_put_tag(0x70, cert, certlen, cp, certobjlen - (cp - certobj), &cp)) != SC_SUCCESS ||
5544
0
          (r = sc_asn1_put_tag(0x71, NULL, 1, cp, certobjlen - (cp - certobj), &cp)) != SC_SUCCESS) {
5545
0
        goto err;
5546
0
      }
5547
0
      *cp++ = 0x00;
5548
0
      r = sc_asn1_put_tag(0xFE, NULL, 0, cp, certobjlen - (cp - certobj), &cp);
5549
0
      if (r != SC_SUCCESS) {
5550
0
        goto err;
5551
0
      }
5552
5553
0
      priv->obj_cache[enumtag].obj_data = certobj;
5554
0
      priv->obj_cache[enumtag].obj_len = certobjlen;
5555
0
      priv->obj_cache[enumtag].flags |= PIV_OBJ_CACHE_VALID;
5556
0
      priv->obj_cache[enumtag].flags &= ~PIV_OBJ_CACHE_NOT_PRESENT;
5557
5558
0
      r = piv_cache_internal_data(card, enumtag);
5559
0
      sc_log(card->ctx, "got internal r=%d", r);
5560
5561
0
      sc_log(card->ctx, "Added from off card file #%d %p:%zu 0x%02X",
5562
0
          enumtag,
5563
0
          priv->obj_cache[enumtag].obj_data,
5564
0
          priv->obj_cache[enumtag].obj_len, *keyref);
5565
5566
0
      bodylen -= (seqlen + seq - seqtag);
5567
0
      seq += seqlen;
5568
0
    }
5569
0
  }
5570
2.01k
err:
5571
2.01k
  if (ocfhfbuf)
5572
0
    free(ocfhfbuf);
5573
2.01k
  LOG_FUNC_RETURN(card->ctx, r);
5574
2.01k
}
5575
5576
static int
5577
piv_obj_cache_free_entry(sc_card_t *card, int enumtag, int flags)
5578
294k
{
5579
294k
  piv_private_data_t *priv = PIV_DATA(card);
5580
5581
294k
  if (priv->obj_cache[enumtag].obj_data)
5582
978
    free(priv->obj_cache[enumtag].obj_data);
5583
294k
  priv->obj_cache[enumtag].obj_data = NULL;
5584
294k
  priv->obj_cache[enumtag].obj_len = 0;
5585
5586
294k
  if (priv->obj_cache[enumtag].internal_obj_data)
5587
0
    free(priv->obj_cache[enumtag].internal_obj_data);
5588
294k
  priv->obj_cache[enumtag].internal_obj_data = NULL;
5589
294k
  priv->obj_cache[enumtag].internal_obj_len = 0;
5590
294k
  priv->obj_cache[enumtag].flags = flags;
5591
5592
294k
  return SC_SUCCESS;
5593
294k
}
5594
5595
static int
5596
piv_finish(sc_card_t *card)
5597
7.73k
{
5598
7.73k
  piv_private_data_t *priv = PIV_DATA(card);
5599
7.73k
  int i;
5600
5601
7.73k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
5602
7.73k
  if (priv) {
5603
4.87k
    if (priv->context_specific) {
5604
0
      sc_log(card->ctx, "Clearing CONTEXT_SPECIFIC lock");
5605
0
      priv->context_specific = 0;
5606
0
      sc_unlock(card);
5607
0
    }
5608
4.87k
    free(priv->aid_der.value);
5609
4.87k
    free(priv->al_label);
5610
4.87k
    if (priv->w_buf)
5611
0
      free(priv->w_buf);
5612
4.87k
    if (priv->offCardCertURL)
5613
123
      free(priv->offCardCertURL);
5614
297k
    for (i = 0; i < PIV_OBJ_LAST_ENUM - 1; i++) {
5615
292k
      piv_obj_cache_free_entry(card, i, 0);
5616
292k
    }
5617
131k
    for (i = 0; i < PIV_NUM_YK_SLOT_INFO; i++) {
5618
126k
      free(priv->yk_slot_info[i].pubkey.value);
5619
126k
    }
5620
#ifdef ENABLE_PIV_SM
5621
    piv_clear_cvc_content(&priv->sm_cvc);
5622
    piv_clear_cvc_content(&priv->sm_in_cvc);
5623
    piv_clear_sm_session(&priv->sm_session);
5624
#endif /* ENABLE_PIV_SM */
5625
5626
4.87k
    free(priv);
5627
4.87k
    card->drv_data = NULL; /* priv */
5628
4.87k
  }
5629
7.73k
  return 0;
5630
7.73k
}
5631
5632
static int
5633
piv_match_card(sc_card_t *card)
5634
3.39k
{
5635
3.39k
  int r = 0;
5636
5637
3.39k
  sc_debug(card->ctx, SC_LOG_DEBUG_MATCH, "PIV_MATCH card->type:%d\n", card->type);
5638
  /* piv_match_card may be called with card->type, set by opensc.conf */
5639
  /* user provided card type must be one we know */
5640
3.39k
  switch (card->type) {
5641
3.39k
  case -1:
5642
3.39k
  case SC_CARD_TYPE_PIV_II_BASE:
5643
3.39k
  case SC_CARD_TYPE_PIV_II_GENERIC:
5644
3.39k
  case SC_CARD_TYPE_PIV_II_HIST:
5645
3.39k
  case SC_CARD_TYPE_PIV_II_NEO:
5646
3.39k
  case SC_CARD_TYPE_PIV_II_YUBIKEY4:
5647
3.39k
  case SC_CARD_TYPE_PIV_II_GI_DE_DUAL_CAC:
5648
3.39k
  case SC_CARD_TYPE_PIV_II_GI_DE:
5649
3.39k
  case SC_CARD_TYPE_PIV_II_GEMALTO_DUAL_CAC:
5650
3.39k
  case SC_CARD_TYPE_PIV_II_GEMALTO:
5651
3.39k
  case SC_CARD_TYPE_PIV_II_OBERTHUR_DUAL_CAC:
5652
3.39k
  case SC_CARD_TYPE_PIV_II_OBERTHUR:
5653
3.39k
  case SC_CARD_TYPE_PIV_II_PIVKEY:
5654
3.39k
  case SC_CARD_TYPE_PIV_II_SWISSBIT:
5655
3.39k
  case SC_CARD_TYPE_PIV_II_800_73_4:
5656
3.39k
  case SC_CARD_TYPE_PIV_II_NITROKEY:
5657
3.39k
  case SC_CARD_TYPE_PIV_II_TOKEN2:
5658
3.39k
  case SC_CARD_TYPE_PIV_II_PIVAPPLET:
5659
3.39k
  case SC_CARD_TYPE_PIV_II_OPENFIPS201:
5660
3.39k
    break;
5661
0
  default:
5662
0
    return 0; /* can not handle the card */
5663
3.39k
  }
5664
5665
3.39k
  r = sc_lock(card);
5666
3.39k
  if (r < 0)
5667
0
    return 0;
5668
  /* its one we know, or we can test for it in piv_init */
5669
3.39k
  r = piv_match_card_continued(card);
5670
3.39k
  sc_unlock(card);
5671
5672
3.39k
  if (r < 0 || !card->drv_data) {
5673
    /* clean up what we left in card */
5674
1.47k
    piv_finish(card);
5675
1.47k
    return 0; /* match failed */
5676
1.47k
  }
5677
5678
1.91k
  sc_debug(card->ctx, SC_LOG_DEBUG_MATCH, "PIV_MATCH card->type:%d r:%d\n", card->type, r);
5679
1.91k
  return 1; /* matched */
5680
3.39k
}
5681
5682
static int
5683
piv_match_card_continued(sc_card_t *card)
5684
4.87k
{
5685
4.87k
  int i, r = 0, r2 = 0;
5686
4.87k
  int type = -1;
5687
4.87k
  piv_private_data_t *priv = NULL;
5688
4.87k
  int saved_type = card->type;
5689
4.87k
  sc_apdu_t apdu;
5690
4.87k
  u8 yubico_version_buf[3] = {0};
5691
5692
  /* piv_match_card may be called with card->type, set by opensc.conf */
5693
  /* User provided card type must be one we know */
5694
5695
4.87k
  switch (card->type) {
5696
4.87k
  case -1:
5697
4.87k
  case SC_CARD_TYPE_PIV_II_BASE:
5698
4.87k
  case SC_CARD_TYPE_PIV_II_GENERIC:
5699
4.87k
  case SC_CARD_TYPE_PIV_II_HIST:
5700
4.87k
  case SC_CARD_TYPE_PIV_II_NEO:
5701
4.87k
  case SC_CARD_TYPE_PIV_II_YUBIKEY4:
5702
4.87k
  case SC_CARD_TYPE_PIV_II_GI_DE_DUAL_CAC:
5703
4.87k
  case SC_CARD_TYPE_PIV_II_GI_DE:
5704
4.87k
  case SC_CARD_TYPE_PIV_II_GEMALTO_DUAL_CAC:
5705
4.87k
  case SC_CARD_TYPE_PIV_II_GEMALTO:
5706
4.87k
  case SC_CARD_TYPE_PIV_II_OBERTHUR_DUAL_CAC:
5707
4.87k
  case SC_CARD_TYPE_PIV_II_OBERTHUR:
5708
4.87k
  case SC_CARD_TYPE_PIV_II_PIVKEY:
5709
4.87k
  case SC_CARD_TYPE_PIV_II_SWISSBIT:
5710
4.87k
  case SC_CARD_TYPE_PIV_II_800_73_4:
5711
4.87k
  case SC_CARD_TYPE_PIV_II_NITROKEY:
5712
4.87k
  case SC_CARD_TYPE_PIV_II_TOKEN2:
5713
4.87k
  case SC_CARD_TYPE_PIV_II_PIVAPPLET:
5714
4.87k
  case SC_CARD_TYPE_PIV_II_OPENFIPS201:
5715
5716
4.87k
    type = card->type;
5717
4.87k
    break;
5718
0
  default:
5719
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_WRONG_CARD);
5720
4.87k
  }
5721
4.87k
  sc_debug(card->ctx, SC_LOG_DEBUG_MATCH, "PIV_MATCH card->type:%d type:%d r:%d\n", card->type, type, r);
5722
4.87k
  if (type == -1) {
5723
    /*
5724
     * Try to identify card by ATR or historical data in ATR
5725
     * currently all PIV card will respond to piv_find_aid
5726
     * the same. But in future may need to know card type first,
5727
     * so do it here.
5728
     */
5729
5730
4.87k
    if (card->reader->atr_info.hist_bytes != NULL) {
5731
1.54k
      if (card->reader->atr_info.hist_bytes_len == 8 &&
5732
240
          !(memcmp(card->reader->atr_info.hist_bytes, "Yubikey4", 8))) {
5733
15
        type = SC_CARD_TYPE_PIV_II_YUBIKEY4;
5734
1.52k
      } else if (card->reader->atr_info.hist_bytes_len >= 7 &&
5735
1.11k
          !(memcmp(card->reader->atr_info.hist_bytes, "Yubikey", 7))) {
5736
541
        type = SC_CARD_TYPE_PIV_II_NEO;
5737
984
      } else if (card->reader->atr_info.hist_bytes_len >= 6 &&
5738
881
          !(memcmp(card->reader->atr_info.hist_bytes, "PIVKEY", 6))) {
5739
201
        type = SC_CARD_TYPE_PIV_II_PIVKEY;
5740
783
      } else if (card->reader->atr_info.hist_bytes_len >= 6 &&
5741
680
          !(memcmp(card->reader->atr_info.hist_bytes, (u8 *)"TK\x00PIV", 6))) {
5742
146
        type = SC_CARD_TYPE_PIV_II_TOKEN2;
5743
146
      }
5744
      /* look for TLV historic data */
5745
637
      else if (card->reader->atr_info.hist_bytes_len > 0 &&
5746
626
          card->reader->atr_info.hist_bytes[0] == 0x80u) { /* compact TLV */
5747
344
        size_t datalen;
5748
344
        const u8 *data;
5749
5750
        /* look for card issuer's data:  tag 5X where X is datalen */
5751
344
        if ((data = sc_compacttlv_find_tag(card->reader->atr_info.hist_bytes + 1,
5752
344
                 card->reader->atr_info.hist_bytes_len - 1, 0x50, &datalen))) {
5753
152
          if (datalen >= 8 && !(memcmp(data, "Nitrokey", 8))) { /* first 8 are Nitrokey */
5754
37
            type = SC_CARD_TYPE_PIV_II_NITROKEY;
5755
115
          } else if (datalen == 7 && !(memcmp(data, "YubiKey", 7))) {
5756
4
            type = SC_CARD_TYPE_PIV_II_YUBIKEY4; /* reader says 4  really 5 */
5757
4
          }
5758
          /* Yubikey 5 NFC ATR using ACR122 contactless reader does not match
5759
           * https://developers.yubico.com/PIV/Introduction/Yubico_extensions.html
5760
           * On Windows 10, using Omnikey 5021, the ATR is correct
5761
           * will look at only 6 bytes that do match
5762
           */
5763
111
          else if (datalen == 7 && !(memcmp(data, "YubiKe", 6))) {
5764
4
            type = SC_CARD_TYPE_PIV_II_YUBIKEY4; /* reader says 4 really 5 */
5765
4
          }
5766
192
        } else if ((data = sc_compacttlv_find_tag(card->reader->atr_info.hist_bytes + 1,
5767
192
                  card->reader->atr_info.hist_bytes_len - 1, 0xF0, &datalen))) {
5768
73
          int k;
5769
5770
194
          for (k = 0; piv_aids[k].len_long != 0; k++) {
5771
136
            if (datalen == piv_aids[k].len_long &&
5772
96
                !memcmp(data, piv_aids[k].value, datalen)) {
5773
15
              type = SC_CARD_TYPE_PIV_II_HIST;
5774
15
              break;
5775
15
            }
5776
136
          }
5777
73
        }
5778
344
      }
5779
1.54k
    }
5780
5781
4.87k
    sc_debug(card->ctx, SC_LOG_DEBUG_MATCH, "PIV_MATCH card->type:%d type:%d r:%d\n", card->type, type, r);
5782
5783
4.87k
    if (type == -1) {
5784
      /* use known ATRs  which changes the type */
5785
3.91k
      i = _sc_match_atr(card, piv_atrs, &type);
5786
3.91k
      if (i < 0)
5787
3.81k
        type = SC_CARD_TYPE_PIV_II_BASE; /* May be some newer unknown card including CAC or PIV-like card */
5788
3.91k
    }
5789
4.87k
  }
5790
5791
4.87k
  card->type = type;
5792
5793
  /* we either found via ATR historic bytes or ATR directly */
5794
4.87k
  sc_debug(card->ctx, SC_LOG_DEBUG_MATCH, "PIV_MATCH card->type:%d type:%d r:%d\n", card->type, type, r);
5795
5796
  /* allocate and init basic fields */
5797
4.87k
  priv = calloc(1, sizeof(piv_private_data_t));
5798
5799
4.87k
  if (!priv)
5800
4.87k
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
5801
5802
4.87k
  card->drv_data = priv; /* will free if no match, or pass on to piv_init */
5803
  /*
5804
   * Largest object defined in NIST sp800-73-3 and sp800-73-4 is 12710 bytes
5805
   * If for some reason future cards have larger objects, this value needs to
5806
   * be increased here.
5807
   */
5808
4.87k
  priv->max_object_size = MAX_FILE_SIZE - 256; /* fix SM apdu resplen issue */
5809
4.87k
  priv->selected_obj = -1;
5810
4.87k
  priv->pin_preference = 0x80; /* 800-73-3 part 1, table 3 */
5811
4.87k
  priv->logged_in = SC_PIN_STATE_UNKNOWN;
5812
4.87k
  priv->pstate = PIV_STATE_MATCH;
5813
5814
#ifdef ENABLE_PIV_SM
5815
  memset(&card->sm_ctx, 0, sizeof card->sm_ctx);
5816
  card->sm_ctx.ops.open = piv_sm_open;
5817
  card->sm_ctx.ops.get_sm_apdu = piv_get_sm_apdu;
5818
  card->sm_ctx.ops.free_sm_apdu = piv_free_sm_apdu;
5819
  card->sm_ctx.ops.close = piv_sm_close;
5820
#endif /* ENABLE_PIV_SM */
5821
5822
  /* See if contactless  or run as virtual card */
5823
  /* PivApplet in .github/test_piv.sh for example */
5824
4.87k
  if (card->reader->atr.len >= 4 &&
5825
1.67k
      card->reader->atr.value[0] == 0x3b &&
5826
1.58k
      (card->reader->atr.value[1] & 0xF0) == 0x80 &&
5827
205
      card->reader->atr.value[2] == 0x80 &&
5828
140
      card->reader->atr.value[3] == 0x01) {
5829
101
    priv->init_flags |= PIV_INIT_CONTACTLESS;
5830
101
  }
5831
5832
297k
  for (i = 0; i < PIV_OBJ_LAST_ENUM - 1; i++)
5833
292k
    if (piv_objects[i].flags & PIV_OBJECT_NOT_PRESENT)
5834
97.5k
      priv->obj_cache[i].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
5835
  /*
5836
   * Detect if active AID is PIV. NIST 800-73 says only one PIV application per card
5837
   * and PIV must be the default application.
5838
   * Try to avoid doing a select_aid and losing the login state on some cards.
5839
   * We may get interference on some cards by other drivers trying SELECT_AID before
5840
   * we get to see if PIV application is still active. Putting PIV driver first might help.
5841
   *
5842
   * Discovery Object introduced in 800-73-3 so will return OK if found and PIV applet active.
5843
   * Will fail with SC_ERROR_FILE_NOT_FOUND if 800-73-3 and no Discovery object.
5844
   * But some other card could also return SC_ERROR_FILE_NOT_FOUND.
5845
   * Will fail for other reasons if wrong applet is selected or bad PIV implementation.
5846
   */
5847
5848
  /*
5849
   * if ATR matched or user forced card type
5850
   * test if PIV is active applet without using AID If fails try AID
5851
   */
5852
5853
4.87k
  if (card->type > SC_CARD_TYPE_PIV_II_BASE &&
5854
1.05k
      !(priv->init_flags & PIV_INIT_CONTACTLESS)) {
5855
1.04k
    r = piv_find_discovery(card);
5856
1.04k
    if (r < 0) {
5857
611
      piv_obj_cache_free_entry(card, PIV_OBJ_DISCOVERY, 0); /* don't cache  on failure */
5858
611
      r = piv_find_aid(card);
5859
611
      LOG_TEST_GOTO_ERR(card->ctx, r, "Not a PIV card");
5860
611
    }
5861
3.82k
  } else {
5862
    /* piv_find_aid saves al_label from response */
5863
3.82k
    r = piv_find_aid(card);
5864
3.82k
    LOG_TEST_GOTO_ERR(card->ctx, r, "Not a PIV card");
5865
3.82k
  }
5866
5867
  /* Know to be PIV card but not the type */
5868
5869
  /* If card type still unknown, see if Application Label is known and set card->type */
5870
2.01k
  if (priv->al_label && priv->al_labellen) {
5871
35
    switch (card->type) {
5872
28
    case SC_CARD_TYPE_PIV_II_BASE:
5873
28
    case SC_CARD_TYPE_PIV_II_GENERIC:
5874
79
      for (i = 0; al_map[i].al_label; i++) {
5875
54
        if ((priv->al_labellen >= al_map[i].al_labellen) &&
5876
38
            (!memcmp(priv->al_label, al_map[i].al_label, al_map[i].al_labellen))) {
5877
3
          sc_debug(card->ctx, SC_LOG_DEBUG_MATCH, "AL match i:%d type:%d", i, al_map[i].al_type);
5878
3
          card->type = al_map[i].al_type;
5879
3
          break;
5880
3
        }
5881
54
      }
5882
28
      break;
5883
35
    }
5884
35
  }
5885
5886
2.01k
  sc_debug(card->ctx, SC_LOG_DEBUG_MATCH, "PIV_MATCH card->type:%d  CI:%08x r:%d AI:%08x\n",
5887
2.01k
      card->type, priv->card_issues, r, priv->alg_ids);
5888
5889
  /*
5890
   * Assumes all Yubikey/Nitrokey/Token2/PivApplet cards are all "Yubico like"
5891
   * via ATR, ATR Historic bytes or Application Label
5892
   * Will also check if BASE cards are Yubikey like card and return a version number
5893
   * SC_CARD_TYPE_PIV_II_GENERIC can be set by user to not test for Yubico version
5894
   */
5895
2.01k
  switch (card->type) {
5896
301
  case SC_CARD_TYPE_PIV_II_NEO:
5897
308
  case SC_CARD_TYPE_PIV_II_YUBIKEY4:
5898
339
  case SC_CARD_TYPE_PIV_II_NITROKEY:
5899
396
  case SC_CARD_TYPE_PIV_II_TOKEN2:
5900
398
  case SC_CARD_TYPE_PIV_II_PIVAPPLET:
5901
399
  case SC_CARD_TYPE_PIV_II_OPENFIPS201:
5902
399
  case SC_CARD_TYPE_PIV_II_GENERIC:
5903
1.83k
  case SC_CARD_TYPE_PIV_II_BASE: /* unknown PIV card */
5904
1.83k
    sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xFD, 0x00, 0x00);
5905
1.83k
    apdu.lc = 0;
5906
1.83k
    apdu.data = NULL;
5907
1.83k
    apdu.datalen = 0;
5908
1.83k
    apdu.resp = yubico_version_buf;
5909
1.83k
    apdu.resplen = sizeof(yubico_version_buf);
5910
1.83k
    apdu.le = apdu.resplen;
5911
1.83k
    r2 = sc_transmit_apdu(card, &apdu); /* if not supported yubico_version == 0 */
5912
1.83k
    if (r2 == SC_SUCCESS && apdu.resplen == 3) {
5913
255
      priv->yubico_version = (yubico_version_buf[0] << 16) | (yubico_version_buf[1] << 8) | yubico_version_buf[2];
5914
255
      sc_log(card->ctx, "Yubikey version test card->type=%d, r=0x%08x version=0x%08x", card->type, r, priv->yubico_version);
5915
255
      if (priv->yubico_version == 1) {
5916
2
        sc_log(card->ctx, "Detected Alpha/development version of yubikey. Assuming v6");
5917
2
        priv->yubico_version = 0x060000;
5918
2
      }
5919
255
    }
5920
1.83k
    break;
5921
2.01k
  }
5922
5923
2.01k
  sc_debug(card->ctx, SC_LOG_DEBUG_MATCH, "PIV_MATCH card->type:%d r2:%d CI:%08x r:%d AI:%08x\n",
5924
2.01k
      card->type, r2, priv->card_issues, r, priv->alg_ids);
5925
5926
  /* We now know PIV AID is active, test CCC object. 800-73-* say CCC is required */
5927
  /* CCC not readable over contactless, unless using VCI. but dont need CCC for SC_CARD_TYPE_PIV_II_800_73_4 */
5928
2.01k
  switch (card->type) {
5929
  /*
5930
   * For cards that may also be CAC, try and read the CCC
5931
   * CCC is required and all Dual PIV/CAC will have a CCC
5932
   * Currently Dual PIV/CAC are based on NIST 800-73-1 which does not have Discovery or History
5933
   */
5934
1.43k
  case SC_CARD_TYPE_PIV_II_BASE: /* i.e. really dont know what this is */
5935
1.43k
  case SC_CARD_TYPE_PIV_II_GENERIC:
5936
1.43k
  case SC_CARD_TYPE_PIV_II_HIST:
5937
1.43k
  case SC_CARD_TYPE_PIV_II_GI_DE:
5938
1.44k
  case SC_CARD_TYPE_PIV_II_GEMALTO:
5939
1.46k
  case SC_CARD_TYPE_PIV_II_OBERTHUR:
5940
1.46k
    r2 = piv_process_ccc(card);
5941
1.46k
    sc_debug(card->ctx, SC_LOG_DEBUG_MATCH, "PIV_MATCH card->type:%d r2:%d CI:%08x r:%d AI:%08x\n",
5942
1.46k
        card->type, r2, priv->card_issues, r, priv->alg_ids);
5943
    /* Ignore any error. */
5944
    /* If CCC says it has CAC with PKI on card set to one of the SC_CARD_TYPE_PIV_II_*_DUAL_CAC */
5945
1.46k
    if (priv->ccc_flags & PIV_CCC_F3_CAC_PKI) {
5946
17
      switch (card->type) {
5947
14
      case SC_CARD_TYPE_PIV_II_BASE:
5948
14
      case SC_CARD_TYPE_PIV_II_GENERIC:
5949
15
      case SC_CARD_TYPE_PIV_II_HIST:
5950
15
      case SC_CARD_TYPE_PIV_II_GI_DE:
5951
15
        card->type = SC_CARD_TYPE_PIV_II_GI_DE_DUAL_CAC;
5952
15
        priv->card_issues |= CI_DISCOVERY_USELESS;
5953
15
        priv->obj_cache[PIV_OBJ_DISCOVERY].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
5954
15
        break;
5955
1
      case SC_CARD_TYPE_PIV_II_GEMALTO:
5956
1
        card->type = SC_CARD_TYPE_PIV_II_GEMALTO_DUAL_CAC;
5957
1
        priv->card_issues |= CI_DISCOVERY_USELESS;
5958
1
        priv->obj_cache[PIV_OBJ_DISCOVERY].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
5959
1
        break;
5960
1
      case SC_CARD_TYPE_PIV_II_OBERTHUR:
5961
1
        card->type = SC_CARD_TYPE_PIV_II_OBERTHUR_DUAL_CAC;
5962
1
        priv->card_issues |= CI_DISCOVERY_USELESS;
5963
1
        priv->obj_cache[PIV_OBJ_DISCOVERY].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
5964
1
        break;
5965
17
      }
5966
17
    }
5967
1.46k
    break;
5968
5969
1.46k
  case SC_CARD_TYPE_PIV_II_GI_DE_DUAL_CAC:
5970
8
  case SC_CARD_TYPE_PIV_II_GEMALTO_DUAL_CAC:
5971
8
  case SC_CARD_TYPE_PIV_II_OBERTHUR_DUAL_CAC:
5972
8
    priv->card_issues |= CI_DISCOVERY_USELESS;
5973
8
    priv->obj_cache[PIV_OBJ_DISCOVERY].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
5974
8
    break;
5975
2.01k
  }
5976
2.01k
  sc_debug(card->ctx, SC_LOG_DEBUG_MATCH, "PIV_MATCH card->type:%d r2:%d CI:%08x r:%d AI:%08x\n",
5977
2.01k
      card->type, r2, priv->card_issues, r, priv->alg_ids);
5978
5979
  /* If contactless or run as virtual card try to get alg refs from AC entries in response to SELECT AID */
5980
2.01k
  if (!(priv->init_flags & PIV_INIT_AID_PARSED) && priv->init_flags & PIV_INIT_CONTACTLESS) {
5981
0
    r2 = piv_find_aid(card);
5982
0
  }
5983
5984
  /* Read AID if needed for these cards types */
5985
2.01k
  if (!(priv->init_flags & PIV_INIT_AID_PARSED)) {
5986
436
    switch (card->type) {
5987
0
    case SC_CARD_TYPE_PIV_II_BASE:
5988
0
    case SC_CARD_TYPE_PIV_II_GENERIC:
5989
1
    case SC_CARD_TYPE_PIV_II_800_73_4:
5990
2
    case SC_CARD_TYPE_PIV_II_NITROKEY:
5991
6
    case SC_CARD_TYPE_PIV_II_TOKEN2:
5992
6
    case SC_CARD_TYPE_PIV_II_PIVAPPLET:
5993
6
    case SC_CARD_TYPE_PIV_II_OPENFIPS201:
5994
5995
6
      r2 = piv_find_aid(card);
5996
436
    }
5997
436
  }
5998
5999
2.01k
  sc_debug(card->ctx, SC_LOG_DEBUG_MATCH, "PIV_MATCH card->type:%d r2:%d CI:%08x r:%d AI:%08x\n",
6000
2.01k
      card->type, r2, priv->card_issues, r, priv->alg_ids);
6001
6002
  /* if card did not specify any of the NIST basic alg_ids add them */
6003
2.01k
  if ((priv->alg_ids & AI_NIST) == 0) {
6004
2.01k
    priv->alg_ids |= AI_NIST;
6005
2.01k
  }
6006
6007
  /* If unknown card has 800-73-4 features, it must be based on 800-73-4 or above */
6008
2.01k
  switch (card->type) {
6009
1.42k
  case SC_CARD_TYPE_PIV_II_BASE:
6010
1.42k
  case SC_CARD_TYPE_PIV_II_GENERIC:
6011
1.42k
    if (priv->init_flags & PIV_INIT_AID_AC_SM) {
6012
0
      card->type = SC_CARD_TYPE_PIV_II_800_73_4;
6013
0
    }
6014
6015
#ifdef ENABLE_PIV_SM
6016
    /* Discovery object has pin policy. 800-74-4 bits, its at least SC_CARD_TYPE_PIV_II_800_73_4 */
6017
    if ((priv->pin_policy & (PIV_PP_OCC | PIV_PP_VCI_IMPL | PIV_PP_VCI_WITHOUT_PC)) != 0) {
6018
      card->type = SC_CARD_TYPE_PIV_II_800_73_4;
6019
    }
6020
#endif
6021
1.42k
    break;
6022
2.01k
  }
6023
6024
2.01k
  sc_debug(card->ctx, SC_LOG_DEBUG_MATCH, "PIV_MATCH card->type:%d r2:%d CI:%08x r:%d AI:%08x\n",
6025
2.01k
      card->type, r2, priv->card_issues, r, priv->alg_ids);
6026
6027
  /*
6028
   * Set card_issues flags based card->type and version numbers if available.
6029
   *
6030
   * YubiKey NEO, Yubikey 4 and other devices with PIV applets, have compliance
6031
   * issues with the NIST 800-73-3 specs. The OpenSC developers do not have
6032
   * access to all the different devices or versions of the devices.
6033
   * Vendor and user input is welcome on any compliance issues.
6034
   *
6035
   * For the Yubico devices The assumption is also made that if a bug is
6036
   * fixed in a Yubico version that means it is fixed on both NEO and Yubikey 4.
6037
   *
6038
   * The flags CI_CANT_USE_GETDATA_FOR_STATE and CI_DISCOVERY_USELESS
6039
   * may be set earlier or later then in the following code.
6040
   */
6041
6042
2.01k
  sc_debug(card->ctx, SC_LOG_DEBUG_MATCH, "PIV_MATCH card->type:%d r2:%d CI:%08x r:%d AI:%08x\n",
6043
2.01k
      card->type, r2, priv->card_issues, r, priv->alg_ids);
6044
2.01k
  switch (card->type) {
6045
301
  case SC_CARD_TYPE_PIV_II_NEO:
6046
301
    priv->card_issues |= CI_NO_EC384 |
6047
301
             CI_VERIFY_630X |
6048
301
             CI_OTHER_AID_LOSE_STATE |
6049
301
             CI_LEAKS_FILE_NOT_FOUND |
6050
301
             CI_NFC_EXPOSE_TOO_MUCH;
6051
301
    if (priv->yubico_version < 0x00040302)
6052
280
      priv->card_issues |= CI_VERIFY_LC0_FAIL;
6053
301
    break;
6054
6055
1
  case SC_CARD_TYPE_PIV_II_OPENFIPS201:
6056
    /* also supports using yubico-piv-tool */
6057
1
    priv->card_issues |= CI_ENFORCES_EC_HASH_EQ_KEYSIZE |
6058
1
             CI_OTHER_AID_LOSE_STATE |
6059
1
             CI_LEAKS_FILE_NOT_FOUND;
6060
1
    break;
6061
6062
7
  case SC_CARD_TYPE_PIV_II_YUBIKEY4:
6063
9
  case SC_CARD_TYPE_PIV_II_PIVAPPLET:
6064
66
  case SC_CARD_TYPE_PIV_II_TOKEN2:
6065
66
    priv->card_issues |= CI_OTHER_AID_LOSE_STATE |
6066
66
             CI_LEAKS_FILE_NOT_FOUND;
6067
66
    if (priv->yubico_version < 0x00040302)
6068
35
      priv->card_issues |= CI_VERIFY_LC0_FAIL;
6069
66
    if (priv->yubico_version >= 0x00050700) /* Also used by Token2 */
6070
14
      priv->alg_ids |= AI_RSA_4096 | AI_25519 | AI_X25519;
6071
66
    break;
6072
6073
31
  case SC_CARD_TYPE_PIV_II_NITROKEY:
6074
31
    priv->card_issues |= CI_OTHER_AID_LOSE_STATE;
6075
31
    if (priv->yubico_version >= 0x00010802) /* use for NitroKey too */
6076
13
      priv->alg_ids |= AI_RSA_4096;
6077
31
    break;
6078
6079
0
  case SC_CARD_TYPE_PIV_II_GI_DE:
6080
17
  case SC_CARD_TYPE_PIV_II_OBERTHUR:
6081
25
  case SC_CARD_TYPE_PIV_II_GEMALTO:
6082
26
  case SC_CARD_TYPE_PIV_II_SWISSBIT:
6083
26
    priv->card_issues |= 0; /* could add others here */
6084
26
    break;
6085
6086
1.42k
  case SC_CARD_TYPE_PIV_II_BASE:
6087
1.42k
  case SC_CARD_TYPE_PIV_II_HIST:
6088
1.42k
  case SC_CARD_TYPE_PIV_II_800_73_4:
6089
1.42k
    priv->card_issues |= 0; /* could add others here */
6090
1.42k
    break;
6091
6092
23
  case SC_CARD_TYPE_PIV_II_GI_DE_DUAL_CAC:
6093
24
  case SC_CARD_TYPE_PIV_II_GEMALTO_DUAL_CAC:
6094
25
  case SC_CARD_TYPE_PIV_II_OBERTHUR_DUAL_CAC:
6095
25
    priv->card_issues |= CI_VERIFY_LC0_FAIL |
6096
25
             CI_PIV_AID_LOSE_STATE |
6097
25
             CI_NO_RANDOM |
6098
25
             CI_OTHER_AID_LOSE_STATE;
6099
25
    break;
6100
6101
0
  case SC_CARD_TYPE_PIV_II_GENERIC:
6102
0
    priv->card_issues |= CI_VERIFY_LC0_FAIL |
6103
0
             CI_OTHER_AID_LOSE_STATE;
6104
0
    break;
6105
6106
143
  case SC_CARD_TYPE_PIV_II_PIVKEY:
6107
143
    priv->card_issues |= CI_VERIFY_LC0_FAIL |
6108
143
             CI_PIV_AID_LOSE_STATE | /* be conservative */
6109
143
             CI_NO_RANDOM;      /* does not have 9B key */
6110
                   /* Discovery object returns 6A 82 so is not on card by default */
6111
143
    break;
6112
6113
0
  default:
6114
0
    priv->card_issues |= CI_VERIFY_LC0_FAIL |
6115
0
             CI_OTHER_AID_LOSE_STATE;
6116
    /* opensc.conf may have it wrong, continue anyway */
6117
0
    sc_log(card->ctx, "Unknown PIV card->type %d", card->type);
6118
0
    card->type = SC_CARD_TYPE_PIV_II_GENERIC;
6119
2.01k
  }
6120
2.01k
  sc_log(card->ctx, "PIV_MATCH card->type:%d r2:%d CI:%08x r:%d AI:%08x\n",
6121
2.01k
      card->type, r2, priv->card_issues, r, priv->alg_ids);
6122
6123
2.01k
  if (!(priv->card_issues & CI_DISCOVERY_USELESS) && !(priv->init_flags & PIV_INIT_DISCOVERY_PARSED)) {
6124
    /*
6125
     * We now know PIV AID is active, test DISCOVERY object again
6126
     * Some PIV don't support DISCOVERY and return
6127
     * SC_ERROR_INCORRECT_PARAMETERS. Any error
6128
     * including SC_ERROR_FILE_NOT_FOUND means we cannot use discovery
6129
     * to test for active AID.
6130
     */
6131
1.56k
    r2 = piv_find_discovery(card);
6132
6133
1.56k
    if (r2 < 0) {
6134
1.56k
      priv->card_issues |= CI_DISCOVERY_USELESS;
6135
1.56k
      piv_obj_cache_free_entry(card, PIV_OBJ_DISCOVERY, PIV_OBJ_CACHE_NOT_PRESENT);
6136
1.56k
    }
6137
1.56k
  }
6138
6139
2.01k
  sc_log(card->ctx, "PIV_MATCH card->type:%d r2:%d CI:%08x r:%d AI:%08x\n",
6140
2.01k
      card->type, r2, priv->card_issues, r, priv->alg_ids);
6141
  /* Matched, caller will use or free priv and sc_lock as needed */
6142
2.01k
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
6143
6144
2.85k
err:
6145
2.85k
  sc_debug(card->ctx, SC_LOG_DEBUG_MATCH, "PIV_MATCH failed card->type:%d r2:%d CI:%08x r:%d AI:%08x\n",
6146
2.85k
      card->type, r2, priv->card_issues, r, priv->alg_ids);
6147
  /* don't match. Does not have a PIV applet. */
6148
2.85k
  piv_finish(card);
6149
2.85k
  card->type = saved_type;
6150
2.85k
  LOG_FUNC_RETURN(card->ctx, r);
6151
2.85k
}
6152
6153
static int
6154
piv_init(sc_card_t *card)
6155
3.39k
{
6156
3.39k
  int r = 0;
6157
3.39k
  piv_private_data_t *priv = PIV_DATA(card);
6158
3.39k
  unsigned long flags;
6159
3.39k
  unsigned long flags_eddsa;
6160
3.39k
  unsigned long flags_xeddsa;
6161
3.39k
  unsigned long ext_flags;
6162
6163
3.39k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
6164
6165
3.39k
  r = sc_lock(card); /* hold until match or init is complete */
6166
3.39k
  LOG_TEST_RET(card->ctx, r, "sc_lock failed");
6167
6168
  /* piv_match_card_continued called from card match should have left card->drv_data */
6169
3.39k
  if (priv == NULL) {
6170
1.47k
    r = piv_match_card_continued(card);
6171
1.47k
    priv = PIV_DATA(card);
6172
1.47k
    if (r < 0 || !priv) {
6173
1.37k
      sc_log(card->ctx, "piv_match_card_continued failed card->type:%d", card->type);
6174
1.37k
      sc_unlock(card);
6175
1.37k
      piv_finish(card);
6176
      /* tell sc_connect_card to try other driver */
6177
1.37k
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD);
6178
1.37k
    }
6179
1.47k
  }
6180
6181
  /* read "card_driver PIV-II" opensc.conf options, and env parameters */
6182
2.01k
  piv_load_options(card);
6183
6184
2.01k
  priv->pstate = PIV_STATE_INIT;
6185
6186
2.01k
  sc_log(card->ctx, "Max send = %zu recv = %zu card->type:%d, CI:%08x AI:%08x",
6187
2.01k
      card->max_send_size, card->max_recv_size, card->type, priv->card_issues, priv->alg_ids);
6188
2.01k
  card->cla = 0x00;
6189
2.01k
  if (card->name == NULL)
6190
2.01k
    card->name = card->driver->name;
6191
6192
2.01k
  priv->enumtag = piv_aids[0].enumtag;
6193
6194
  /* PKCS#11 may try to generate session keys, and get confused
6195
   * if SC_ALGORITHM_ONBOARD_KEY_GEN is present
6196
   * piv-tool can still do this, just don't tell PKCS#11
6197
   */
6198
6199
2.01k
  flags = SC_ALGORITHM_RSA_RAW;
6200
6201
2.01k
  if (card->type == SC_CARD_TYPE_PIV_II_SWISSBIT) {
6202
1
    flags |= SC_ALGORITHM_ONBOARD_KEY_GEN;
6203
1
  }
6204
6205
2.01k
  if (priv->alg_ids & AI_RSA_1024)
6206
2.01k
    _sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */
6207
6208
2.01k
  if (priv->alg_ids & AI_RSA_2048)
6209
2.01k
    _sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */
6210
6211
2.01k
  if (priv->alg_ids & AI_RSA_3072)
6212
2.01k
    _sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */
6213
6214
2.01k
  if (priv->alg_ids & AI_RSA_4096)
6215
28
    _sc_card_add_rsa_alg(card, 4096, flags, 0); /* non standard */
6216
6217
2.01k
  if (!(priv->card_issues & CI_NO_EC)) {
6218
2.01k
    int i;
6219
2.01k
    flags = SC_ALGORITHM_ECDSA_RAW | SC_ALGORITHM_ECDH_CDH_RAW | SC_ALGORITHM_ECDSA_HASH_NONE;
6220
2.01k
    ext_flags = SC_ALGORITHM_EXT_EC_NAMEDCURVE | SC_ALGORITHM_EXT_EC_UNCOMPRESES;
6221
2.01k
    flags_eddsa = SC_ALGORITHM_EDDSA_RAW;
6222
2.01k
    flags_xeddsa = SC_ALGORITHM_XEDDSA_RAW | SC_ALGORITHM_ECDH_CDH_RAW;
6223
6224
10.0k
    for (i = 0; ec_curves[i].oid.value[0] >= 0; i++) {
6225
8.07k
      if (ec_curves[i].key_type == SC_ALGORITHM_EC) {
6226
4.03k
        if (!(priv->card_issues & CI_NO_EC384 && ec_curves[i].size == 384))
6227
3.73k
          _sc_card_add_ec_alg(card, ec_curves[i].size, flags, ext_flags, &ec_curves[i].oid);
6228
4.03k
      }
6229
6230
4.03k
      else if (priv->alg_ids & AI_25519 && ec_curves[i].key_type == SC_ALGORITHM_EDDSA)
6231
15
        _sc_card_add_eddsa_alg(card, ec_curves[i].size, flags_eddsa, ext_flags, &ec_curves[i].oid);
6232
6233
4.02k
      else if (priv->alg_ids & AI_X25519 && ec_curves[i].key_type == SC_ALGORITHM_XEDDSA)
6234
17
        _sc_card_add_xeddsa_alg(card, ec_curves[i].size, flags_xeddsa, ext_flags, &ec_curves[i].oid);
6235
8.07k
    }
6236
2.01k
  }
6237
6238
2.01k
  if (!(priv->card_issues & CI_NO_RANDOM))
6239
1.85k
    card->caps |= SC_CARD_CAP_RNG;
6240
6241
  /* May turn off SC_CARD_CAP_ISO7816_PIN_INFO later */
6242
2.01k
  card->caps |= SC_CARD_CAP_ISO7816_PIN_INFO;
6243
6244
  /*
6245
   * 800-73-3 cards may have discovery. "piv-like cards may or may not.
6246
   * 800-73-4 with VCI must have it as it has the pin policy needed for VCI .
6247
   */
6248
6249
#ifdef ENABLE_PIV_SM
6250
  /*
6251
   * 800-73-4
6252
   * Response of AID says if SM is supported. Look for Cipher Suite
6253
   */
6254
  if (priv->csID && priv->cs != NULL) {
6255
    /*
6256
     * Main point in SM and VCI is to allow contactless access
6257
     */
6258
    /* Only piv_init and piv_reader_lock_obtained should call piv_sm_open */
6259
6260
    /* If user said PIV_SM_FLAGS_NEVER, dont start SM; implies limited contatless access */
6261
    if (priv->sm_flags & PIV_SM_FLAGS_NEVER) {
6262
      sc_log(card->ctx, "User has requested PIV_SM_FLAGS_NEVER");
6263
      r = SC_SUCCESS; /* Users choice */
6264
6265
    } else if ((priv->init_flags & PIV_INIT_CONTACTLESS) &&
6266
        !(priv->pin_policy & PIV_PP_VCI_IMPL)) {
6267
      sc_log(card->ctx, "Contactless and no card support for VCI");
6268
      r = SC_SUCCESS; /* User should know VCI is not possible with their card; use like 800-73-3 contactless  */
6269
6270
    } else if ((priv->init_flags & PIV_INIT_CONTACTLESS) &&
6271
        !(priv->pin_policy & PIV_PP_VCI_WITHOUT_PC) &&
6272
        (priv->pairing_code[0] == 0x00)) {
6273
      sc_log(card->ctx, "Contactless, pairing_code required and no pairing code");
6274
      r = SC_ERROR_PIN_CODE_INCORRECT; /* User should know they need to set pairing code */
6275
6276
    } else {
6277
      priv->sm_flags |= PIV_SM_FLAGS_DEFER_OPEN; /* tell priv_sm_open, OK to open */
6278
      r = piv_sm_open(card);
6279
      sc_log(card->ctx, "piv_sm_open returned:%d", r);
6280
    }
6281
6282
    /* If failed, and user said PIV_SM_FLAGS_ALWAYS quit */
6283
    if (priv->sm_flags & PIV_SM_FLAGS_ALWAYS && r < 0) {
6284
      sc_log(card->ctx, "User has requested PIV_SM_FLAGS_ALWAYS, SM has failed to start, don't use the card");
6285
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ALLOWED);
6286
    }
6287
6288
    /* user has wrong or no required pairing code */
6289
    if (r == SC_ERROR_PIN_CODE_INCORRECT)
6290
      LOG_FUNC_RETURN(card->ctx, r);
6291
6292
    /* If SM did not start, or is not expected to start, continue on without it */
6293
  }
6294
#endif /* ENABLE_PIV_SM */
6295
6296
  /*
6297
   * 800-73-3 cards may have a history object
6298
   * We want to process it now as this has information on what
6299
   * keys and certs. "piv like" cards may or may not have history
6300
   */
6301
2.01k
  piv_process_history(card);
6302
6303
2.01k
  priv->pstate = PIV_STATE_NORMAL;
6304
2.01k
  sc_unlock(card);
6305
2.01k
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
6306
2.01k
}
6307
6308
static int
6309
piv_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2)
6310
103k
{
6311
103k
  struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
6312
6313
103k
  int r;
6314
#ifdef ENABLE_PIV_SM
6315
  int i;
6316
#endif
6317
103k
  piv_private_data_t *priv = PIV_DATA(card);
6318
6319
103k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
6320
6321
  /* may be called before piv_init has allocated priv */
6322
103k
  if (priv) {
6323
    /* need to save sw1 and sw2 if trying to determine card_state from pin_cmd */
6324
6325
103k
    if (priv->pin_cmd_verify) {
6326
0
      priv->pin_cmd_verify_sw1 = sw1;
6327
0
      priv->pin_cmd_verify_sw2 = sw2;
6328
103k
    } else {
6329
      /* a command has completed and it is not verify
6330
       * If we are in a context_specific sequence, unlock
6331
       * This just decrements the extra lock count
6332
       */
6333
103k
      if (priv->context_specific) {
6334
0
        sc_log(card->ctx, "Clearing CONTEXT_SPECIFIC lock");
6335
0
        priv->context_specific = 0;
6336
0
        sc_unlock(card);
6337
0
      }
6338
103k
    }
6339
6340
103k
    if (priv->card_issues & CI_VERIFY_630X) {
6341
6342
      /* Handle the Yubikey NEO or any other PIV card which returns in response to a verify
6343
       * 63 0X rather than 63 CX indicate the number of remaining PIN retries.
6344
       * Perhaps they misread the spec and thought 0xCX meant "clear" or "don't care", not a literal 0xC!
6345
       */
6346
72.3k
      if (priv->pin_cmd_verify && sw1 == 0x63U) {
6347
0
        priv->pin_cmd_verify_sw2 |= 0xC0U; /* make it easier to test in other code */
6348
0
        if ((sw2 & ~0x0fU) == 0x00U) {
6349
0
          sc_log(card->ctx, "Verification failed (remaining tries: %d)", (sw2 & 0x0f));
6350
0
          return SC_ERROR_PIN_CODE_INCORRECT;
6351
          /* this is what the iso_check_sw returns for 63 C0 */
6352
0
        }
6353
0
      }
6354
72.3k
    }
6355
103k
  }
6356
#ifdef ENABLE_PIV_SM
6357
  /* Note 6982 is map to SC_ERROR_SM_NO_SESSION_KEYS but iso maps it to SC_ERROR_SECURITY_STATUS_NOT_SATISFIED */
6358
  /* we do this because 6982 could also mean a verify is not allowed over contactless without VCI */
6359
  /* we stashed the sw1 and sw2 above for verify */
6360
  /* Check specific NIST sp800-73-4 SM  errors */
6361
  for (i = 0; piv_sm_errors[i].SWs != 0; i++) {
6362
    if (piv_sm_errors[i].SWs == ((sw1 << 8) | sw2)) {
6363
      sc_log(card->ctx, "%s", piv_sm_errors[i].errorstr);
6364
      return piv_sm_errors[i].errorno;
6365
    }
6366
  }
6367
#endif
6368
103k
  r = iso_drv->ops->check_sw(card, sw1, sw2);
6369
103k
  return r;
6370
103k
}
6371
6372
static int
6373
piv_check_protected_objects(sc_card_t *card)
6374
0
{
6375
0
  int r = 0;
6376
0
  int i;
6377
0
  piv_private_data_t *priv = PIV_DATA(card);
6378
0
  u8 buf[8]; /* tag of 53 with 82 xx xx  will fit in 4 */
6379
0
  u8 *rbuf;
6380
0
  size_t buf_len;
6381
0
  static int protected_objects[] = {PIV_OBJ_PI, PIV_OBJ_CHF, PIV_OBJ_IRIS_IMAGE};
6382
6383
0
  LOG_FUNC_CALLED(card->ctx);
6384
  /*
6385
   * routine only called from piv_pin_cmd after verify lc=0 did not return 90 00
6386
   * We will test for a protected object using GET DATA.
6387
   *
6388
   * Based on observations, of cards using the GET DATA APDU,
6389
   * SC_ERROR_SECURITY_STATUS_NOT_SATISFIED  means the PIN not verified,
6390
   * SC_SUCCESS means PIN has been verified even if it has length 0
6391
   * SC_ERROR_FILE_NOT_FOUND (which is the bug) does not tell us anything
6392
   * about the state of the PIN and we will try the next object.
6393
   *
6394
   * If we can't determine the security state from this process,
6395
   * set card_issues CI_CANT_USE_GETDATA_FOR_STATE
6396
   * and return SC_ERROR_PIN_CODE_INCORRECT
6397
   * The circumvention is to add a dummy Printed Info object in the card.
6398
   * so we will have an object to test.
6399
   *
6400
   * We save the object's number to use in the future.
6401
   *
6402
   */
6403
0
  if (priv->object_test_verify == 0) {
6404
0
    for (i = 0; i < (int)(sizeof(protected_objects) / sizeof(int)); i++) {
6405
0
      buf_len = sizeof(buf);
6406
0
      rbuf = buf;
6407
0
      r = piv_get_data(card, protected_objects[i], &rbuf, &buf_len);
6408
0
      if (r >= 0 || r == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {
6409
6410
        /* we can use this object next time if needed */
6411
0
        priv->object_test_verify = protected_objects[i];
6412
0
        break;
6413
0
      }
6414
0
    }
6415
0
    if (priv->object_test_verify == 0) {
6416
      /*
6417
       * none of the objects returned acceptable sw1, sw2
6418
       */
6419
0
      sc_log(card->ctx, "No protected objects found, setting CI_CANT_USE_GETDATA_FOR_STATE");
6420
0
      priv->card_issues |= CI_CANT_USE_GETDATA_FOR_STATE;
6421
0
      r = SC_ERROR_PIN_CODE_INCORRECT;
6422
0
    }
6423
0
  } else {
6424
    /* use the one object we found earlier. Test is security status has changed */
6425
0
    buf_len = sizeof(buf);
6426
0
    rbuf = buf;
6427
0
    r = piv_get_data(card, priv->object_test_verify, &rbuf, &buf_len);
6428
0
  }
6429
0
  if (r == SC_ERROR_FILE_NOT_FOUND)
6430
0
    r = SC_ERROR_PIN_CODE_INCORRECT;
6431
0
  else if (r == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED)
6432
0
    r = SC_ERROR_PIN_CODE_INCORRECT;
6433
0
  else if (r > 0)
6434
0
    r = SC_SUCCESS;
6435
6436
0
  sc_log(card->ctx, "card->type:%d CI:%08x r:%d AI:%08x\n",
6437
0
      card->type, priv->card_issues, r, priv->alg_ids);
6438
0
  LOG_FUNC_RETURN(card->ctx, r);
6439
0
}
6440
6441
static int
6442
piv_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data)
6443
0
{
6444
0
  int r = 0;
6445
0
  piv_private_data_t *priv = PIV_DATA(card);
6446
6447
  /* Extra validation of (new) PIN during a PIN change request, to
6448
   * ensure it's not outside the FIPS 201 4.1.6.1 (numeric only) and
6449
   * FIPS 140-2 (6 character minimum) requirements.
6450
   */
6451
0
  struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
6452
6453
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
6454
0
  sc_log(card->ctx, "piv_pin_cmd tries_left=%d, logged_in=%d", priv->tries_left, priv->logged_in);
6455
0
  if (data->cmd == SC_PIN_CMD_CHANGE) {
6456
0
    size_t i = 0;
6457
0
    if (data->pin2.len < 6) {
6458
0
      return SC_ERROR_INVALID_PIN_LENGTH;
6459
0
    }
6460
0
    for (i = 0; i < data->pin2.len; ++i) {
6461
0
      if (!isdigit(data->pin2.data[i])) {
6462
0
        return SC_ERROR_INVALID_DATA;
6463
0
      }
6464
0
    }
6465
0
  }
6466
6467
0
  priv->pin_cmd_verify_sw1 = 0x00U;
6468
6469
0
  if (data->cmd == SC_PIN_CMD_GET_INFO) { /* fill in what we think it should be */
6470
0
    data->pin1.logged_in = priv->logged_in;
6471
0
    data->pin1.tries_left = priv->tries_left;
6472
6473
    /*
6474
     * If called to check on the login state for a context specific login
6475
     * return not logged in. Needed because of logic in e6f7373ef066
6476
     */
6477
0
    if (data->pin_type == SC_AC_CONTEXT_SPECIFIC) {
6478
0
      data->pin1.logged_in = SC_PIN_STATE_LOGGED_OUT;
6479
0
      LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
6480
0
    }
6481
6482
0
    if (priv->logged_in & SC_PIN_STATE_LOGGED_IN) {
6483
      /* Avoid status requests when the user is logged in to handle NIST
6484
       * 800-73-4 Part 2:
6485
       * The PKI cryptographic function (see Table 4b) is protected with
6486
       * a “PIN Always” or “OCC Always” access rule. In other words, the
6487
       * PIN or OCC data must be submitted and verified every time
6488
       * immediately before a digital signature key operation.  This
6489
       * ensures cardholder participation every time the private key is
6490
       * used for digital signature generation */
6491
0
      LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
6492
0
    }
6493
0
  }
6494
6495
  /*
6496
   * If this was for a CKU_CONTEXT_SPECFIC login, lock the card one more time.
6497
   * to avoid any interference from other applications.
6498
   * Sc_unlock will be called at a later time after the next card command
6499
   * that should be a crypto operation. If its not then it is a error by the
6500
   * calling application.
6501
   */
6502
0
  if (data->cmd == SC_PIN_CMD_VERIFY && data->pin_type == SC_AC_CONTEXT_SPECIFIC) {
6503
0
    priv->context_specific = 1;
6504
0
    sc_log(card->ctx, "Starting CONTEXT_SPECIFIC verify");
6505
0
    r = sc_lock(card);
6506
0
    if (r != SC_SUCCESS) {
6507
0
      sc_log(card->ctx, "sc_lock failed");
6508
0
      return r;
6509
0
    }
6510
0
  }
6511
6512
0
  priv->pin_cmd_verify = 1; /* tell piv_check_sw its a verify to save sw1, sw2 */
6513
0
  r = iso_drv->ops->pin_cmd(card, data);
6514
0
  priv->pin_cmd_verify = 0;
6515
6516
  /* tell user verify not supported on contactless without VCI */
6517
0
  if (priv->pin_cmd_verify_sw1 == 0x69 && priv->pin_cmd_verify_sw2 == 0x82 &&
6518
0
      priv->init_flags & PIV_INIT_CONTACTLESS &&
6519
0
      card->type == SC_CARD_TYPE_PIV_II_800_73_4) {
6520
0
    sc_log(card->ctx, "Token does not support pin verify over contacless reader");
6521
0
    r = SC_ERROR_NOT_SUPPORTED;
6522
0
  }
6523
6524
  /* if verify failed, release the lock */
6525
0
  if (data->cmd == SC_PIN_CMD_VERIFY && r < 0 && priv->context_specific) {
6526
0
    sc_log(card->ctx, "Clearing CONTEXT_SPECIFIC");
6527
0
    priv->context_specific = 0;
6528
0
    sc_unlock(card);
6529
0
  }
6530
6531
  /* if access to applet is know to be reset by other driver  we select_aid and try again */
6532
0
  if (priv->card_issues & CI_OTHER_AID_LOSE_STATE && priv->pin_cmd_verify_sw1 == 0x6DU) {
6533
0
    sc_log(card->ctx, "AID may be lost doing piv_find_aid and retry pin_cmd");
6534
0
    piv_find_aid(card);
6535
6536
0
    priv->pin_cmd_verify = 1; /* tell piv_check_sw its a verify to save sw1, sw2 */
6537
0
    r = iso_drv->ops->pin_cmd(card, data);
6538
0
    priv->pin_cmd_verify = 0;
6539
0
  }
6540
6541
  /* If verify worked, we are logged_in */
6542
0
  if (data->cmd == SC_PIN_CMD_VERIFY) {
6543
0
    if (r >= 0) {
6544
0
      priv->logged_in = SC_PIN_STATE_LOGGED_IN;
6545
      /* the card reset its retry counter; the reset value is issuer dependent */
6546
0
      priv->tries_left = -1;
6547
0
    } else {
6548
0
      priv->logged_in = SC_PIN_STATE_LOGGED_OUT;
6549
0
    }
6550
0
  }
6551
6552
  /* Some cards never return 90 00  for SC_PIN_CMD_GET_INFO even if the card state is verified */
6553
  /* PR 797 has changed the return codes from pin_cmd, and added a data->pin1.logged_in flag */
6554
6555
0
  if (data->cmd == SC_PIN_CMD_GET_INFO) {
6556
0
    if (priv->card_issues & CI_CANT_USE_GETDATA_FOR_STATE) {
6557
0
      sc_log(card->ctx, "CI_CANT_USE_GETDATA_FOR_STATE set, assume logged_in=%d", priv->logged_in);
6558
0
      data->pin1.logged_in = priv->logged_in; /* use what ever we saw last */
6559
0
    } else if (priv->card_issues & CI_VERIFY_LC0_FAIL &&
6560
0
        priv->pin_cmd_verify_sw1 == 0x63U) { /* can not use modified return codes from iso->drv->pin_cmd */
6561
      /* try another method, looking at a protected object this may require adding one of these to NEO */
6562
0
      r = piv_check_protected_objects(card);
6563
0
      if (r == SC_SUCCESS)
6564
0
        data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN;
6565
0
      else if (r == SC_ERROR_PIN_CODE_INCORRECT) {
6566
0
        if (priv->card_issues & CI_CANT_USE_GETDATA_FOR_STATE) { /* we still can not determine login state */
6567
6568
0
          data->pin1.logged_in = priv->logged_in; /* may have be set from SC_PIN_CMD_VERIFY */
6569
0
        } else {
6570
0
          data->pin1.logged_in = SC_PIN_STATE_LOGGED_OUT;
6571
0
        }
6572
0
        r = SC_SUCCESS;
6573
0
      }
6574
0
    }
6575
0
    priv->logged_in = data->pin1.logged_in;
6576
0
    priv->tries_left = data->pin1.tries_left;
6577
0
  }
6578
6579
0
  sc_log(card->ctx, "piv_pin_cmd tries_left=%d, logged_in=%d", priv->tries_left, priv->logged_in);
6580
0
  LOG_FUNC_RETURN(card->ctx, r);
6581
0
}
6582
6583
static int
6584
piv_logout(sc_card_t *card)
6585
0
{
6586
0
  int r = SC_ERROR_INTERNAL;
6587
0
  piv_private_data_t *priv = PIV_DATA(card);
6588
6589
0
  LOG_FUNC_CALLED(card->ctx);
6590
6591
0
  if (priv) {
6592
    /* logout defined since 800-73-4 */
6593
0
    r = iso7816_logout(card, priv->pin_preference);
6594
0
    if (r == SC_SUCCESS) {
6595
0
      priv->logged_in = SC_PIN_STATE_LOGGED_OUT;
6596
0
    }
6597
0
  }
6598
6599
0
  LOG_FUNC_RETURN(card->ctx, r);
6600
0
}
6601
6602
/*
6603
 * Called when a sc_lock gets a reader lock and PCSC SCardBeginTransaction
6604
 * If SCardBeginTransaction may pass back that a card reset was seen since
6605
 * the last transaction  completed.
6606
 * There may have been one or more resets, by other card drivers in different
6607
 * processes, and they may have taken action already
6608
 * and changed the AID and or may have sent a  VERIFY with PIN
6609
 * So test the state of the card.
6610
 * this is very similar to what the piv_match routine does,
6611
 */
6612
6613
/* card.c also calls piv_sm_open before this if a reset was done, but
6614
 * does not say if a reset was done or not. May need to ignore the call
6615
 * the piv_sm_open in this case, but how? may need a open is active flag,
6616
 * in case it is the APDU done from open caused  triggered the case.
6617
 */
6618
static int
6619
piv_card_reader_lock_obtained(sc_card_t *card, int was_reset)
6620
50.7k
{
6621
50.7k
  int r = 0;
6622
50.7k
  u8 temp[SC_MAX_APDU_BUFFER_SIZE];
6623
50.7k
  size_t templen = sizeof(temp);
6624
50.7k
  piv_private_data_t *priv = PIV_DATA(card); /* may be null */
6625
6626
50.7k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
6627
6628
  /* We have a PCSC transaction and sc_lock */
6629
50.7k
  if (priv == NULL || priv->pstate == PIV_STATE_MATCH) {
6630
6.79k
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
6631
6.79k
        priv ? "PIV_STATE_MATCH" : "priv==NULL");
6632
6.79k
    r = 0; /* do nothing, piv_match will take care of it */
6633
6.79k
    goto err;
6634
6.79k
  }
6635
6636
43.9k
  priv->init_flags |= PIV_INIT_IN_READER_LOCK_OBTAINED;
6637
6638
  /* make sure our application is active */
6639
6640
  /* first see if AID is active AID by reading discovery object '7E' */
6641
  /* If not try selecting AID */
6642
6643
  /* but if card does not support DISCOVERY object we can not use it */
6644
43.9k
  if (priv->card_issues & CI_DISCOVERY_USELESS) {
6645
4.46k
    r = SC_ERROR_NO_CARD_SUPPORT;
6646
39.4k
  } else {
6647
39.4k
    r = piv_find_discovery(card);
6648
#ifdef ENABLE_PIV_SM
6649
    /*
6650
     * All 800-73-4 cards that support SM, also have a discovery object with
6651
     * the pin_policy, so can not have CI_DISCOVERY_USELESS
6652
     * Discovery object can be read with contact or contactless
6653
     * If read with SM and fails with 69 88  SC_ERROR_SM_INVALID_SESSION_KEY
6654
     * sm.c will close the SM connectrion, and set defer
6655
     */
6656
    if (was_reset == 0 && (r == SC_ERROR_SM_INVALID_SESSION_KEY || priv->sm_flags & PIV_SM_FLAGS_DEFER_OPEN)) {
6657
      sc_log(card->ctx, "SC_ERROR_SM_INVALID_SESSION_KEY || PIV_SM_FLAGS_DEFER_OPEN");
6658
      piv_sm_open(card);
6659
      r = piv_find_discovery(card);
6660
    }
6661
#endif /* ENABLE_PIV_SM */
6662
39.4k
  }
6663
6664
43.9k
  if (r < 0) {
6665
43.7k
    if (was_reset > 0 || !(priv->card_issues & CI_PIV_AID_LOSE_STATE)) {
6666
40.8k
      r = iso7816_select_aid(card, piv_aids[0].value, piv_aids[0].len_short, temp, &templen);
6667
40.8k
      sc_debug(card->ctx, SC_LOG_DEBUG_MATCH, "iso7816_select_aid card->type:%d r:%d\n", card->type, r);
6668
40.8k
    } else {
6669
2.85k
      r = 0; /* can't do anything with this card, hope there was no interference */
6670
2.85k
    }
6671
43.7k
  }
6672
6673
43.9k
  if (r < 0) /* bad error return will show up in sc_lock as error*/
6674
38.6k
    goto err;
6675
6676
5.34k
  if (was_reset > 0)
6677
0
    priv->logged_in = SC_PIN_STATE_UNKNOWN;
6678
6679
5.34k
  r = 0;
6680
6681
50.7k
err:
6682
50.7k
  if (priv)
6683
45.8k
    priv->init_flags &= ~PIV_INIT_IN_READER_LOCK_OBTAINED;
6684
50.7k
  LOG_FUNC_RETURN(card->ctx, r);
6685
50.7k
}
6686
6687
static struct sc_card_driver *
6688
sc_get_driver(void)
6689
3.39k
{
6690
3.39k
  struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
6691
6692
3.39k
  piv_ops = *iso_drv->ops;
6693
3.39k
  piv_ops.match_card = piv_match_card;
6694
3.39k
  piv_ops.init = piv_init;
6695
3.39k
  piv_ops.finish = piv_finish;
6696
6697
3.39k
  piv_ops.select_file = piv_select_file; /* must use get/put, could emulate? */
6698
3.39k
  piv_ops.get_challenge = piv_get_challenge;
6699
3.39k
  piv_ops.logout = piv_logout;
6700
3.39k
  piv_ops.read_binary = piv_read_binary;
6701
3.39k
  piv_ops.write_binary = piv_write_binary;
6702
3.39k
  piv_ops.set_security_env = piv_set_security_env;
6703
3.39k
  piv_ops.restore_security_env = piv_restore_security_env;
6704
3.39k
  piv_ops.compute_signature = piv_compute_signature;
6705
3.39k
  piv_ops.decipher = piv_decipher;
6706
3.39k
  piv_ops.check_sw = piv_check_sw;
6707
3.39k
  piv_ops.card_ctl = piv_card_ctl;
6708
3.39k
  piv_ops.pin_cmd = piv_pin_cmd;
6709
3.39k
  piv_ops.card_reader_lock_obtained = piv_card_reader_lock_obtained;
6710
6711
3.39k
  return &piv_drv;
6712
3.39k
}
6713
6714
struct sc_card_driver *
6715
sc_get_piv_driver(void)
6716
3.39k
{
6717
3.39k
  return sc_get_driver();
6718
3.39k
}