Coverage Report

Created: 2026-09-03 06:07

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/opensc/src/libopensc/card-openpgp.c
Line
Count
Source
1
/*
2
 * card-openpgp.c: Support for OpenPGP card
3
 *
4
 * Copyright (C) 2003  Olaf Kirch <okir@suse.de>
5
 *
6
 * This library is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
10
 *
11
 * This library is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
 */
20
21
/*
22
 * Specifications:
23
 * (all available from: https://gnupg.org/ftp/specs/)
24
 * https://gnupg.org/ftp/specs/openpgp-card-1.0.pdf (obsolete)
25
 * https://gnupg.org/ftp/specs/openpgp-card-1.1.pdf
26
 * https://gnupg.org/ftp/specs/OpenPGP-smart-card-application-2.0.pdf
27
 * https://gnupg.org/ftp/specs/OpenPGP-smart-card-application-2.1.pdf
28
 * https://gnupg.org/ftp/specs/OpenPGP-smart-card-application-2.2.pdf
29
 * https://gnupg.org/ftp/specs/OpenPGP-smart-card-application-3.0.pdf
30
 * https://gnupg.org/ftp/specs/OpenPGP-smart-card-application-3.1.pdf
31
 * https://gnupg.org/ftp/specs/OpenPGP-smart-card-application-3.2.pdf
32
 * https://gnupg.org/ftp/specs/OpenPGP-smart-card-application-3.3.pdf
33
 * https://gnupg.org/ftp/specs/OpenPGP-smart-card-application-3.3.0.pdf
34
 * https://gnupg.org/ftp/specs/OpenPGP-smart-card-application-3.3.1.pdf
35
 * https://gnupg.org/ftp/specs/OpenPGP-smart-card-application-3.4.pdf
36
 */
37
38
#ifdef HAVE_CONFIG_H
39
#include "config.h"
40
#endif
41
42
#include <stdlib.h>
43
#include <string.h>
44
#include <ctype.h>
45
#include <time.h>
46
47
#include "internal.h"
48
#include "asn1.h"
49
#include "cardctl.h"
50
#include "errors.h"
51
#ifdef ENABLE_OPENSSL
52
#include <openssl/evp.h>
53
#include <openssl/sha.h>
54
#endif /* ENABLE_OPENSSL */
55
56
#include "card-openpgp.h"
57
58
59
static const char default_cardname[]    = "OpenPGP card";
60
static const char default_cardname_v1[] = "OpenPGP card v1.x";
61
static const char default_cardname_v2[] = "OpenPGP card v2.x";
62
static const char default_cardname_v3[] = "OpenPGP card v3.x";
63
64
65
static const struct sc_atr_table pgp_atrs[] = {
66
  { "3b:fa:13:00:ff:81:31:80:45:00:31:c1:73:c0:01:00:00:90:00:b1", NULL, default_cardname_v1, SC_CARD_TYPE_OPENPGP_V1, 0, NULL },
67
  { "3b:da:18:ff:81:b1:fe:75:1f:03:00:31:c5:73:c0:01:40:00:90:00:0c", NULL, default_cardname_v2, SC_CARD_TYPE_OPENPGP_V2, 0, NULL },
68
  {
69
    "3b:da:11:ff:81:b1:fe:55:1f:03:00:31:84:73:80:01:80:00:90:00:e4",
70
    "ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:00:ff:ff:00",
71
    "Gnuk v1.x.x (OpenPGP v2.0)", SC_CARD_TYPE_OPENPGP_GNUK, 0, NULL
72
  },
73
  { "3b:fc:13:00:00:81:31:fe:15:59:75:62:69:6b:65:79:4e:45:4f:72:33:e1", NULL, "Yubikey NEO (OpenPGP v2.0)", SC_CARD_TYPE_OPENPGP_V2, 0, NULL },
74
  { "3b:f8:13:00:00:81:31:fe:15:59:75:62:69:6b:65:79:34:d4", NULL, "Yubikey 4 (OpenPGP v2.1)", SC_CARD_TYPE_OPENPGP_V2, 0, NULL },
75
  { "3b:fd:13:00:00:81:31:fe:15:80:73:c0:21:c0:57:59:75:62:69:4b:65:79:40", NULL, "Yubikey 5 (OpenPGP v3.4)", SC_CARD_TYPE_OPENPGP_V3, 0, NULL },
76
  { "3b:da:18:ff:81:b1:fe:75:1f:03:00:31:f5:73:c0:01:60:00:90:00:1c", NULL, default_cardname_v3, SC_CARD_TYPE_OPENPGP_V3, 0, NULL },
77
  { NULL, NULL, NULL, 0, 0, NULL }
78
};
79
80
81
static struct sc_card_operations *iso_ops;
82
static struct sc_card_operations pgp_ops;
83
static struct sc_card_driver pgp_drv = {
84
  "OpenPGP card",
85
  "openpgp",
86
  &pgp_ops,
87
  NULL, 0, NULL
88
};
89
90
// clang-format off
91
static pgp_ec_curves_t ec_curves_openpgp34[] = {
92
  /* OpenPGP 3.4+ Ed25519 and Curve25519 */
93
    {{{1, 3, 6, 1, 4, 1, 3029, 1, 5, 1, -1}}, 255, SC_ALGORITHM_XEDDSA}, /* curve25519 for encryption => CKK_EC_MONTGOMERY */
94
    {{{1, 3, 101, 110, -1}},      255, SC_ALGORITHM_XEDDSA}, /* RFC8410 OID equivalent to curve25519 */
95
    {{{1, 3, 6, 1, 4, 1, 11591, 15, 1, -1}},  255, SC_ALGORITHM_EDDSA}, /* ed25519 for signatures => CKK_EC_EDWARDS */
96
    {{{1, 3, 101, 112, -1}},      255, SC_ALGORITHM_EDDSA}, /* RFC8410 OID equivalent to ed25519 */
97
98
  /* v3.0+ supports: [RFC 4880 & 6637] 0x12 = ECDH, 0x13 = ECDSA */
99
    {{{1, 2, 840, 10045, 3, 1, 7, -1}},   256, SC_ALGORITHM_EC}, /* ansiX9p256r1 */
100
    {{{1, 3, 132, 0, 34, -1}},      384, SC_ALGORITHM_EC}, /* ansiX9p384r1 */
101
    {{{1, 3, 132, 0, 35, -1}},      521, SC_ALGORITHM_EC}, /* ansiX9p521r1 */
102
    {{{1, 3, 36, 3, 3, 2, 8, 1, 1, 7, -1}},   256, SC_ALGORITHM_EC}, /* brainpoolP256r1 */
103
    {{{1, 3, 36, 3, 3, 2, 8, 1, 1, 11, -1}},  384, SC_ALGORITHM_EC}, /* brainpoolP384r1 */
104
    {{{1, 3, 36, 3, 3, 2, 8, 1, 1, 13, -1}},  512, SC_ALGORITHM_EC}, /* brainpoolP512r1 */
105
    {{{1, 3, 36, 3, 3, 2, 8, 1, 1, 8, -1}},   256, SC_ALGORITHM_EC}, /* brainpoolP256t1 */
106
    {{{1, 3, 36, 3, 3, 2, 8, 1, 1, 12, -1}},  384, SC_ALGORITHM_EC}, /* brainpoolP384t1 */
107
    {{{1, 3, 36, 3, 3, 2, 8, 1, 1, 14, -1}},  512, SC_ALGORITHM_EC}, /* brainpoolP512t1 */
108
    {{{-1}},          0, 0  } /* This entry must not be touched. */
109
};
110
111
#ifdef ENABLE_OPENSSL
112
static pgp_ec_curves_alt_t ec_curves_alt[] = {
113
    {{{1, 3, 6, 1, 4, 1, 3029, 1, 5, 1, -1}}, {{1, 3, 101, 110, -1}}, 255}, /* curve25519 CKK_EC_MONTGOMERY X25519 */
114
    {{{1, 3, 6, 1, 4, 1, 11591, 15, 1, -1}},  {{1, 3, 101, 112, -1}}, 255}, /* ed25519 CKK_EC_EDWARDS Ed25519 */
115
    {{{-1}},          {{-1}},     0  }  /* This entry must not be touched. */
116
};
117
118
#endif /* ENABLE_OPENSSL */
119
120
static pgp_ec_curves_t *ec_curves_openpgp = ec_curves_openpgp34 + 4;
121
122
struct sc_object_id curve25519_oid = {{1, 3, 6, 1, 4, 1, 3029, 1, 5, 1, -1}};
123
struct sc_object_id X25519_oid = {{1, 3, 101, 110, -1}}; /* need to check for RFC8410 version? */
124
125
/* Gnuk supports NIST, SECG and Curve25519 since version 1.2 */
126
static pgp_ec_curves_t ec_curves_gnuk[] = {
127
    {{{1, 2, 840, 10045, 3, 1, 7, -1}},   256, SC_ALGORITHM_EC},     /* ansiX9p256r1 */
128
    {{{1, 3, 132, 0, 10, -1}},      256, SC_ALGORITHM_EC},     /* secp256k1 */
129
    {{{1, 3, 6, 1, 4, 1, 3029, 1, 5, 1, -1}}, 255, SC_ALGORITHM_XEDDSA}, /* curve25519 for encryption => CKK_EC_MONTGOMERY */
130
    {{{1, 3, 101, 110, -1}},                  255, SC_ALGORITHM_XEDDSA}, /* RFC8410 OID equivalent to curve25519 */
131
    {{{1, 3, 6, 1, 4, 1, 11591, 15, 1, -1}},  255, SC_ALGORITHM_EDDSA},  /* ed25519 for signatures => CKK_EC_EDWARDS */
132
    {{{1, 3, 101, 112, -1}},      255, SC_ALGORITHM_EDDSA},  /* RFC8410 OID equivalent to ed25519 */
133
    {{{-1}},          0,   0}        /* This entry must not be touched. */
134
};
135
// clang-format on
136
137
/*
138
 * The OpenPGP card doesn't have a file system, instead everything
139
 * is stored in data objects that are accessed through GET/PUT.
140
 *
141
 * However, much inside OpenSC's pkcs15 implementation is based on
142
 * the assumption that we have a file system. So we fake one here.
143
 *
144
 * Selecting the MF causes us to select the OpenPGP AID.
145
 *
146
 * Everything else is mapped to "file" IDs.
147
 */
148
149
static int    pgp_get_card_features(sc_card_t *card);
150
static int    pgp_finish(sc_card_t *card);
151
static void   pgp_free_blobs(pgp_blob_t *);
152
153
static int    pgp_get_blob(sc_card_t *card, pgp_blob_t *blob,
154
         unsigned int id, pgp_blob_t **ret);
155
static pgp_blob_t *pgp_new_blob(sc_card_t *, pgp_blob_t *, unsigned int, sc_file_t *);
156
static void   pgp_free_blob(pgp_blob_t *);
157
static int    pgp_get_pubkey(sc_card_t *, unsigned int, u8 *, size_t);
158
static int    pgp_get_pubkey_pem(sc_card_t *, unsigned int, u8 *, size_t);
159
static int    pgp_enumerate_blob(sc_card_t *card, pgp_blob_t *blob);
160
161
// clang-format off
162
static pgp_do_info_t  pgp1x_objects[] = { /* OpenPGP card spec 1.1 */
163
  { 0x004f, SIMPLE,      READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
164
  { 0x005b, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
165
  { 0x005e, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  sc_get_data,        sc_put_data },
166
  { 0x0065, CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, sc_get_data,        NULL        },
167
  { 0x006e, CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, sc_get_data,        NULL        },
168
  { 0x0073, CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
169
  { 0x007a, CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, sc_get_data,        NULL        },
170
  { 0x0081, SIMPLE,      READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
171
  { 0x0082, SIMPLE,      READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
172
  { 0x0093, SIMPLE,      READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
173
  { 0x00c0, SIMPLE,      READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
174
  { 0x00c1, SIMPLE,      READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
175
  { 0x00c2, SIMPLE,      READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
176
  { 0x00c3, SIMPLE,      READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
177
  { 0x00c4, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
178
  { 0x00c5, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
179
  { 0x00c6, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
180
  { 0x00c7, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
181
  { 0x00c8, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
182
  { 0x00c9, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
183
  { 0x00ca, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
184
  { 0x00cb, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
185
  { 0x00cc, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
186
  { 0x00cd, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
187
  { 0x00ce, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
188
  { 0x00cf, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
189
  { 0x00d0, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
190
  { 0x00e0, CONSTRUCTED, READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
191
  { 0x00e1, CONSTRUCTED, READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
192
  { 0x00e2, CONSTRUCTED, READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
193
  { 0x0101, SIMPLE,      READ_ALWAYS | WRITE_PIN2,  sc_get_data,        sc_put_data },
194
  { 0x0102, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  sc_get_data,        sc_put_data },
195
  { 0x0103, SIMPLE,      READ_PIN2   | WRITE_PIN2,  sc_get_data,        sc_put_data },
196
  { 0x0104, SIMPLE,      READ_PIN3   | WRITE_PIN3,  sc_get_data,        sc_put_data },
197
  { 0x3f00, CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
198
  { 0x5f2d, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
199
  { 0x5f35, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
200
  { 0x5f50, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  sc_get_data,        sc_put_data },
201
  { 0x7f49, CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
202
  { DO_AUTH,     CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, pgp_get_pubkey,     NULL   },
203
  { DO_AUTH_SYM, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  pgp_get_pubkey_pem, NULL   },
204
  { DO_SIGN,     CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, pgp_get_pubkey,     NULL   },
205
  { DO_SIGN_SYM, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  pgp_get_pubkey_pem, NULL   },
206
  { DO_ENCR,     CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, pgp_get_pubkey,     NULL   },
207
  { DO_ENCR_SYM, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  pgp_get_pubkey_pem, NULL   },
208
  { 0, 0, 0, NULL, NULL },
209
};
210
211
static pgp_do_info_t  pgp34_objects[] = { /**** OpenPGP card spec 3.4 ****/
212
  { 0x00d9, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
213
  { 0x00da, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
214
  { 0x00db, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
215
  { 0x00dc, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
216
  { 0x00de, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
217
  { 0x00de, SIMPLE,      READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
218
  /* DO FA is CONSTRUCTED in spec; we treat it as SIMPLE for the time being */
219
  { 0x00fa, CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, sc_get_data,        NULL        },
220
  /* DO FB is CONSTRUCTED in spec; we treat it as SIMPLE for the time being */
221
  { 0x00fb, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
222
  /* DO FC is CONSTRUCTED in spec; we treat it as SIMPLE for the time being */
223
  { 0x00fc, SIMPLE,      READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
224
  /**** OpenPGP card spec 3.3 ****/
225
  { DO_KDF, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  sc_get_data,        sc_put_data },
226
  /**** OpenPGP card spec 3.0 - 3.2 ****/
227
  { 0x00d6, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
228
  { 0x00d7, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
229
  { 0x00d8, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
230
  /* DO 7F66 is CONSTRUCTED in spec; we treat it as SIMPLE: no need to parse TLV */
231
  { 0x7f66, SIMPLE,      READ_ALWAYS | WRITE_NEVER, NULL,               sc_put_data },
232
  /* DO 7F74 is CONSTRUCTED in spec; we treat it as SIMPLE for the time being */
233
  { 0x7f74, SIMPLE,      READ_ALWAYS | WRITE_NEVER, NULL,               sc_put_data },
234
  /**** OpenPGP card spec 2.1 & 2.2 ****/
235
  { 0x00d5, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
236
  /**** OpenPGP card spec 2.0 ****/
237
  { 0x004d, CONSTRUCTED, READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
238
  { 0x004f, SIMPLE,      READ_ALWAYS | WRITE_NEVER, sc_get_data,        NULL        },
239
  { 0x005b, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
240
  { 0x005e, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  sc_get_data,        sc_put_data },
241
  { 0x0065, CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, sc_get_data,        NULL        },
242
  { 0x006e, CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, sc_get_data,        NULL        },
243
  { 0x0073, CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
244
  { 0x007a, CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, sc_get_data,        NULL        },
245
  { 0x0081, SIMPLE,      READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
246
  { 0x0082, SIMPLE,      READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
247
  { 0x0093, SIMPLE,      READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
248
  { 0x00c0, SIMPLE,      READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
249
  { 0x00c1, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
250
  { 0x00c2, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
251
  { 0x00c3, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
252
  { 0x00c4, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  sc_get_data,        sc_put_data },
253
  { 0x00c5, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
254
  { 0x00c6, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
255
  { 0x00c7, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
256
  { 0x00c8, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
257
  { 0x00c9, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
258
  { 0x00ca, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
259
  { 0x00cb, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
260
  { 0x00cc, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
261
  { 0x00cd, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
262
  { 0x00ce, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
263
  { 0x00cf, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
264
  { 0x00d0, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
265
  { 0x00d1, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
266
  { 0x00d2, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
267
  { 0x00d3, SIMPLE,      READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
268
  { 0x00f4, CONSTRUCTED, READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
269
  { 0x0101, SIMPLE,      READ_ALWAYS | WRITE_PIN2,  sc_get_data,        sc_put_data },
270
  { 0x0102, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  sc_get_data,        sc_put_data },
271
  { 0x0103, SIMPLE,      READ_PIN2   | WRITE_PIN2,  sc_get_data,        sc_put_data },
272
  { 0x0104, SIMPLE,      READ_PIN3   | WRITE_PIN3,  sc_get_data,        sc_put_data },
273
  { 0x3f00, CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
274
  { 0x5f2d, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
275
  { 0x5f35, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  NULL,               sc_put_data },
276
  { 0x5f48, CONSTRUCTED, READ_NEVER  | WRITE_PIN3,  NULL,               sc_put_data },
277
  { 0x5f50, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  sc_get_data,        sc_put_data },
278
  { 0x5f52, SIMPLE,      READ_ALWAYS | WRITE_NEVER, sc_get_data,        NULL        },
279
  /* DO 7F21 is CONSTRUCTED in spec; we treat it as SIMPLE: no need to parse TLV */
280
  { DO_CERT, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  sc_get_data,       sc_put_data },
281
  { 0x7f48, CONSTRUCTED, READ_NEVER  | WRITE_NEVER, NULL,               NULL        },
282
  { 0x7f49, CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, NULL,               NULL        },
283
  { DO_AUTH,     CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, pgp_get_pubkey,     NULL   },
284
  /* The DOs 0xA401, 0xB601, 0xB801 are virtual DOs, they do not represent any real DO.
285
   * However, their R/W access condition may block the process of importing key in pkcs15init.
286
   * So we set their accesses condition as WRITE_PIN3 (writable). */
287
  { DO_AUTH_SYM, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  pgp_get_pubkey_pem, NULL   },
288
  { DO_SIGN,     CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, pgp_get_pubkey,     NULL   },
289
  { DO_SIGN_SYM, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  pgp_get_pubkey_pem, NULL   },
290
  { DO_ENCR,     CONSTRUCTED, READ_ALWAYS | WRITE_NEVER, pgp_get_pubkey,     NULL   },
291
  { DO_ENCR_SYM, SIMPLE,      READ_ALWAYS | WRITE_PIN3,  pgp_get_pubkey_pem, NULL   },
292
  { 0, 0, 0, NULL, NULL },
293
};
294
// clang-format on
295
296
static pgp_do_info_t  *pgp33_objects = pgp34_objects +  9;
297
static pgp_do_info_t  *pgp30_objects = pgp34_objects + 10;
298
static pgp_do_info_t  *pgp21_objects = pgp34_objects + 15;
299
static pgp_do_info_t  *pgp20_objects = pgp34_objects + 16;
300
301
302
/**
303
 * Internal: get OpenPGP application identifier from AID DO 004F
304
 */
305
static int
306
get_full_pgp_aid(sc_card_t *card, sc_file_t *file)
307
2.07k
{
308
2.07k
  int r = SC_ERROR_INVALID_ARGUMENTS;
309
310
2.07k
  if (file != NULL) {
311
    /* explicitly get the full aid */
312
2.07k
    r = sc_get_data(card, 0x004F, file->name, sizeof file->name);
313
2.07k
    file->namelen = MAX(r, 0);
314
2.07k
  }
315
316
2.07k
  return r;
317
2.07k
}
318
319
320
/**
321
 * ABI: check if card's ATR matches one of driver's
322
 * or if the OpenPGP application is present on the card.
323
 */
324
static int
325
pgp_match_card(sc_card_t *card)
326
4.15k
{
327
4.15k
  int i;
328
329
4.15k
  LOG_FUNC_CALLED(card->ctx);
330
331
4.15k
  i = _sc_match_atr(card, pgp_atrs, &card->type);
332
4.15k
  if (i >= 0) {
333
132
    card->name = pgp_atrs[i].name;
334
132
    LOG_FUNC_RETURN(card->ctx, 1);
335
132
  }
336
4.02k
  else {
337
4.02k
    sc_path_t partial_aid;
338
4.02k
    sc_file_t *file = NULL;
339
340
    /* select application "OpenPGP" */
341
4.02k
    sc_format_path("D276:0001:2401", &partial_aid);
342
4.02k
    partial_aid.type = SC_PATH_TYPE_DF_NAME;
343
    /* OpenPGP card only supports selection *with* requested FCI */
344
4.02k
    i = iso_ops->select_file(card, &partial_aid, &file);
345
4.02k
    if (SC_SUCCESS == i) {
346
981
      card->type = SC_CARD_TYPE_OPENPGP_BASE;
347
981
      card->name = default_cardname;
348
349
981
      if (file->namelen != 16)
350
980
        (void) get_full_pgp_aid(card, file);
351
981
      if (file->namelen == 16) {
352
15
        unsigned char major = BCD2UCHAR(file->name[6]);
353
354
15
        switch (major) {
355
3
          case 1:
356
3
            card->type = SC_CARD_TYPE_OPENPGP_V1;
357
3
            card->name = default_cardname_v1;
358
3
            break;
359
4
          case 2:
360
4
            card->type = SC_CARD_TYPE_OPENPGP_V2;
361
4
            card->name = default_cardname_v2;
362
4
            break;
363
4
          case 3:
364
4
            card->type = SC_CARD_TYPE_OPENPGP_V3;
365
4
            card->name = default_cardname_v3;
366
4
            break;
367
4
          default:
368
4
            break;
369
15
        }
370
15
      }
371
981
      sc_file_free(file);
372
981
      LOG_FUNC_RETURN(card->ctx, 1);
373
981
    }
374
4.02k
  }
375
3.04k
  LOG_FUNC_RETURN(card->ctx, 0);
376
3.04k
}
377
378
379
/* populate MF - add matching blobs listed in the pgp_objects table */
380
int populate_blobs_to_mf(sc_card_t *card, struct pgp_priv_data *priv)
381
1.08k
{
382
1.08k
  pgp_do_info_t *info;
383
384
1.08k
  if (priv->mf == NULL)
385
0
    return SC_ERROR_INTERNAL;
386
387
61.0k
  for (info = priv->pgp_objects; (info != NULL) && (info->id > 0); info++) {
388
59.9k
    if (((info->access & READ_MASK) != READ_NEVER) && (info->get_fn != NULL)) {
389
19.5k
      pgp_blob_t *child = NULL;
390
19.5k
      sc_file_t *file = sc_file_new();
391
392
19.5k
      child = pgp_new_blob(card, priv->mf, info->id, file);
393
394
      /* catch out of memory condition */
395
19.5k
      if (child == NULL) {
396
0
        sc_file_free(file);
397
0
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
398
0
      }
399
19.5k
    }
400
59.9k
  }
401
1.08k
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
402
1.08k
}
403
404
/**
405
 * ABI: initialize driver & allocate private data.
406
 */
407
static int
408
pgp_init(sc_card_t *card)
409
1.11k
{
410
1.11k
  struct pgp_priv_data *priv;
411
1.11k
  sc_path_t path;
412
1.11k
  sc_file_t *file = NULL;
413
1.11k
  int   r, i;
414
415
1.11k
  LOG_FUNC_CALLED(card->ctx);
416
417
1.11k
  priv = calloc (1, sizeof *priv);
418
1.11k
  if (!priv)
419
1.11k
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
420
1.11k
  card->drv_data = priv;
421
422
1.11k
  card->cla = 0x00;
423
424
  /* select application "OpenPGP" */
425
1.11k
  sc_format_path("D276:0001:2401", &path);
426
1.11k
  path.type = SC_PATH_TYPE_DF_NAME;
427
1.11k
  if ((r = iso_ops->select_file(card, &path, &file)) < 0) {
428
22
    sc_file_free(file);
429
22
    pgp_finish(card);
430
22
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD);
431
22
  }
432
433
  /* defensive programming check */
434
1.09k
  if (!file)   {
435
0
    pgp_finish(card);
436
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD);
437
0
  }
438
439
1.09k
  if (file->namelen != 16) {
440
    /* explicitly get the full aid */
441
1.09k
    r = get_full_pgp_aid(card, file);
442
1.09k
    if (r < 0) {
443
8
      sc_file_free(file);
444
8
      pgp_finish(card);
445
8
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD);
446
8
    }
447
1.09k
  }
448
449
  /* read information from AID */
450
1.08k
  if (file->namelen == 16) {
451
539
    static char card_name[SC_MAX_APDU_BUFFER_SIZE] = "OpenPGP card";
452
453
    /* OpenPGP card spec 1.1, 2.x & 3.x, section 4.2.1 & 4.1.2.1 */
454
539
    priv->bcd_version = bebytes2ushort(file->name + 6);
455
539
    card->version.fw_major = card->version.hw_major = BCD2UCHAR(file->name[6]);
456
539
    card->version.fw_minor = card->version.hw_minor = BCD2UCHAR(file->name[7]);
457
458
    /* for "standard" cards, include detailed card version & serial no. in card name */
459
539
    if (card->name == default_cardname_v1 ||
460
538
        card->name == default_cardname_v2 ||
461
537
        card->name == default_cardname_v3) {
462
3
      snprintf(card_name, sizeof(card_name),
463
3
         "OpenPGP card v%u.%u (%04X %08lX)",
464
3
         card->version.hw_major, card->version.hw_minor,
465
3
         bebytes2ushort(file->name + 8),
466
3
         bebytes2ulong(file->name + 10));
467
3
    }
468
536
    else if (card->name != NULL) {
469
      /* for other cards, append serial number to the card name */
470
536
      snprintf(card_name, sizeof(card_name),
471
536
         "%s (%04X %08lX)",
472
536
         card->name,
473
536
         bebytes2ushort(file->name + 8),
474
536
         bebytes2ulong(file->name + 10));
475
536
    }
476
539
    card->name = card_name;
477
478
    /* GPG compatibility: set card's serial number to manufacturer ID + serial number */
479
539
    memcpy(card->serialnr.value, file->name + 8, 6);
480
539
    card->serialnr.len = 6;
481
544
  } else {
482
    /* set detailed card version */
483
544
    switch (card->type) {
484
2
      case SC_CARD_TYPE_OPENPGP_V3:
485
2
        priv->bcd_version = OPENPGP_CARD_3_0;
486
2
        break;
487
74
      case SC_CARD_TYPE_OPENPGP_GNUK:
488
76
      case SC_CARD_TYPE_OPENPGP_V2:
489
76
        priv->bcd_version = OPENPGP_CARD_2_0;
490
76
        break;
491
466
      default:
492
466
        priv->bcd_version = OPENPGP_CARD_1_1;
493
466
        break;
494
544
    }
495
544
  }
496
497
  /* set pointer to correct list of card objects */
498
1.08k
  priv->pgp_objects = (priv->bcd_version < OPENPGP_CARD_2_0) ? pgp1x_objects
499
1.08k
        : (priv->bcd_version < OPENPGP_CARD_2_1) ? pgp20_objects
500
596
        : (priv->bcd_version < OPENPGP_CARD_3_0) ? pgp21_objects
501
515
        : (priv->bcd_version < OPENPGP_CARD_3_3) ? pgp30_objects
502
476
        : (priv->bcd_version < OPENPGP_CARD_3_4) ? pgp33_objects
503
472
        :              pgp34_objects;
504
505
  /* With gnuk, we use different curves */
506
1.08k
  if (card->type == SC_CARD_TYPE_OPENPGP_GNUK) {
507
129
    priv->ec_curves = ec_curves_gnuk;
508
954
  } else if (priv->bcd_version >= OPENPGP_CARD_3_4) {
509
427
    priv->ec_curves = ec_curves_openpgp34;
510
527
  } else {
511
527
    priv->ec_curves = ec_curves_openpgp;
512
527
  }
513
514
  /* change file path to MF for reuse in MF */
515
1.08k
  sc_format_path("3f00", &file->path);
516
517
  /* set up the root of our fake file tree */
518
  /* Transfers ownership of the file to the priv->mf structure */
519
1.08k
  priv->mf = pgp_new_blob(card, NULL, 0x3f00, file);
520
1.08k
  if (!priv->mf) {
521
0
    sc_file_free(file);
522
0
    pgp_finish(card);
523
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
524
0
  }
525
526
  /* select MF */
527
1.08k
  priv->current = priv->mf;
528
529
1.08k
  r = populate_blobs_to_mf(card, priv);
530
1.08k
  if (r < 0) {
531
0
    pgp_finish(card);
532
0
    LOG_FUNC_RETURN(card->ctx, r);
533
0
  }
534
535
  /* get card_features from ATR & DOs */
536
1.08k
  if (pgp_get_card_features(card)) {
537
94
    LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
538
94
  }
539
540
  /* if algorithm attributes can be changed,
541
   * add supported algorithms based on specification for pkcs15-init */
542
989
  if (priv->ext_caps & EXT_CAP_ALG_ATTR_CHANGEABLE) {
543
76
    unsigned long flags_rsa, flags_ecc, ext_flags;
544
76
    unsigned long flags_eddsa, flags_xeddsa;
545
546
    /* OpenPGP card spec 1.1 & 2.x, section 7.2.9 & 7.2.10 / v3.x section 7.2.11 & 7.2.12 */
547
76
    flags_rsa = SC_ALGORITHM_RSA_PAD_PKCS1|
548
76
          SC_ALGORITHM_RSA_HASH_NONE|
549
76
          SC_ALGORITHM_ONBOARD_KEY_GEN;
550
76
    flags_ecc = SC_ALGORITHM_ECDSA_RAW|
551
76
          SC_ALGORITHM_ECDH_CDH_RAW|
552
76
          SC_ALGORITHM_ECDSA_HASH_NONE|
553
76
          SC_ALGORITHM_ONBOARD_KEY_GEN;
554
76
    ext_flags = SC_ALGORITHM_EXT_EC_NAMEDCURVE;
555
556
76
    flags_eddsa = SC_ALGORITHM_EDDSA_RAW |
557
76
            SC_ALGORITHM_ONBOARD_KEY_GEN;
558
    /* xeddsa may allow signing at some time */
559
76
    flags_xeddsa = SC_ALGORITHM_ECDH_CDH_RAW |
560
76
             SC_ALGORITHM_ONBOARD_KEY_GEN;
561
562
76
    switch (card->type) {
563
1
      case SC_CARD_TYPE_OPENPGP_V3:
564
        /* RSA 1024 was removed for v3+ */
565
1
        _sc_card_add_rsa_alg(card, 4096, flags_rsa, 0);
566
1
        _sc_card_add_rsa_alg(card, 3072, flags_rsa, 0);
567
        /* fallthrough */
568
11
      case SC_CARD_TYPE_OPENPGP_GNUK:
569
11
        _sc_card_add_rsa_alg(card, 2048, flags_rsa, 0);
570
80
        for (i=0; priv->ec_curves[i].oid.value[0] >= 0; i++)
571
69
        {
572
69
          if (priv->ec_curves[i].key_type == SC_ALGORITHM_EC)
573
29
            _sc_card_add_ec_alg(card, priv->ec_curves[i].size,
574
29
                flags_ecc, ext_flags, &priv->ec_curves[i].oid);
575
40
          else if (priv->ec_curves[i].key_type == SC_ALGORITHM_EDDSA)
576
20
            _sc_card_add_eddsa_alg(card, priv->ec_curves[i].size,
577
20
                flags_eddsa, ext_flags, &priv->ec_curves[i].oid);
578
20
          else if (priv->ec_curves[i].key_type == SC_ALGORITHM_XEDDSA)
579
20
            _sc_card_add_xeddsa_alg(card, priv->ec_curves[i].size,
580
20
                flags_xeddsa, ext_flags, &priv->ec_curves[i].oid);
581
0
          else
582
0
            LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
583
69
        }
584
11
        break;
585
11
      case SC_CARD_TYPE_OPENPGP_V2:
586
65
      default:
587
65
        _sc_card_add_rsa_alg(card, 1024, flags_rsa, 0);
588
65
        _sc_card_add_rsa_alg(card, 2048, flags_rsa, 0);
589
65
        _sc_card_add_rsa_alg(card, 3072, flags_rsa, 0);
590
65
        _sc_card_add_rsa_alg(card, 4096, flags_rsa, 0);
591
65
        break;
592
76
    }
593
76
  }
594
595
989
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
596
989
}
597
598
599
/**
600
 * Internal: parse historic bytes to get card capabilities.
601
 */
602
static void
603
pgp_parse_hist_bytes(sc_card_t *card, u8 *ctlv, size_t ctlv_len)
604
306
{
605
306
  struct pgp_priv_data *priv = DRVDATA(card);
606
306
  const u8 *ptr;
607
608
  /* IS07816-4 hist bytes: 3rd function table */
609
306
  if ((ptr = sc_compacttlv_find_tag(ctlv, ctlv_len, 0x73, NULL)) != NULL) {
610
    /* bit 0x40 in byte 3 of TL 0x73 means "extended Le/Lc" */
611
164
    if (ptr[2] & 0x40) {
612
30
      card->caps |= SC_CARD_CAP_APDU_EXT;
613
30
      priv->ext_caps |= EXT_CAP_APDU_EXT;
614
30
    }
615
    /* bit 0x80 in byte 3 of TL 0x73 means "Command chaining" */
616
164
    if (ptr[2] & 0x80) {
617
147
      priv->ext_caps |= EXT_CAP_CHAINING;
618
147
    }
619
164
  }
620
621
306
  if ((priv->bcd_version >= OPENPGP_CARD_3_0) &&
622
86
      ((ptr = sc_compacttlv_find_tag(ctlv, ctlv_len, 0x31, NULL)) != NULL)) {
623
    // ToDo ...
624
52
  }
625
306
}
626
627
628
/**
629
 * Internal: parse an algorithm attributes DO
630
 **/
631
static int
632
pgp_parse_algo_attr_blob(sc_card_t *card, const pgp_blob_t *blob,
633
    sc_cardctl_openpgp_key_gen_store_info_t *key_info)
634
8.99k
{
635
8.99k
  struct pgp_priv_data *priv = DRVDATA(card);
636
8.99k
  struct sc_object_id oid;
637
8.99k
  unsigned int j, r;
638
639
8.99k
  LOG_FUNC_CALLED(card->ctx);
640
641
8.99k
  if (blob == NULL || blob->data == NULL || blob->len == 0 ||
642
8.19k
      blob->id < 0x00c1 || blob->id > 0x00c3 || key_info == NULL) {
643
799
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
644
799
  }
645
646
8.19k
  key_info->key_id = blob->id - 0x00c0; /* attribute algorithm blobs are C1 - C3 */
647
648
8.19k
  switch (blob->data[0]) {
649
1.99k
    case SC_OPENPGP_KEYALGO_RSA:
650
1.99k
      if (blob->len < 5) {
651
310
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
652
310
      }
653
654
1.68k
      key_info->algorithm = SC_OPENPGP_KEYALGO_RSA;
655
1.68k
      key_info->u.rsa.modulus_len = bebytes2ushort(blob->data + 1);
656
1.68k
      key_info->u.rsa.exponent_len = bebytes2ushort(blob->data + 3);
657
658
1.68k
      key_info->u.rsa.keyformat = (blob->len > 5)
659
1.68k
              ? blob->data[5]
660
1.68k
              : SC_OPENPGP_KEYFORMAT_RSA_STD;
661
1.68k
      break;
662
1.45k
    case SC_OPENPGP_KEYALGO_ECDH:
663
5.32k
    case SC_OPENPGP_KEYALGO_ECDSA:
664
5.83k
    case SC_OPENPGP_KEYALGO_EDDSA:
665
666
      /* SC_OPENPGP_KEYALGO_ECDH || SC_OPENPGP_KEYALGO_ECDSA || SC_OPENPGP_KEYALGO_EDDSA */
667
5.83k
      key_info->algorithm = blob->data[0];
668
669
      /* last byte is set to 0xFF if pubkey import is supported */
670
5.83k
      if (blob->data[blob->len-1] == SC_OPENPGP_KEYFORMAT_EC_STDPUB){
671
2.93k
        if (blob->len < 3)
672
349
          return SC_ERROR_INCORRECT_PARAMETERS;
673
2.58k
        key_info->u.ec.oidv_len = blob->len - 2;
674
2.58k
        key_info->u.ec.keyformat = SC_OPENPGP_KEYFORMAT_EC_STDPUB;
675
2.58k
      }
676
2.90k
      else {
677
        /* otherwise, last byte could be 00, so let's ignore it, as
678
         * it is not part of OID */
679
2.90k
        if (blob->len < 2)
680
197
          return SC_ERROR_INCORRECT_PARAMETERS;
681
2.70k
        if (blob->data[blob->len-1] == SC_OPENPGP_KEYFORMAT_EC_STD)
682
269
          key_info->u.ec.oidv_len = blob->len - 2;
683
2.43k
        else
684
2.43k
          key_info->u.ec.oidv_len = blob->len - 1;
685
2.70k
        key_info->u.ec.keyformat = SC_OPENPGP_KEYFORMAT_EC_STD;
686
2.70k
      }
687
688
      /* Create copy of oid from blob */
689
5.29k
      sc_init_oid(&oid);
690
5.29k
      r = sc_asn1_decode_object_id(&blob->data[1], key_info->u.ec.oidv_len, &oid);
691
692
      /* decoding failed, return sc_asn1_decode_object_id error code */
693
5.29k
      if (r > 0){
694
1.73k
        return r;
695
1.73k
      }
696
      /* compare with list of supported ec_curves */
697
29.1k
      for (j = 0; priv->ec_curves[j].oid.value[0] >= 0; j++) {
698
27.8k
        if (sc_compare_oid(&priv->ec_curves[j].oid, &oid)) {
699
2.25k
          sc_log(card->ctx, "Matched EC oid %s (%d)",
700
2.25k
            sc_dump_oid(&oid), j);
701
2.25k
          key_info->u.ec.oid = priv->ec_curves[j].oid;
702
2.25k
          key_info->u.ec.key_length = priv->ec_curves[j].size;
703
2.25k
          break;
704
2.25k
        }
705
27.8k
      }
706
      /* We did not match the OID */
707
3.55k
      if (priv->ec_curves[j].oid.value[0] < 0) {
708
1.29k
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
709
1.29k
      }
710
2.25k
      break;
711
2.25k
    default:
712
371
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
713
8.19k
  }
714
715
3.93k
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
716
3.93k
}
717
718
int
719
_pgp_handle_curve25519(sc_card_t *card,
720
    sc_cardctl_openpgp_key_gen_store_info_t *key_info, unsigned int do_num)
721
783
{
722
783
  if (!card || !key_info)
723
0
    return 0;
724
783
  if (!sc_compare_oid(&key_info->u.ec.oid, &curve25519_oid) &&
725
783
      !sc_compare_oid(&key_info->u.ec.oid, &X25519_oid))
726
783
    return 0;
727
728
  /* CKM_XEDDSA supports both Sign and Derive, but
729
  * OpenPGP card supports only derivation using these
730
  * keys as far as I know */
731
0
  _sc_card_add_xeddsa_alg(card, key_info->u.ec.key_length,
732
0
      SC_ALGORITHM_ECDH_CDH_RAW | SC_ALGORITHM_ONBOARD_KEY_GEN, 0, &key_info->u.ec.oid);
733
0
  sc_log(card->ctx, "DO %uX: Added XEDDSA algorithm (%d), mod_len = %zu",
734
0
      do_num, SC_ALGORITHM_XEDDSA, key_info->u.ec.key_length);
735
0
  return 1;
736
783
}
737
738
int
739
_pgp_add_algo(sc_card_t *card, sc_cardctl_openpgp_key_gen_store_info_t *key_info, unsigned int do_num)
740
3.93k
{
741
3.93k
  unsigned long flags = 0, ext_flags = 0;
742
743
3.93k
  if (!card || !key_info)
744
0
    return 0;
745
746
  /* [RFC 4880], [draft-ietf-openpgp-crypto-refresh] */
747
3.93k
  switch (key_info->algorithm) {
748
1.68k
  case SC_OPENPGP_KEYALGO_RSA:
749
    /* OpenPGP card spec 1.1 & 2.x, section 7.2.9 & 7.2.10 /
750
     * v3.x section 7.2.11 & 7.2.12 */
751
1.68k
    flags = SC_ALGORITHM_RSA_PAD_PKCS1 |
752
1.68k
      SC_ALGORITHM_RSA_HASH_NONE |
753
1.68k
      SC_ALGORITHM_ONBOARD_KEY_GEN; /* key gen on card */
754
755
1.68k
    _sc_card_add_rsa_alg(card, key_info->u.rsa.modulus_len, flags, 0);
756
1.68k
    sc_log(card->ctx, "DO %uX: Added RSA algorithm, mod_len = %zu",
757
1.68k
        do_num, key_info->u.rsa.modulus_len);
758
1.68k
    break;
759
466
  case SC_OPENPGP_KEYALGO_ECDH:
760
    /* The montgomery curve (curve25519) needs to go through
761
     * different paths, otherwise we handle it as a normal EC key */
762
466
    if (_pgp_handle_curve25519(card, key_info, do_num))
763
0
      break;
764
    /* fall through */
765
1.94k
  case SC_OPENPGP_KEYALGO_ECDSA:
766
    /* v3.0+: ECC [RFC 4880 & 6637] */
767
768
    /* Allow curve to be used by both ECDH and ECDSA.
769
     * pgp_init set these flags the same way */
770
1.94k
    flags = SC_ALGORITHM_ECDH_CDH_RAW;
771
1.94k
    flags |= SC_ALGORITHM_ECDSA_RAW;
772
1.94k
    flags |= SC_ALGORITHM_ECDSA_HASH_NONE;
773
1.94k
    flags |= SC_ALGORITHM_ONBOARD_KEY_GEN;
774
1.94k
    ext_flags = SC_ALGORITHM_EXT_EC_NAMEDCURVE;
775
776
1.94k
    _sc_card_add_ec_alg(card, key_info->u.ec.key_length, flags, ext_flags,
777
1.94k
      &key_info->u.ec.oid);
778
1.94k
    sc_log(card->ctx, "DO %uX: Added EC algorithm (%d), mod_len = %zu" ,
779
1.94k
      do_num, key_info->algorithm, key_info->u.ec.key_length);
780
1.94k
    break;
781
317
  case SC_OPENPGP_KEYALGO_EDDSA:
782
    /* EdDSA from draft-ietf-openpgp-rfc4880bis-08 */
783
    /* Handle Yubikey bug, that in DO FA curve25519 has EDDSA algo */
784
317
    if (_pgp_handle_curve25519(card, key_info, do_num))
785
0
      break;
786
317
    _sc_card_add_eddsa_alg(card, key_info->u.ec.key_length,
787
317
        SC_ALGORITHM_EDDSA_RAW | SC_ALGORITHM_ONBOARD_KEY_GEN, 0, &key_info->u.ec.oid);
788
789
317
    sc_log(card->ctx, "DO %uX: Added EDDSA algorithm (%d), mod_len = %zu" ,
790
317
      do_num, key_info->algorithm, key_info->u.ec.key_length);
791
317
    break;
792
0
  default:
793
0
    sc_log(card->ctx, "DO %uX: Unknown algorithm ID (%d)" ,
794
0
      do_num, key_info->algorithm);
795
    /* return "false" if we do not understand algo */
796
0
    return 0;
797
3.93k
  }
798
  /* return true */
799
3.93k
  return 1;
800
3.93k
}
801
802
#ifdef ENABLE_OPENSSL
803
static int
804
pgp_decode_kdf_do(sc_card_t *card, struct pgp_priv_data *priv)
805
90
{
806
90
  pgp_pin_kdf_info_t *pin_kdf_info = (pgp_pin_kdf_info_t *)calloc(1, sizeof(pgp_pin_kdf_info_t));
807
90
  int r = SC_ERROR_OUT_OF_MEMORY;
808
90
  pgp_blob_t *kdf_blob;
809
90
  const uint8_t *data;
810
90
  size_t data_len;
811
90
  size_t tag_len;
812
90
  const uint8_t *p;
813
90
  pgp_blob_t *blob;
814
815
90
  if (!pin_kdf_info) {
816
0
    return r;
817
0
  }
818
819
90
  r = SC_ERROR_INVALID_DATA;
820
90
  priv->pin_kdf_info = NULL;
821
90
  if ((pgp_get_blob(card, priv->mf, DO_KDF, &kdf_blob) != SC_SUCCESS) || (kdf_blob->len < 3)) {
822
67
    sc_log(card->ctx, "KDF DO does not exists or contains invalid data but card claims to support it");
823
67
    goto out;
824
67
  }
825
826
23
  data = kdf_blob->data;
827
23
  data_len = kdf_blob->len;
828
23
  p = sc_asn1_find_tag(card->ctx, data, data_len, 0x81, &tag_len);
829
23
  if (!p) {
830
4
    sc_log(card->ctx, "KDF algorithm byte not found");
831
4
    goto out;
832
4
  }
833
19
  if (tag_len != 1) {
834
3
    sc_log(card->ctx, "Unexpected KDF algorithm byte length, expects 1, got %zu", tag_len);
835
3
    goto out;
836
3
  }
837
838
16
  if (*p != 0x3) {
839
7
    if (*p == 0x0) {
840
1
      r = SC_SUCCESS;
841
1
      sc_log(card->ctx, "KDF derived PIN format disabled");
842
6
    } else {
843
6
      sc_log(card->ctx, "Unknown KDF algorithm ID %x", *p);
844
6
    }
845
7
    goto out;
846
7
  }
847
848
9
  p = sc_asn1_find_tag(card->ctx, data, data_len, 0x82, &tag_len);
849
9
  if (!p) {
850
1
    sc_log(card->ctx, "KDF hash algorithm byte not found");
851
1
    goto out;
852
1
  }
853
8
  if (tag_len != 1) {
854
2
    sc_log(card->ctx, "Unexpected KDF hash algorithm byte length, expects 1, got %zu", tag_len);
855
2
    goto out;
856
2
  }
857
858
6
  switch (*p) {
859
2
  case 0x08:
860
2
    pin_kdf_info->hash_algo = "SHA256";
861
2
    break;
862
3
  case 0x0A:
863
3
    pin_kdf_info->hash_algo = "SHA512";
864
3
    break;
865
1
  default:
866
1
    sc_log(card->ctx, "Unknown KDF hash algorithm ID %x", *p);
867
1
    goto out;
868
6
  }
869
870
5
  p = sc_asn1_find_tag(card->ctx, data, data_len, 0x83, &tag_len);
871
5
  if (!p) {
872
1
    sc_log(card->ctx, "KDF iteration count not found");
873
1
    goto out;
874
1
  }
875
4
  if (tag_len != 4) {
876
1
    sc_log(card->ctx, "Unexpected KDF iteration count length, expects 4, got %zu", tag_len);
877
1
    goto out;
878
1
  }
879
3
  pin_kdf_info->iterations = (uint32_t)bebytes2ulong(p);
880
881
3
  r = pgp_get_blob(card, kdf_blob, 0x84, &blob);
882
3
  if (r != SC_SUCCESS) {
883
1
    sc_log(card->ctx, "Failed to get salt bytes of user password");
884
1
    goto out;
885
1
  }
886
2
  pin_kdf_info->userpw_salt = blob;
887
888
2
  r = pgp_get_blob(card, kdf_blob, 0x86, &blob);
889
2
  if (r != SC_SUCCESS) {
890
1
    sc_log(card->ctx, "Failed to get salt bytes of admin password");
891
1
    goto out;
892
1
  }
893
1
  pin_kdf_info->adminpw_salt = blob;
894
895
1
  sc_log(card->ctx, "KDF derived PIN format enabled");
896
1
  priv->pin_kdf_info = pin_kdf_info;
897
1
  return r;
898
89
out:
899
89
  free(pin_kdf_info);
900
89
  return r;
901
2
}
902
#endif /* ENABLE_OPENSSL */
903
904
/**
905
 * Internal: get features of the card: capabilities, ...
906
 */
907
static int
908
pgp_get_card_features(sc_card_t *card)
909
1.08k
{
910
1.08k
  struct pgp_priv_data *priv = DRVDATA(card);
911
1.08k
  u8 *hist_bytes = card->reader->atr_info.hist_bytes;
912
1.08k
  size_t hist_bytes_len = card->reader->atr_info.hist_bytes_len;
913
1.08k
  unsigned int i;
914
1.08k
  pgp_blob_t *blob, *blob6e, *blob73, *blobfa;
915
1.08k
  int handled_algos = 0;
916
917
1.08k
  LOG_FUNC_CALLED(card->ctx);
918
919
  /* parse card capabilities from historical bytes in ATR */
920
1.08k
  if (hist_bytes_len > 0) {
921
    /* category indicator 0x00, 0x10 or 0x80 => compact TLV (ISO) */
922
281
    switch (hist_bytes[0]) {
923
144
      case 0x00:
924
144
        if (hist_bytes_len > 4) {
925
141
          pgp_parse_hist_bytes(card, hist_bytes+1, hist_bytes_len-4);
926
141
        }
927
144
        break;
928
122
      case 0x80:
929
122
        if (hist_bytes_len > 1) {
930
121
          pgp_parse_hist_bytes(card, hist_bytes+1, hist_bytes_len-1);
931
121
        }
932
122
        break;
933
5
      case 0x10:
934
5
        if (hist_bytes_len > 2) {
935
4
          pgp_parse_hist_bytes(card, hist_bytes+2, hist_bytes_len-2);
936
4
        }
937
5
        break;
938
281
    }
939
281
  }
940
941
  /* v1.1 does not support lifecycle via ACTIVATE & TERMINATE: set default */
942
1.08k
  priv->ext_caps &= ~EXT_CAP_LCS;
943
944
1.08k
  if (priv->bcd_version >= OPENPGP_CARD_2_0) {
945
    /* get card capabilities from "historical bytes" DO */
946
596
    if ((pgp_get_blob(card, priv->mf, 0x5f52, &blob) >= 0) &&
947
596
        (blob->data != NULL) && (blob->data[0] == 0x00)) {
948
949
43
      if (blob->len > 4) {
950
40
        pgp_parse_hist_bytes(card, blob->data+1, blob->len-4);
951
40
      }
952
953
      /* get card status from historical bytes status indicator */
954
43
      if ((blob->data[0] == 0x00) && (blob->len >= 4)) {
955
42
        priv->state = blob->data[blob->len-3];
956
        /* state not CARD_STATE_UNKNOWN => LCS supported */
957
42
        if (priv->state != CARD_STATE_UNKNOWN)
958
37
          priv->ext_caps |= EXT_CAP_LCS;
959
42
      }
960
43
    }
961
596
  }
962
963
1.08k
  if (priv->bcd_version >= OPENPGP_CARD_3_1) {
964
472
    card->caps |= SC_CARD_CAP_ISO7816_PIN_INFO;
965
472
  }
966
967
1.08k
  if (priv->bcd_version >= OPENPGP_CARD_3_4) {
968
    /* Parse supported algorithms from Algorithm Information DO
969
     * see OpenPGP card spec 3.4 section 4.4.3.11 */
970
471
    if (pgp_get_blob(card, priv->mf, 0x00fa, &blobfa) >= 0) {
971
471
      pgp_blob_t *child;
972
471
      pgp_enumerate_blob(card, blobfa);
973
      /* There will be multiple children with the same ID, but
974
       * different algos, so we need to iterate over all of them */
975
14.8k
      for (child = blobfa->files; child; child = child->next) {
976
14.3k
        if ((child->id < 0x00c1) || (child->id > 0x00c3))
977
5.36k
          continue;
978
8.97k
        sc_cardctl_openpgp_key_gen_store_info_t key_info;
979
8.97k
        if (pgp_parse_algo_attr_blob(card, child, &key_info) >= 0)
980
3.93k
          handled_algos += _pgp_add_algo(card, &key_info, 0x00fa);
981
8.97k
      }
982
471
    }
983
471
  }
984
985
  /* v1.1 & v2.x: special DOs are limited to 254 bytes */
986
1.08k
  priv->max_specialDO_size = 254;
987
988
1.08k
  if ((pgp_get_blob(card, priv->mf, 0x006e, &blob6e) >= 0) &&
989
1.08k
      (pgp_get_blob(card, blob6e, 0x0073, &blob73) >= 0)) {
990
991
    /* get "extended capabilities" DO */
992
205
    if ((pgp_get_blob(card, blob73, 0x00c0, &blob) >= 0) &&
993
167
        (blob->data != NULL) && (blob->len > 0)) {
994
165
      if ((blob->data[0] & 0x01) && (priv->bcd_version >= OPENPGP_CARD_3_3)) {
995
90
        priv->ext_caps |= EXT_CAP_KDF_DO;
996
90
      }
997
      /* v2.0+: bit 0x04 in first byte means "algorithm attributes changeable" */
998
165
      if ((blob->data[0] & 0x04) &&
999
85
          (priv->bcd_version >= OPENPGP_CARD_2_0))
1000
76
        priv->ext_caps |= EXT_CAP_ALG_ATTR_CHANGEABLE;
1001
      /* bit 0x08 in first byte means "support for private use DOs" */
1002
165
      if (blob->data[0] & 0x08)
1003
61
        priv->ext_caps |= EXT_CAP_PRIVATE_DO;
1004
      /* bit 0x10 in first byte means "support for CHV status byte changeable" */
1005
165
      if (blob->data[0] & 0x10)
1006
77
        priv->ext_caps |= EXT_CAP_C4_CHANGEABLE;
1007
      /* bit 0x20 in first byte means "support for Key Import" */
1008
165
      if (blob->data[0] & 0x20)
1009
91
        priv->ext_caps |= EXT_CAP_KEY_IMPORT;
1010
      /* bit 0x40 in first byte means "support for Get Challenge" */
1011
165
      if (blob->data[0] & 0x40) {
1012
126
        card->caps |= SC_CARD_CAP_RNG;
1013
126
        priv->ext_caps |= EXT_CAP_GET_CHALLENGE;
1014
126
      }
1015
      /* v2.0+: bit 0x80 in first byte means "support Secure Messaging" */
1016
165
      if ((blob->data[0] & 0x80) &&
1017
67
          (priv->bcd_version >= OPENPGP_CARD_2_0))
1018
60
        priv->ext_caps |= EXT_CAP_SM;
1019
1020
165
      if ((priv->bcd_version >= OPENPGP_CARD_2_0) && (blob->len >= 10)) {
1021
        /* v2.0+: max. challenge size is at bytes 3-4 */
1022
154
        priv->max_challenge_size = bebytes2ushort(blob->data + 2);
1023
        /* v2.0+: max. cert size it at bytes 5-6 */
1024
154
        priv->max_cert_size = bebytes2ushort(blob->data + 4);
1025
1026
154
        if (priv->bcd_version < OPENPGP_CARD_3_0) {
1027
          /* v2.x: SM algorithm is at byte 2: 0 == 3DES */
1028
25
          priv->sm_algo = blob->data[1];
1029
25
          if ((priv->sm_algo == SM_ALGO_NONE) && (priv->ext_caps & EXT_CAP_SM))
1030
7
            priv->sm_algo = SM_ALGO_3DES;
1031
1032
          /* v2.x: max. send/receive sizes are at bytes 7-8 resp. 9-10 */
1033
25
          card->max_send_size = bebytes2ushort(blob->data + 6);
1034
25
          card->max_recv_size = bebytes2ushort(blob->data + 8);
1035
25
        }
1036
129
        else {
1037
          /* v3.0+: SM algorithm is at byte 2: 0 == UNKNOWN */
1038
129
          priv->sm_algo = blob->data[1];
1039
129
          if ((priv->sm_algo == SM_ALGO_NONE) && (priv->ext_caps & EXT_CAP_SM))
1040
11
            priv->sm_algo = SM_ALGO_UNKNOWN;
1041
1042
          /* v3.0+: max. size of special DOs is at bytes 7-8 */
1043
129
          priv->max_specialDO_size = bebytes2ushort(blob->data + 6);
1044
129
        }
1045
154
        if (priv->bcd_version >= OPENPGP_CARD_3_3 && (blob->len >= 10)) {
1046
          /* v3.3+: MSE for key numbers 2(DEC) and 3(AUT) supported */
1047
127
          if (blob->data[9])
1048
79
            priv->ext_caps |= EXT_CAP_MSE;
1049
127
        }
1050
154
      }
1051
165
    }
1052
1053
    /* get max. PIN length from "CHV status bytes" DO */
1054
205
    if ((pgp_get_blob(card, blob73, 0x00c4, &blob) >= 0) &&
1055
63
      (blob->data != NULL) && (blob->len > 1)) {
1056
      /* 2nd byte in "CHV status bytes" DO means "max. PIN length" */
1057
2
      card->max_pin_len = blob->data[1];
1058
2
    }
1059
1060
205
    if (priv->bcd_version >= OPENPGP_CARD_3_0) {
1061
      /* v3.0+: get length info from "extended length information" DO */
1062
131
      if ((pgp_get_blob(card, blob6e, 0x7f66, &blob) >= 0) &&
1063
0
        (blob->data != NULL) && (blob->len >= 8)) {
1064
        /* kludge: treat as SIMPLE DO and use appropriate offsets */
1065
0
        card->max_send_size = bebytes2ushort(blob->data + 2);
1066
0
        card->max_recv_size = bebytes2ushort(blob->data + 6);
1067
0
      }
1068
131
    }
1069
1070
205
#ifdef ENABLE_OPENSSL
1071
205
    if (priv->ext_caps & EXT_CAP_KDF_DO) {
1072
90
      int r = pgp_decode_kdf_do(card, priv);
1073
90
      if (r != SC_SUCCESS) {
1074
88
        sc_log(card->ctx, "Failed to decode KDF DO: %s", sc_strerror(r));
1075
88
      }
1076
90
    }
1077
205
#endif /* ENABLE_OPENSSL */
1078
1079
    /* if we found at least one usable algo, let's skip other ways to find them */
1080
205
    if (handled_algos) {
1081
1
      sc_log(card->ctx, "Algo list populated from Algorithm Information DO");
1082
1
      LOG_FUNC_RETURN(card->ctx, handled_algos);
1083
1
    }
1084
1085
    /* get _current_ algorithms & key lengths from "algorithm attributes" DOs
1086
     *
1087
     * All available algorithms should be already provided by pgp_init. However, if another
1088
     * algorithm is found in the "algorithm attributes" DOs, it is supported by the card as
1089
     * well and therefore added
1090
     * see OpenPGP card spec 1.1 & 2.x section 4.3.3.6 / v3.x section 4.4.3.7 */
1091
816
    for (i = 0x00c1; i <= 0x00c3; i++) {
1092
612
      sc_cardctl_openpgp_key_gen_store_info_t key_info;
1093
1094
612
      sc_log(card->ctx, "Parsing algorithm attributes DO %uX" , i);
1095
1096
      /* OpenPGP card spec 1.1 & 2.x section 4.3.3.6 / v3.x section 4.4.3.7 */
1097
612
      if ((pgp_get_blob(card, blob73, i, &blob) >= 0) &&
1098
18
          (pgp_parse_algo_attr_blob(card, blob, &key_info) >= 0)) {
1099
7
        if (!_pgp_add_algo(card, &key_info, i))
1100
7
          LOG_TEST_RET(card->ctx, SC_ERROR_INTERNAL, "Cannot add algorithm");
1101
7
      }
1102
612
    }
1103
1104
204
  }
1105
1106
1.08k
  LOG_FUNC_RETURN(card->ctx, handled_algos);
1107
1.08k
}
1108
1109
1110
/**
1111
 * ABI: terminate driver & free private data.
1112
 */
1113
static int
1114
pgp_finish(sc_card_t *card)
1115
1.11k
{
1116
1.11k
  if (card != NULL) {
1117
1.11k
    struct pgp_priv_data *priv = DRVDATA(card);
1118
1119
1.11k
    if (priv != NULL) {
1120
      /* delete fake file hierarchy */
1121
1.11k
      pgp_free_blobs(priv->mf);
1122
1123
      /* delete kdf do related data if exists */
1124
1.11k
      free(priv->pin_kdf_info);
1125
1126
      /* delete private data */
1127
1.11k
      free(priv);
1128
1.11k
    }
1129
1.11k
    card->drv_data = NULL;
1130
1.11k
  }
1131
1.11k
  return SC_SUCCESS;
1132
1.11k
}
1133
1134
1135
/**
1136
 * Internal: fill a blob's data.
1137
 */
1138
static int
1139
pgp_set_blob(pgp_blob_t *blob, const u8 *data, size_t len)
1140
1.64M
{
1141
1.64M
  if (blob->data)
1142
7
    free(blob->data);
1143
1.64M
  blob->data = NULL;
1144
1.64M
  blob->len    = 0;
1145
1.64M
  blob->status = 0;
1146
1147
1.64M
  if (len > 0) {
1148
383k
    void *tmp = calloc(1, len);
1149
1150
383k
    if (tmp == NULL)
1151
0
      return SC_ERROR_OUT_OF_MEMORY;
1152
1153
383k
    blob->data = tmp;
1154
383k
    blob->len  = (unsigned int)len;
1155
383k
    if (data != NULL)
1156
383k
      memcpy(blob->data, data, len);
1157
383k
  }
1158
1159
1.64M
  if (blob->file)
1160
1.64M
    blob->file->size = len;
1161
1162
1.64M
  return SC_SUCCESS;
1163
1.64M
}
1164
1165
1166
/**
1167
 * Internal: implement Access Control List for emulated file.
1168
 * The Access Control is derived from the DO access permission.
1169
 **/
1170
static void
1171
pgp_attach_acl(sc_card_t *card, sc_file_t *file, pgp_do_info_t *info)
1172
905k
{
1173
905k
  unsigned int method = SC_AC_NONE;
1174
905k
  unsigned long key_ref = SC_AC_KEY_REF_NONE;
1175
1176
  /* Write access */
1177
905k
  switch (info->access & WRITE_MASK) {
1178
819k
  case WRITE_NEVER:
1179
819k
    method = SC_AC_NEVER;
1180
819k
    break;
1181
0
  case WRITE_PIN1:
1182
0
    method = SC_AC_CHV;
1183
0
    key_ref = 0x01;
1184
0
    break;
1185
2.16k
  case WRITE_PIN2:
1186
2.16k
    method = SC_AC_CHV;
1187
2.16k
    key_ref = 0x02;
1188
2.16k
    break;
1189
83.5k
  case WRITE_PIN3:
1190
83.5k
    method = SC_AC_CHV;
1191
83.5k
    key_ref = 0x03;
1192
83.5k
    break;
1193
905k
  }
1194
1195
905k
  if (method != SC_AC_NONE || key_ref != SC_AC_KEY_REF_NONE) {
1196
905k
    sc_file_add_acl_entry(file, SC_AC_OP_WRITE, method, key_ref);
1197
905k
    sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, method, key_ref);
1198
905k
    sc_file_add_acl_entry(file, SC_AC_OP_DELETE, method, key_ref);
1199
905k
    sc_file_add_acl_entry(file, SC_AC_OP_CREATE, method, key_ref);
1200
905k
  }
1201
0
  else {
1202
    /* When SC_AC_OP_DELETE is absent, we need to provide
1203
     * SC_AC_OP_DELETE_SELF for sc_pkcs15init_delete_by_path() */
1204
0
    sc_file_add_acl_entry(file, SC_AC_OP_DELETE_SELF, method, key_ref);
1205
0
  }
1206
1207
905k
  method = SC_AC_NONE;
1208
905k
  key_ref = SC_AC_KEY_REF_NONE;
1209
  /* Read access */
1210
905k
  switch (info->access & READ_MASK) {
1211
64.8k
  case READ_NEVER:
1212
64.8k
    method = SC_AC_NEVER;
1213
64.8k
    break;
1214
0
  case READ_PIN1:
1215
0
    method = SC_AC_CHV;
1216
0
    key_ref = 0x01;
1217
0
    break;
1218
1.08k
  case READ_PIN2:
1219
1.08k
    method = SC_AC_CHV;
1220
1.08k
    key_ref = 0x02;
1221
1.08k
    break;
1222
1.08k
  case READ_PIN3:
1223
1.08k
    method = SC_AC_CHV;
1224
1.08k
    key_ref = 0x03;
1225
1.08k
    break;
1226
905k
  }
1227
1228
905k
  if (method != SC_AC_NONE || key_ref != SC_AC_KEY_REF_NONE) {
1229
67.0k
    sc_file_add_acl_entry(file, SC_AC_OP_READ, method, key_ref);
1230
67.0k
  }
1231
905k
}
1232
1233
1234
/**
1235
 * Internal: append a blob to the list of children of a given parent blob.
1236
 */
1237
static pgp_blob_t *
1238
pgp_new_blob(sc_card_t *card, pgp_blob_t *parent, unsigned int file_id,
1239
    sc_file_t *file)
1240
1.56M
{
1241
1.56M
  pgp_blob_t *blob = NULL;
1242
1243
1.56M
  if (file == NULL)
1244
0
    return NULL;
1245
1246
1.56M
  if ((blob = calloc(1, sizeof(pgp_blob_t))) != NULL) {
1247
1.56M
    struct pgp_priv_data *priv = DRVDATA(card);
1248
1.56M
    pgp_do_info_t *info;
1249
1250
1.56M
    blob->file = file;
1251
1252
1.56M
    blob->file->type         = SC_FILE_TYPE_WORKING_EF; /* default */
1253
1.56M
    blob->file->ef_structure = SC_FILE_EF_TRANSPARENT;
1254
1.56M
    blob->file->id           = file_id;
1255
1256
1.56M
    blob->id     = file_id;
1257
1.56M
    blob->parent = parent;
1258
1259
1.56M
    if (parent != NULL) {
1260
1.56M
      pgp_blob_t **p;
1261
1262
      /* set file's path = parent's path + file's id */
1263
1.56M
      blob->file->path = parent->file->path;
1264
1.56M
      sc_append_file_id(&blob->file->path, file_id);
1265
1266
      /* append blob to list of parent's children */
1267
9.48M
      for (p = &parent->files; *p != NULL; p = &(*p)->next)
1268
7.91M
        ;
1269
1.56M
      *p = blob;
1270
1.56M
    }
1271
1.08k
    else {
1272
1.08k
      char path[10] = "0000"; /* long enough */
1273
1274
      /* no parent: set file's path = file's id */
1275
1.08k
      if (4 != snprintf(path, sizeof(path), "%04X", file_id & 0xFFFF)) {
1276
0
        free(blob);
1277
0
        return NULL;
1278
0
      }
1279
1280
1.08k
      sc_format_path(path, &blob->file->path);
1281
1.08k
    }
1282
1283
    /* find matching DO info: set file type depending on it */
1284
39.1M
    for (info = priv->pgp_objects; (info != NULL) && (info->id > 0); info++) {
1285
38.4M
      if (info->id == file_id) {
1286
905k
        blob->info = info;
1287
905k
        blob->file->type = blob->info->type;
1288
905k
        pgp_attach_acl(card, blob->file, info);
1289
905k
        break;
1290
905k
      }
1291
38.4M
    }
1292
1.56M
  }
1293
1294
1.56M
  return blob;
1295
1.56M
}
1296
1297
1298
/**
1299
 * Internal: free a blob including its content.
1300
 */
1301
static void
1302
pgp_free_blob(pgp_blob_t *blob)
1303
1.56M
{
1304
1.56M
  if (blob) {
1305
1.56M
    if (blob->parent) {
1306
1.56M
      pgp_blob_t **p;
1307
1308
      /* remove blob from list of parent's children */
1309
1.56M
      for (p = &blob->parent->files; *p != NULL && *p != blob; p = &(*p)->next)
1310
0
        ;
1311
1.56M
      if (*p == blob)
1312
1.56M
        *p = blob->next;
1313
1.56M
    }
1314
1315
1.56M
    sc_file_free(blob->file);
1316
1.56M
    if (blob->data)
1317
383k
      free(blob->data);
1318
1.56M
    free(blob);
1319
1.56M
  }
1320
1.56M
}
1321
1322
1323
/**
1324
 * Internal: iterate through the blob tree, calling pgp_free_blob for each blob.
1325
 */
1326
static void
1327
pgp_free_blobs(pgp_blob_t *blob)
1328
1.56M
{
1329
1.56M
  if (blob) {
1330
1.56M
    pgp_blob_t *child = blob->files;
1331
1332
3.13M
    while (child != NULL) {
1333
1.56M
      pgp_blob_t *next = child->next;
1334
1335
1.56M
      pgp_free_blobs(child);
1336
1.56M
      child = next;
1337
1.56M
    }
1338
1.56M
    pgp_free_blob(blob);
1339
1.56M
  }
1340
1.56M
}
1341
1342
1343
/**
1344
 * Internal: read a blob's contents from card.
1345
 */
1346
static int
1347
pgp_read_blob(sc_card_t *card, pgp_blob_t *blob)
1348
1.48M
{
1349
1.48M
  struct pgp_priv_data *priv = DRVDATA(card);
1350
1351
1.48M
  if (blob->data != NULL)
1352
289k
    return SC_SUCCESS;
1353
1.19M
  if (blob->info == NULL)
1354
433k
    return blob->status;
1355
1356
759k
  if (blob->info->get_fn) { /* readable, top-level DO */
1357
758k
    u8  buffer[MAX_OPENPGP_DO_SIZE];
1358
758k
    size_t  buf_len = sizeof(buffer);
1359
758k
    int r = SC_SUCCESS;
1360
1361
    /* buffer length for certificate */
1362
758k
    if (blob->id == DO_CERT && priv->max_cert_size > 0) {
1363
77
      buf_len = MIN(priv->max_cert_size, sizeof(buffer));
1364
77
    }
1365
1366
    /* buffer length for Gnuk pubkey */
1367
758k
    if (card->type == SC_CARD_TYPE_OPENPGP_GNUK &&
1368
5.28k
        (blob->id == DO_AUTH ||
1369
5.22k
         blob->id == DO_SIGN ||
1370
5.16k
         blob->id == DO_ENCR ||
1371
5.10k
         blob->id == DO_AUTH_SYM ||
1372
5.10k
         blob->id == DO_SIGN_SYM ||
1373
5.10k
         blob->id == DO_ENCR_SYM)) {
1374
190
      buf_len = MIN(MAXLEN_RESP_PUBKEY_GNUK, sizeof(buffer));
1375
190
    }
1376
1377
758k
    r = blob->info->get_fn(card, blob->id, buffer, buf_len);
1378
1379
758k
    if (r < 0) { /* an error occurred */
1380
662k
      blob->status = r;
1381
662k
      return r;
1382
662k
    }
1383
1384
96.1k
    return pgp_set_blob(blob, buffer, r);
1385
758k
  }
1386
338
  else {   /* un-readable DO or part of a constructed DO */
1387
338
    return SC_SUCCESS;
1388
338
  }
1389
759k
}
1390
1391
1392
/**
1393
 * Internal: enumerate contents of a data blob.
1394
 * The OpenPGP card has a TLV encoding according ASN.1 BER-encoding rules.
1395
 */
1396
static int
1397
pgp_enumerate_blob(sc_card_t *card, pgp_blob_t *blob)
1398
1.48M
{
1399
1.48M
  const u8  *in;
1400
1.48M
  int   r;
1401
1.48M
  sc_file_t *file = NULL;
1402
1403
1.48M
  if (blob->files != NULL)
1404
5.96k
    return SC_SUCCESS;
1405
1406
1.47M
  if ((r = pgp_read_blob(card, blob)) < 0)
1407
661k
    return r;
1408
1409
818k
  in = blob->data;
1410
1411
2.64M
  while ((int) blob->len > (in - blob->data)) {
1412
2.12M
    unsigned int  cla, tag, tmptag;
1413
2.12M
    size_t    len;
1414
2.12M
    const u8  *data = in;
1415
2.12M
    pgp_blob_t  *new;
1416
1417
2.12M
    if (!in)
1418
0
      return SC_ERROR_OBJECT_NOT_VALID;
1419
1420
2.12M
    r = sc_asn1_read_tag(&data, blob->len - (in - blob->data),
1421
2.12M
          &cla, &tag, &len);
1422
2.12M
    if (r == SC_ERROR_INVALID_ASN1_OBJECT) {
1423
49.8k
      sc_log(card->ctx, "Invalid ASN.1 object");
1424
49.8k
      return SC_ERROR_OBJECT_NOT_VALID;
1425
49.8k
    }
1426
    /* Check for unknown error, or empty data */
1427
2.07M
    if (((r < 0) && (r != SC_ERROR_ASN1_END_OF_CONTENTS)) ||
1428
2.07M
        (data == NULL)) {
1429
149k
      sc_log(card->ctx, "Unexpected end of contents");
1430
149k
      return SC_ERROR_OBJECT_NOT_VALID;
1431
149k
    }
1432
1433
    /* undo ASN1's split of tag & class */
1434
1.98M
    for (tmptag = tag; tmptag > 0x0FF; tmptag >>= 8) {
1435
65.6k
      cla <<= 8;
1436
65.6k
    }
1437
1.92M
    tag |= cla;
1438
    /* Check for length mismatch */
1439
1.92M
    if ((r == SC_ERROR_ASN1_END_OF_CONTENTS) ||
1440
1.82M
        (data + len > blob->data + blob->len)) {
1441
      // Check if it is not known Yubikey 5 issue
1442
101k
      if ((tag != blob->id) || (tag != 0xfa)) {
1443
101k
        sc_log(card->ctx, "Unexpected end of contents");
1444
101k
        return SC_ERROR_OBJECT_NOT_VALID;
1445
101k
      }
1446
101k
    }
1447
1448
    /* Awful hack for composite DOs that have
1449
     * a TLV with the DO's id encompassing the
1450
     * entire blob. Example: Yubikey Neo */
1451
1.82M
    if (tag == blob->id) {
1452
273k
      in = data;
1453
273k
      continue;
1454
273k
    }
1455
1456
    /* create fake file system hierarchy by
1457
     * using constructed DOs as DF */
1458
1.54M
    file = sc_file_new();
1459
1.54M
    if ((new = pgp_new_blob(card, blob, tag, file)) == NULL) {
1460
0
      sc_file_free(file);
1461
0
      return SC_ERROR_OUT_OF_MEMORY;
1462
0
    }
1463
1.54M
    if (pgp_set_blob(new, data, len) != SC_SUCCESS) {
1464
0
      sc_file_free(file);
1465
0
      return SC_ERROR_OUT_OF_MEMORY;
1466
0
    }
1467
1.54M
    in = data + len;
1468
1.54M
  }
1469
1470
517k
  return SC_SUCCESS;
1471
818k
}
1472
1473
1474
/**
1475
 * Internal: find a blob by ID below a given parent, filling its contents when necessary.
1476
 */
1477
static int
1478
pgp_get_blob(sc_card_t *card, pgp_blob_t *blob, unsigned int id,
1479
    pgp_blob_t **ret)
1480
1.48M
{
1481
1.48M
  pgp_blob_t    *child;
1482
1.48M
  int     r;
1483
1484
1.48M
  if ((r = pgp_enumerate_blob(card, blob)) < 0)
1485
961k
    return r;
1486
1487
720k
  for (child = blob->files; child; child = child->next) {
1488
200k
    if (child->id == id) {
1489
2.89k
      (void) pgp_read_blob(card, child);
1490
2.89k
      *ret = child;
1491
2.89k
      return SC_SUCCESS;
1492
2.89k
    }
1493
200k
  }
1494
1495
  /* This part is for "NOT FOUND" cases */
1496
1497
  /* Special case:
1498
   * Gnuk does not have default value for children of DO 65 (DOs 5B, 5F2D, 5F35)
1499
   * So, if these blob was not found, we create it. */
1500
519k
  if (blob->id == DO_CARDHOLDER && (id == DO_NAME || id == DO_LANG_PREF || id == DO_SEX)) {
1501
4
    sc_log(card->ctx, "Create blob %X under %X", id, blob->id);
1502
4
    child = pgp_new_blob(card, blob, id, sc_file_new());
1503
4
    if (child) {
1504
4
      pgp_set_blob(child, NULL, 0);
1505
4
      *ret = child;
1506
4
      return SC_SUCCESS;
1507
4
    }
1508
0
    else
1509
0
      sc_log(card->ctx,
1510
4
             "Not enough memory to create blob for DO %X",
1511
4
             id);
1512
4
  }
1513
1514
519k
  return SC_ERROR_FILE_NOT_FOUND;
1515
519k
}
1516
1517
1518
/**
1519
 * Internal: search recursively for a blob by ID below a given root.
1520
 */
1521
static int
1522
pgp_seek_blob(sc_card_t *card, pgp_blob_t *root, unsigned int id,
1523
    pgp_blob_t **ret)
1524
1.47M
{
1525
1.47M
  pgp_blob_t  *child;
1526
1.47M
  int     r;
1527
1528
1.47M
  if ((r = pgp_get_blob(card, root, id, ret)) == 0)
1529
    /* the sought blob is right under root */
1530
188
    return r;
1531
1532
  /* not found, seek deeper */
1533
3.04M
  for (child = root->files; child; child = child->next) {
1534
    /* The DO of SIMPLE type or the DO holding certificate
1535
     * does not contain children */
1536
1.56M
    if ((child->info && child->info->type == SIMPLE) || child->id == DO_CERT)
1537
84.7k
      continue;
1538
1.47M
    r = pgp_seek_blob(card, child, id, ret);
1539
1.47M
    if (r == 0)
1540
219
      return r;
1541
1.47M
  }
1542
1543
1.47M
  return SC_ERROR_FILE_NOT_FOUND;
1544
1.47M
}
1545
1546
1547
/**
1548
 * Internal: find a blob by tag - pgp_seek_blob with optimizations.
1549
 */
1550
static pgp_blob_t *
1551
pgp_find_blob(sc_card_t *card, unsigned int tag)
1552
1.08k
{
1553
1.08k
  struct pgp_priv_data *priv = DRVDATA(card);
1554
1.08k
  pgp_blob_t *blob = NULL;
1555
1.08k
  int r;
1556
1557
  /* check if current selected blob is which we want to test */
1558
1.08k
  if (priv->current->id == tag) {
1559
3
    return priv->current;
1560
3
  }
1561
  /* look for the blob representing the DO */
1562
1.08k
  r = pgp_seek_blob(card, priv->mf, tag, &blob);
1563
1.08k
  if (r < 0) {
1564
892
    sc_log(card->ctx, "Failed to seek the blob representing the tag %04X. Error %d.", tag, r);
1565
892
    return NULL;
1566
892
  }
1567
188
  return blob;
1568
1.08k
}
1569
1570
1571
/**
1572
 * Internal: get info for a specific tag.
1573
 */
1574
static pgp_do_info_t *
1575
pgp_get_info_by_tag(sc_card_t *card, unsigned int tag)
1576
892
{
1577
892
  struct pgp_priv_data *priv = DRVDATA(card);
1578
892
  pgp_do_info_t *info;
1579
1580
48.1k
  for (info = priv->pgp_objects; (info != NULL) && (info->id > 0); info++)
1581
47.3k
    if (tag == info->id)
1582
32
      return info;
1583
1584
860
  return NULL;
1585
892
}
1586
1587
1588
/**
1589
 * Internal: strip out the parts of PKCS15 file layout in the path.
1590
 * Get the reduced version which is understood by the OpenPGP card driver.
1591
 * Return the index whose preceding part will be ignored.
1592
 **/
1593
static unsigned int
1594
pgp_strip_path(sc_card_t *card, const sc_path_t *path)
1595
0
{
1596
0
  unsigned int start_point = 0;
1597
  /* start_point will move through the path string */
1598
0
  if (path->len == 0)
1599
0
    return 0;
1600
1601
  /* ignore 3F00 (MF) at the beginning */
1602
0
  start_point = (memcmp(path->value, "\x3f\x00", 2) == 0) ? 2 : 0;
1603
  /* strip path of PKCS15-App DF (5015) */
1604
0
  start_point += (memcmp(path->value + start_point, "\x50\x15", 2) == 0) ? 2 : 0;
1605
0
  return start_point;
1606
0
}
1607
1608
1609
/**
1610
 * ABI: ISO 7816-4 SELECT FILE - search given file & make it the currently selected one.
1611
 */
1612
static int
1613
pgp_select_file(sc_card_t *card, const sc_path_t *path, sc_file_t **ret)
1614
0
{
1615
0
  struct pgp_priv_data *priv = DRVDATA(card);
1616
0
  pgp_blob_t  *blob;
1617
0
  unsigned int  path_start = 0;
1618
0
  unsigned int  n;
1619
0
  sc_path_t dummy_path;
1620
1621
0
  LOG_FUNC_CALLED(card->ctx);
1622
1623
0
  if (path->type == SC_PATH_TYPE_DF_NAME)
1624
0
    LOG_FUNC_RETURN(card->ctx, iso_ops->select_file(card, path, ret));
1625
1626
0
  if (path->len < 2 || (path->len & 1))
1627
0
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
1628
0
        "invalid path length");
1629
1630
0
  if (path->type == SC_PATH_TYPE_FILE_ID && path->len != 2)
1631
0
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
1632
0
        "invalid path type");
1633
1634
  /* Due to pkcs15init implementation, sometimes a file at path "11001101"
1635
   * need to be written (one use case is when importing key&cert from p12 file).
1636
   * This file does not exist in OpenPGP but pkcs15 requires that
1637
   * writing this file must be successful.
1638
   * So, we pretend that selecting & writing this file is successful.
1639
   * The "11001101"is defined in sc_pkcs15emu_get_df() function, pkcs15-sync.c file. */
1640
0
  sc_format_path("11001101", &dummy_path);
1641
0
  if (sc_compare_path(path, &dummy_path)) {
1642
0
    if (ret != NULL) {
1643
0
      *ret = sc_file_new();
1644
      /* One use case of this dummy file is after writing certificate in pkcs15init.
1645
       * So we set its size to be the same as max certificate size the card supports. */
1646
0
      (*ret)->size = priv->max_cert_size;
1647
0
    }
1648
0
    LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
1649
0
  }
1650
1651
  /* ignore explicitly mentioned MF at the path's beginning */
1652
0
  path_start = pgp_strip_path(card, path);
1653
1654
  /* starting with the MF ... */
1655
0
  blob = priv->mf;
1656
  /* ... recurse through the tree following the path */
1657
0
  for (n = path_start; n < path->len; n += 2) {
1658
0
    unsigned int  id = bebytes2ushort(path->value + n);
1659
0
    int   r = pgp_get_blob(card, blob, id, &blob);
1660
1661
    /* This file ID is referred when importing key&certificate via pkcs15init, like above.
1662
     * We pretend to successfully find this inexistent file. */
1663
0
    if (id == 0x4402 || id == 0x5f48) {
1664
0
      if (ret == NULL)
1665
        /* No need to return file */
1666
0
        LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
1667
1668
      /* Else, need to return file */
1669
0
      *ret = sc_file_new();
1670
0
      (*ret)->size = priv->max_cert_size;
1671
0
      LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
1672
0
    }
1673
1674
0
    if (r < 0) { /* failure */
1675
0
      LOG_FUNC_RETURN(card->ctx, r);
1676
0
    }
1677
0
  }
1678
1679
  /* success: select file = set "current" pointer to blob found */
1680
0
  priv->current = blob;
1681
1682
0
  if (ret)
1683
0
    sc_file_dup(ret, blob->file);
1684
1685
0
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
1686
0
}
1687
1688
1689
/**
1690
 * ABI: ISO 7816-4 LIST FILES - enumerate all files in current DF.
1691
 */
1692
static int
1693
pgp_list_files(sc_card_t *card, u8 *buf, size_t buflen)
1694
1.08k
{
1695
1.08k
  struct pgp_priv_data *priv = DRVDATA(card);
1696
1.08k
  pgp_blob_t  *blob;
1697
1.08k
  unsigned int  k;
1698
1.08k
  int   r;
1699
1700
1.08k
  LOG_FUNC_CALLED(card->ctx);
1701
1702
  /* jump to selected file */
1703
1.08k
  blob = priv->current;
1704
1705
1.08k
  if (blob->file->type != SC_FILE_TYPE_DF)
1706
1.08k
    LOG_TEST_RET(card->ctx, SC_ERROR_OBJECT_NOT_VALID,
1707
1.08k
        "invalid file type");
1708
1709
1.08k
  if ((r = pgp_enumerate_blob(card, blob)) < 0)
1710
1.08k
    LOG_FUNC_RETURN(card->ctx, r);
1711
1712
20.6k
  for (k = 0, blob = blob->files; blob != NULL; blob = blob->next) {
1713
19.5k
    if (blob->info != NULL && (blob->info->access & READ_MASK) != READ_NEVER) {
1714
19.5k
      if (k + 2 > buflen)
1715
19.5k
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_BUFFER_TOO_SMALL);
1716
1717
19.5k
      ushort2bebytes(buf + k, blob->id);
1718
19.5k
      k += 2;
1719
19.5k
    }
1720
19.5k
  }
1721
1722
1.08k
  LOG_FUNC_RETURN(card->ctx, k);
1723
1.08k
}
1724
1725
1726
/**
1727
 * ABI: ISO 7816-4 GET CHALLENGE - generate random byte sequence.
1728
 */
1729
static int
1730
pgp_get_challenge(struct sc_card *card, u8 *rnd, size_t len)
1731
1.35k
{
1732
1.35k
  struct pgp_priv_data *priv;
1733
1734
1.35k
  LOG_FUNC_CALLED(card->ctx);
1735
1736
1.35k
  priv = DRVDATA(card);
1737
1.35k
  if (0 == (priv->ext_caps & EXT_CAP_GET_CHALLENGE)) {
1738
632
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
1739
632
  }
1740
1741
722
  if (priv->max_challenge_size > 0 && len > priv->max_challenge_size) {
1742
205
    len = priv->max_challenge_size;
1743
205
  }
1744
1745
722
  LOG_FUNC_RETURN(card->ctx, iso_ops->get_challenge(card, rnd, len));
1746
722
}
1747
1748
1749
/**
1750
 * ABI: ISO 7816-4 READ BINARY - read data from currently selected EF.
1751
 */
1752
static int
1753
pgp_read_binary(sc_card_t *card, unsigned int idx,
1754
    u8 *buf, size_t count, unsigned long *flags)
1755
0
{
1756
0
  struct pgp_priv_data *priv = DRVDATA(card);
1757
0
  pgp_blob_t  *blob;
1758
0
  int   r;
1759
1760
0
  LOG_FUNC_CALLED(card->ctx);
1761
1762
  /* jump to selected file */
1763
0
  blob = priv->current;
1764
1765
0
  if (blob == NULL)
1766
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND);
1767
1768
0
  if (blob->file->type != SC_FILE_TYPE_WORKING_EF)
1769
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND);
1770
1771
0
  if ((r = pgp_read_blob(card, blob)) < 0)
1772
0
    LOG_FUNC_RETURN(card->ctx, r);
1773
1774
0
  if (idx > blob->len)
1775
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
1776
1777
0
  if (idx + count > blob->len)
1778
0
    count = blob->len - idx;
1779
0
  memcpy(buf, blob->data + idx, count);
1780
1781
0
  LOG_FUNC_RETURN(card->ctx, (int)count);
1782
0
}
1783
1784
1785
/**
1786
 * Internal: get public key from card - as DF + sub-wEFs.
1787
 */
1788
static int
1789
pgp_get_pubkey(sc_card_t *card, unsigned int tag, u8 *buf, size_t buf_len)
1790
2.70k
{
1791
2.70k
  sc_apdu_t apdu;
1792
2.70k
  u8 apdu_case = (card->type == SC_CARD_TYPE_OPENPGP_GNUK)
1793
2.70k
      ? SC_APDU_CASE_4_SHORT : SC_APDU_CASE_4;
1794
2.70k
  u8    idbuf[2];
1795
2.70k
  int   r;
1796
1797
2.70k
  sc_log(card->ctx, "called, tag=%04x\n", tag);
1798
1799
2.70k
  sc_format_apdu(card, &apdu, apdu_case, 0x47, 0x81, 0);
1800
2.70k
  apdu.lc = 2;
1801
2.70k
  apdu.data = ushort2bebytes(idbuf, tag);
1802
2.70k
  apdu.datalen = 2;
1803
2.70k
  apdu.le = ((buf_len >= 256) && !(card->caps & SC_CARD_CAP_APDU_EXT)) ? 256 : buf_len;
1804
2.70k
  apdu.resp = buf;
1805
2.70k
  apdu.resplen = buf_len;
1806
1807
2.70k
  r = sc_transmit_apdu(card, &apdu);
1808
2.70k
  LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
1809
1810
2.68k
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1811
2.68k
  LOG_TEST_RET(card->ctx, r, "Card returned error");
1812
1813
67
  LOG_FUNC_RETURN(card->ctx, (int)apdu.resplen);
1814
67
}
1815
1816
1817
/**
1818
 * Internal: get public key from card - as one wEF.
1819
 */
1820
static int
1821
pgp_get_pubkey_pem(sc_card_t *card, unsigned int tag, u8 *buf, size_t buf_len)
1822
14
{
1823
14
  struct pgp_priv_data *priv = DRVDATA(card);
1824
14
  pgp_blob_t  *blob, *mod_blob, *exp_blob, *pubkey_blob, *blob6e, *blob73, *aa_blob;
1825
14
  sc_pkcs15_pubkey_t p15pubkey;
1826
14
  sc_cardctl_openpgp_key_gen_store_info_t key_info;
1827
14
  unsigned int  aa_tag = 0;
1828
14
  u8    *data = NULL;
1829
14
  size_t    len = 0;
1830
14
  int   r;
1831
1832
14
  sc_log(card->ctx, "called, tag=%04x\n", tag);
1833
14
  memset(&p15pubkey, 0, sizeof(p15pubkey));
1834
1835
14
  if ((r = pgp_get_blob(card, priv->mf, tag & 0xFFFE, &blob)) < 0
1836
14
    || (r = pgp_get_blob(card, blob, 0x7F49, &blob)) < 0)
1837
14
    LOG_TEST_RET(card->ctx, r, "error getting elements");
1838
1839
  /* RSA */
1840
0
  if ((r = pgp_get_blob(card, blob, 0x0081, &mod_blob)) >= 0
1841
0
    && (r = pgp_get_blob(card, blob, 0x0082, &exp_blob)) >= 0
1842
0
    && (r = pgp_read_blob(card, mod_blob)) >= 0
1843
0
    && (r = pgp_read_blob(card, exp_blob)) >= 0) {
1844
1845
0
    p15pubkey.algorithm = SC_ALGORITHM_RSA;
1846
0
    p15pubkey.u.rsa.modulus.data  = mod_blob->data;
1847
0
    p15pubkey.u.rsa.modulus.len   = mod_blob->len;
1848
0
    p15pubkey.u.rsa.exponent.data = exp_blob->data;
1849
0
    p15pubkey.u.rsa.exponent.len  = exp_blob->len;
1850
0
    r = sc_pkcs15_encode_pubkey(card->ctx, &p15pubkey, &data, &len);
1851
0
  }
1852
  /* ECC */
1853
0
  else if ((r = pgp_get_blob(card, blob, 0x0086, &pubkey_blob)) >= 0
1854
0
    && (r = pgp_read_blob(card, pubkey_blob)) >= 0) {
1855
1856
0
    switch(tag & 0xFFFE) {
1857
0
      case DO_SIGN: aa_tag = 0x00C1; break;
1858
0
      case DO_ENCR: aa_tag = 0x00C2; break;
1859
0
      case DO_AUTH: aa_tag = 0x00C3; break;
1860
0
      default: r = SC_ERROR_INCORRECT_PARAMETERS;
1861
0
    }
1862
1863
    /* Get EC parameters from Algorithm Attribute if present */
1864
1865
0
    if (aa_tag && ((r = pgp_get_blob(card, priv->mf, 0x006e, &blob6e)) >= 0) &&
1866
0
        ((r = pgp_get_blob(card, blob6e, 0x0073, &blob73)) >= 0) &&
1867
0
        ((r = pgp_get_blob(card, blob73, aa_tag, &aa_blob)) >= 0) &&
1868
0
        ((r = pgp_parse_algo_attr_blob(card, aa_blob, &key_info)) >= 0)) {
1869
0
      switch (key_info.algorithm) {
1870
0
      case SC_OPENPGP_KEYALGO_EDDSA:
1871
        /* In EDDSA key case we do not have to care about OIDs
1872
         * as we support only one for now */
1873
0
        p15pubkey.algorithm = SC_ALGORITHM_EDDSA;
1874
0
        p15pubkey.u.ec.ecpointQ.value = pubkey_blob->data;
1875
0
        p15pubkey.u.ec.ecpointQ.len = pubkey_blob->len;
1876
        /* PKCS#11 3.0: 2.3.5 Edwards EC public keys only support the use
1877
         * of the curveName selection to specify a curve name as defined
1878
         * in [RFC 8032] */
1879
0
        r = sc_pkcs15_encode_pubkey_as_spki(card->ctx, &p15pubkey, &data, &len);
1880
0
        break;
1881
0
      case SC_OPENPGP_KEYALGO_ECDH:
1882
        /* This yields either EC(DSA) key or EC_MONTGOMERY (curve25519) key */
1883
0
        if (sc_compare_oid(&key_info.u.ec.oid, &curve25519_oid)) {
1884
0
          p15pubkey.algorithm = SC_ALGORITHM_XEDDSA;
1885
0
          p15pubkey.u.ec.ecpointQ.value = pubkey_blob->data;
1886
0
          p15pubkey.u.ec.ecpointQ.len = pubkey_blob->len;
1887
          /* PKCS#11 3.0 2.3.7 Montgomery EC public keys only support
1888
           * the use of the curveName selection to specify a curve
1889
           * name as defined in [RFC7748] */
1890
          /* XXX only curve25519 supported now. Theoretically could be
1891
           * also curve448 or OIDs */
1892
1893
0
          r = sc_pkcs15_encode_pubkey_as_spki(card->ctx, &p15pubkey, &data, &len);
1894
0
          break;
1895
0
        }
1896
        /* fall through */
1897
0
      case SC_OPENPGP_KEYALGO_ECDSA:
1898
0
        if ((r = sc_encode_oid(card->ctx, &key_info.u.ec.oid,
1899
0
            &p15pubkey.u.ec.params.der.value,
1900
0
            &p15pubkey.u.ec.params.der.len)) == 0) {
1901
0
          p15pubkey.algorithm = SC_ALGORITHM_EC;
1902
0
          p15pubkey.u.ec.ecpointQ.value = pubkey_blob->data;
1903
0
          p15pubkey.u.ec.ecpointQ.len = pubkey_blob->len;
1904
0
          p15pubkey.u.ec.params.type = 1;
1905
0
          r = sc_pkcs15_encode_pubkey_as_spki(card->ctx, &p15pubkey, &data, &len);
1906
0
        } else {
1907
0
          sc_log(card->ctx, "Unable to encode EC curve OID from algorithm info");
1908
0
        }
1909
0
        break;
1910
0
      default:
1911
0
        sc_log(card->ctx, "Unknown algorithm ID received (%d)", key_info.algorithm);
1912
0
        break;
1913
0
      }
1914
0
    } else {
1915
0
      sc_log(card->ctx, "Unable to find Algorithm Attribute for EC curve OID");
1916
0
    }
1917
0
  } else {
1918
0
    LOG_TEST_RET(card->ctx, r, "error getting elements");
1919
0
  }
1920
1921
  /* clean up anything we may have set in p15pubkey that can not be freed */
1922
0
  if (p15pubkey.algorithm == SC_ALGORITHM_RSA) {
1923
0
    p15pubkey.u.rsa.modulus.data  = NULL;
1924
0
    p15pubkey.u.rsa.modulus.len = 0;
1925
0
    p15pubkey.u.rsa.exponent.data  = NULL;
1926
0
    p15pubkey.u.rsa.exponent.len = 0;
1927
0
  } else if (p15pubkey.algorithm == SC_ALGORITHM_EC ||
1928
0
      p15pubkey.algorithm == SC_ALGORITHM_EDDSA ||
1929
0
      p15pubkey.algorithm == SC_ALGORITHM_XEDDSA) {
1930
0
    p15pubkey.u.ec.ecpointQ.value = NULL;
1931
0
    p15pubkey.u.ec.ecpointQ.len = 0;
1932
    /* p15pubkey.u.ec.params.der and named_curve will be freed by sc_pkcs15_erase_pubkey */
1933
0
  }
1934
0
  sc_pkcs15_erase_pubkey(&p15pubkey);
1935
1936
0
  LOG_TEST_RET(card->ctx, r, "public key encoding failed");
1937
1938
0
  if (len > buf_len)
1939
0
    len = buf_len;
1940
0
  memcpy(buf, data, len);
1941
0
  free(data);
1942
1943
0
  LOG_FUNC_RETURN(card->ctx, (int)len);
1944
0
}
1945
1946
1947
/**
1948
 * Internal: SELECT DATA - selects a DO within a DO tag with several instances
1949
 * (supported since OpenPGP Card v3 for DO 7F21 only, see section 7.2.5 of the specification;
1950
 *  this enables us to store multiple Card holder certificates in DO 7F21)
1951
 *
1952
 * p1: number of an instance (DO 7F21: 0x00 for AUT, 0x01 for DEC and 0x02 for SIG)
1953
 */
1954
static int
1955
pgp_select_data(sc_card_t *card, u8 p1)
1956
0
{
1957
0
  sc_apdu_t apdu;
1958
0
  u8  apdu_data[6];
1959
0
  int r;
1960
0
  struct pgp_priv_data *priv = DRVDATA(card);
1961
1962
0
  LOG_FUNC_CALLED(card->ctx);
1963
1964
0
  if (priv->bcd_version < OPENPGP_CARD_3_0)
1965
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
1966
1967
0
  sc_log(card->ctx, "select data with: %u", p1);
1968
1969
  // create apdu data (taken from spec: SELECT DATA 7.2.5.)
1970
0
  apdu_data[0] = 0x60;
1971
0
  apdu_data[1] = 0x04;
1972
0
  apdu_data[2] = 0x5c;
1973
0
  apdu_data[3] = 0x02;
1974
0
  apdu_data[4] = 0x7f;
1975
0
  apdu_data[5] = 0x21;
1976
1977
  // apdu, cla, ins, p1, p2, data, datalen, resp, resplen
1978
0
  sc_format_apdu_ex(&apdu, 0x00, 0xA5, p1, 0x04, apdu_data, sizeof(apdu_data), NULL, 0);
1979
1980
  // transmit apdu
1981
0
  r = sc_transmit_apdu(card, &apdu);
1982
0
  LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
1983
0
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1984
0
  LOG_TEST_RET(card->ctx, r, "Card returned error");
1985
0
  LOG_FUNC_RETURN(card->ctx, r);
1986
0
}
1987
1988
1989
/**
1990
 * ABI: ISO 7816-4 GET DATA - get contents of a DO.
1991
 */
1992
static int
1993
pgp_get_data(sc_card_t *card, unsigned int tag, u8 *buf, size_t buf_len)
1994
758k
{
1995
758k
  sc_apdu_t apdu;
1996
758k
  int   r;
1997
1998
758k
  LOG_FUNC_CALLED(card->ctx);
1999
2000
758k
  sc_format_apdu(card, &apdu, SC_APDU_CASE_2, 0xCA, tag >> 8, tag);
2001
758k
  apdu.le = ((buf_len >= 256) && !(card->caps & SC_CARD_CAP_APDU_EXT)) ? 256 : buf_len;
2002
758k
  apdu.resp = buf;
2003
758k
  apdu.resplen = buf_len;
2004
2005
758k
  r = sc_transmit_apdu(card, &apdu);
2006
758k
  LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
2007
2008
734k
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
2009
2010
  /* Gnuk returns an error instead of empty data if there is no certificate or private DO.
2011
   * So, for this case, we ignore error and consider success */
2012
734k
  if (card->type == SC_CARD_TYPE_OPENPGP_GNUK &&
2013
5.22k
      (tag == DO_CERT  ||
2014
5.16k
       tag == DO_PRIV1 ||
2015
5.16k
       tag == DO_PRIV2 ||
2016
5.16k
       tag == DO_PRIV3 ||
2017
5.16k
       tag == DO_PRIV4)) {
2018
62
    if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) {
2019
1
      r = SC_SUCCESS;
2020
1
      apdu.resplen = 0;
2021
1
    }
2022
62
  }
2023
734k
  LOG_TEST_RET(card->ctx, r, "Card returned error");
2024
2025
97.2k
  LOG_FUNC_RETURN(card->ctx, (int)apdu.resplen);
2026
97.2k
}
2027
2028
/**
2029
 * Internal: write certificate for Gnuk.
2030
 */
2031
static int
2032
gnuk_write_certificate(sc_card_t *card, const u8 *buf, size_t length)
2033
52
{
2034
52
  size_t i = 0;
2035
52
  sc_apdu_t apdu;
2036
52
  int r = SC_SUCCESS;
2037
2038
52
  LOG_FUNC_CALLED(card->ctx);
2039
2040
  /* If null data is passed, delete certificate */
2041
52
  if (buf == NULL || length == 0) {
2042
11
    sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xD6, 0x85, 0);
2043
11
    r = sc_transmit_apdu(card, &apdu);
2044
11
    LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
2045
    /* Check response */
2046
10
    LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
2047
10
  }
2048
2049
  /* Ref: gnuk_put_binary_libusb.py and gnuk_token.py in Gnuk source tree */
2050
  /* Split data to segments of 256 bytes. Send each segment via command chaining,
2051
   * with particular P1 byte for each segment */
2052
479
  for (i = 0; i*256 < length; i++) {
2053
467
    u8 *part = (u8 *)buf + i*256;
2054
467
    size_t plen = MIN(length - i*256, 256);
2055
467
    u8 roundbuf[256]; /* space to build APDU data with even length for Gnuk */
2056
2057
467
    sc_log(card->ctx, "Write part %zu from offset 0x%zX, len %zu", i + 1, i * 256, plen);
2058
2059
    /* 1st chunk: P1 = 0x85, further chunks: P1 = chunk no */
2060
467
    sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xD6, (i == 0) ? 0x85 : (int)i, 0);
2061
467
    apdu.flags |= SC_APDU_FLAGS_CHAINING;
2062
467
    apdu.data = part;
2063
467
    apdu.datalen = apdu.lc = plen;
2064
2065
    /* If the last part has odd length, we add zero padding to make it even.
2066
     * Gnuk does not allow data with odd length */
2067
467
    if (plen < 256 && (plen % 2) != 0) {
2068
15
      memcpy(roundbuf, part, plen);
2069
15
      roundbuf[plen++] = 0;
2070
15
      apdu.data = roundbuf;
2071
15
      apdu.datalen = apdu.lc = plen;
2072
15
    }
2073
2074
467
    r = sc_transmit_apdu(card, &apdu);
2075
467
    LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
2076
    /* Check response */
2077
453
    LOG_TEST_RET(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2), "UPDATE BINARY returned error");
2078
453
  }
2079
2080
12
  LOG_FUNC_RETURN(card->ctx, (int)length);
2081
12
}
2082
2083
2084
/**
2085
 * Internal: use PUT DATA command to write.
2086
 */
2087
static int
2088
pgp_put_data_plain(sc_card_t *card, unsigned int tag, const u8 *buf, size_t buf_len)
2089
132
{
2090
132
  struct pgp_priv_data *priv = DRVDATA(card);
2091
132
  sc_apdu_t apdu;
2092
132
  u8 ins = 0xDA;
2093
132
  u8 p1 = tag >> 8;
2094
132
  u8 p2 = tag & 0xFF;
2095
132
  u8 apdu_case = (card->type == SC_CARD_TYPE_OPENPGP_GNUK)
2096
132
      ? SC_APDU_CASE_3_SHORT : SC_APDU_CASE_3;
2097
132
  int r;
2098
2099
132
  LOG_FUNC_CALLED(card->ctx);
2100
2101
  /* Extended Header list (DO 004D) needs a variant of PUT DATA command */
2102
132
  if (tag == 0x004D) {
2103
4
    ins = 0xDB;
2104
4
    p1 = 0x3F;
2105
4
    p2 = 0xFF;
2106
4
  }
2107
2108
  /* build APDU */
2109
132
  if (buf != NULL && buf_len > 0) {
2110
23
    sc_format_apdu(card, &apdu, apdu_case, ins, p1, p2);
2111
2112
    /* if card/reader does not support extended APDUs, but chaining, then set it */
2113
23
    if (((card->caps & SC_CARD_CAP_APDU_EXT) == 0) && (priv->ext_caps & EXT_CAP_CHAINING))
2114
3
      apdu.flags |= SC_APDU_FLAGS_CHAINING;
2115
2116
23
    apdu.data = (u8 *)buf;
2117
23
    apdu.datalen = buf_len;
2118
23
    apdu.lc = buf_len;
2119
23
  }
2120
109
  else {
2121
    /* This case is to empty DO */
2122
109
    sc_format_apdu(card, &apdu, SC_APDU_CASE_1, ins, p1, p2);
2123
109
  }
2124
2125
  /* send APDU to card */
2126
132
  r = sc_transmit_apdu(card, &apdu);
2127
132
  LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
2128
  /* check response */
2129
129
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
2130
129
  LOG_TEST_RET(card->ctx, r, "Card returned error");
2131
2132
13
  LOG_FUNC_RETURN(card->ctx, (int)buf_len);
2133
13
}
2134
2135
2136
/**
2137
 * ABI: ISO 7816-4 PUT DATA - write contents of a DO.
2138
 */
2139
static int
2140
pgp_put_data(sc_card_t *card, unsigned int tag, const u8 *buf, size_t buf_len)
2141
1.08k
{
2142
1.08k
  struct pgp_priv_data *priv = DRVDATA(card);
2143
1.08k
  pgp_blob_t *affected_blob = NULL;
2144
1.08k
  pgp_do_info_t *dinfo = NULL;
2145
1.08k
  int r;
2146
2147
1.08k
  LOG_FUNC_CALLED(card->ctx);
2148
2149
  /* Check if there is a blob for the given tag */
2150
1.08k
  affected_blob = pgp_find_blob(card, tag);
2151
2152
  /* Non-readable DOs have no represented blob, we have to check from pgp_get_info_by_tag */
2153
1.08k
  if (affected_blob == NULL)
2154
892
    dinfo = pgp_get_info_by_tag(card, tag);
2155
191
  else
2156
191
    dinfo = affected_blob->info;
2157
2158
  /* Make sure the DO exists and is writeable */
2159
1.08k
  if (dinfo == NULL) {
2160
871
    sc_log(card->ctx, "The DO %04X does not exist.", tag);
2161
871
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
2162
871
  }
2163
212
  else if ((dinfo->access & WRITE_MASK) == WRITE_NEVER) {
2164
14
    sc_log(card->ctx, "DO %04X is not writable.", tag);
2165
14
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ALLOWED);
2166
14
  }
2167
2168
  /* Check data size.
2169
   * We won't check other DOs than 7F21 (certificate), because their capacity
2170
   * is hard-coded and may change in various version of the card.
2171
   * If we check here, the driver may be stuck to a limit version number of card.
2172
   * 7F21 size is soft-coded, so we can check it. */
2173
198
  if (tag == DO_CERT && buf_len > priv->max_cert_size) {
2174
14
    sc_log(card->ctx, "Data size %zu exceeds DO size limit %zu.", buf_len, priv->max_cert_size);
2175
14
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_WRONG_LENGTH);
2176
14
  }
2177
2178
184
  if (tag == DO_CERT && card->type == SC_CARD_TYPE_OPENPGP_GNUK) {
2179
    /* Gnuk need a special way to write certificate. */
2180
52
    r = gnuk_write_certificate(card, buf, buf_len);
2181
52
  }
2182
132
  else {
2183
132
    r = pgp_put_data_plain(card, tag, buf, buf_len);
2184
132
  }
2185
2186
  /* instruct more in case of error */
2187
184
  if (r == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {
2188
1
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Please verify PIN first.");
2189
1
  }
2190
184
  LOG_TEST_RET(card->ctx, r, "PUT DATA returned error");
2191
2192
25
  if (affected_blob) {
2193
    /* update the corresponding file */
2194
20
    sc_log(card->ctx, "Updating the corresponding blob data");
2195
20
    r = pgp_set_blob(affected_blob, buf, buf_len);
2196
20
    if (r < 0)
2197
0
      sc_log(card->ctx, "Failed to update blob %04X. Error %d.", affected_blob->id, r);
2198
    /* pgp_set_blob()'s failures do not impact pgp_put_data()'s result */
2199
20
  }
2200
2201
25
  LOG_FUNC_RETURN(card->ctx, (int)buf_len);
2202
25
}
2203
2204
#ifdef ENABLE_OPENSSL
2205
/* KDF_ITERSALTED_S2K algorithm, a simplified version of openpgp_s2k from libgcrypt[1]
2206
 * that supports one-pass only and outputs the same key length as the hash length of
2207
 * the specified hash algorithm.
2208
 * [1]: https://github.com/gpg/libgcrypt/blob/libgcrypt-1.11.0/cipher/kdf.c#L32-L109
2209
 */
2210
static int
2211
kdf_itersalted_s2k(struct sc_context *ctx, const char *hash, const uint8_t *pin, size_t pinlen, const uint8_t *salt, size_t saltlen, uint32_t iterations, uint8_t **out, size_t *outlen)
2212
0
{
2213
0
  int r = SC_ERROR_INVALID_ARGUMENTS;
2214
0
  EVP_MD *md = NULL;
2215
0
  EVP_MD_CTX *hctx = NULL;
2216
0
  int keysize;
2217
0
  uint8_t *outkey = NULL;
2218
0
  size_t count;
2219
0
  int ret;
2220
0
  unsigned int outsize;
2221
2222
0
  if (!ctx || !hash || !pin || pinlen == 0 || !salt || saltlen != 8 || !out || !outlen) {
2223
0
    return r;
2224
0
  }
2225
2226
0
  md = sc_evp_md(ctx, hash);
2227
0
  if (md == NULL) {
2228
0
    return r;
2229
0
  }
2230
2231
0
  r = SC_ERROR_INTERNAL;
2232
0
  hctx = EVP_MD_CTX_new();
2233
0
  if (hctx == NULL) {
2234
0
    goto out;
2235
0
  }
2236
2237
0
  if (!EVP_DigestInit(hctx, md)) {
2238
0
    goto out;
2239
0
  }
2240
2241
0
  keysize = EVP_MD_size(md);
2242
0
  if (keysize <= 0) {
2243
0
    goto out;
2244
0
  }
2245
2246
0
  outkey = (uint8_t *)sc_mem_secure_alloc(keysize);
2247
0
  if (outkey == NULL) {
2248
0
    r = SC_ERROR_NOT_ENOUGH_MEMORY;
2249
0
    goto out;
2250
0
  }
2251
2252
0
  count = iterations;
2253
0
  if (count < pinlen + saltlen) {
2254
0
    count = pinlen + saltlen;
2255
0
  }
2256
2257
0
  while (count >= pinlen + saltlen) {
2258
0
    ret = EVP_DigestUpdate(hctx, salt, saltlen);
2259
0
    if (!ret) {
2260
0
      goto out;
2261
0
    }
2262
0
    ret = EVP_DigestUpdate(hctx, pin, pinlen);
2263
0
    if (!ret) {
2264
0
      goto out;
2265
0
    }
2266
0
    count -= pinlen + saltlen;
2267
0
  }
2268
2269
0
  if (count <= saltlen) {
2270
0
    ret = EVP_DigestUpdate(hctx, salt, count);
2271
0
  } else {
2272
0
    ret = EVP_DigestUpdate(hctx, salt, saltlen);
2273
0
    if (!ret) {
2274
0
      goto out;
2275
0
    }
2276
0
    count -= saltlen;
2277
0
    ret = EVP_DigestUpdate(hctx, pin, count);
2278
0
  }
2279
0
  if (!ret) {
2280
0
    goto out;
2281
0
  }
2282
2283
0
  outsize = keysize;
2284
0
  ret = EVP_DigestFinal(hctx, outkey, &outsize);
2285
0
  if (ret && outsize == (unsigned int)keysize) {
2286
0
    r = SC_SUCCESS;
2287
0
  }
2288
0
out:
2289
0
  if (r != SC_SUCCESS && outkey != NULL) {
2290
0
    sc_mem_secure_clear_free(outkey, keysize);
2291
0
  }
2292
0
  EVP_MD_CTX_free(hctx);
2293
0
  sc_evp_md_free(md);
2294
0
  if (r == SC_SUCCESS) {
2295
0
    *out = outkey;
2296
0
    *outlen = outsize;
2297
0
  }
2298
0
  return r;
2299
0
}
2300
2301
static int
2302
pgp_kdf_do_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data)
2303
0
{
2304
0
  int r = SC_ERROR_INVALID_ARGUMENTS;
2305
0
  struct pgp_priv_data *priv = DRVDATA(card);
2306
0
  const pgp_pin_kdf_info_t *const info = priv->pin_kdf_info;
2307
0
  uint8_t *pin1_derived = NULL;
2308
0
  uint8_t *pin2_derived = NULL;
2309
0
  size_t pin1_derived_len = 0;
2310
0
  size_t pin2_derived_len = 0;
2311
0
  const uint8_t *const pin1 = data->pin1.data;
2312
0
  const size_t pin1len = data->pin1.len;
2313
0
  const uint8_t *const pin2 = data->pin2.data;
2314
0
  const size_t pin2len = data->pin2.len;
2315
0
  const uint8_t *salt = NULL;
2316
0
  size_t saltlen = 0;
2317
2318
0
  switch (data->cmd) {
2319
0
  case SC_PIN_CMD_VERIFY:
2320
0
  case SC_PIN_CMD_CHANGE:
2321
0
  case SC_PIN_CMD_UNBLOCK:
2322
0
    break;
2323
0
  default:
2324
0
    LOG_FUNC_RETURN(card->ctx, iso_ops->pin_cmd(card, data));
2325
0
  }
2326
0
  if (!info) {
2327
0
    return r;
2328
0
  }
2329
2330
0
  switch (data->pin_reference) {
2331
0
  case 0x81:
2332
0
  case 0x82:
2333
0
    salt = info->userpw_salt->data;
2334
0
    saltlen = info->userpw_salt->len;
2335
0
    break;
2336
0
  case 0x83:
2337
0
    salt = info->adminpw_salt->data;
2338
0
    saltlen = info->adminpw_salt->len;
2339
0
    break;
2340
0
  }
2341
2342
0
  switch (data->cmd) {
2343
0
  case SC_PIN_CMD_UNBLOCK:
2344
0
  case SC_PIN_CMD_CHANGE:
2345
0
    r = kdf_itersalted_s2k(card->ctx, info->hash_algo, pin2, pin2len, salt, saltlen, info->iterations, &pin2_derived, &pin2_derived_len);
2346
0
    if (r != SC_SUCCESS) {
2347
0
      break;
2348
0
    }
2349
0
    data->pin2.data = pin2_derived;
2350
0
    data->pin2.len = pin2_derived_len;
2351
0
    if (data->cmd == SC_PIN_CMD_UNBLOCK) {
2352
0
      salt = info->adminpw_salt->data;
2353
0
      saltlen = info->adminpw_salt->len;
2354
0
    }
2355
    // fallthrough
2356
0
  case SC_PIN_CMD_VERIFY:
2357
0
    r = kdf_itersalted_s2k(card->ctx, info->hash_algo, pin1, pin1len, salt, saltlen, info->iterations, &pin1_derived, &pin1_derived_len);
2358
0
    if (r != SC_SUCCESS) {
2359
0
      break;
2360
0
    }
2361
0
    data->pin1.data = pin1_derived;
2362
0
    data->pin1.len = pin1_derived_len;
2363
0
    break;
2364
0
  }
2365
2366
0
  if (r == SC_SUCCESS) {
2367
0
    r = iso_ops->pin_cmd(card, data);
2368
0
  }
2369
0
  if (pin1_derived) {
2370
0
    data->pin1.data = pin1;
2371
0
    data->pin1.len = pin1len;
2372
0
    sc_mem_secure_clear_free(pin1_derived, pin1_derived_len);
2373
0
  }
2374
0
  if (pin2_derived) {
2375
0
    data->pin2.data = pin2;
2376
0
    data->pin2.len = pin2len;
2377
0
    sc_mem_secure_clear_free(pin2_derived, pin2_derived_len);
2378
0
  }
2379
0
  LOG_FUNC_RETURN(card->ctx, r);
2380
0
}
2381
#endif /* ENABLE_OPENSSL */
2382
2383
/**
2384
 * ABI: ISO 7816-9 PIN CMD - verify/change/unblock a PIN.
2385
 */
2386
static int
2387
pgp_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data)
2388
0
{
2389
0
  struct pgp_priv_data *priv = DRVDATA(card);
2390
0
  struct sc_card_operations ops = {.pin_cmd = iso_ops->pin_cmd};
2391
2392
0
  LOG_FUNC_CALLED(card->ctx);
2393
2394
0
  if (data->pin_type != SC_AC_CHV)
2395
0
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2396
0
        "invalid PIN type");
2397
2398
  /* In general, the PIN Reference is extracted from the key-id,
2399
   * for example, CHV0 -> Ref=0, CHV1 -> Ref=1.
2400
   * However, in the case of OpenPGP, the PIN Ref to compose APDU
2401
   * must be 81, 82, 83.
2402
   * So, if we receive Ref=1, Ref=2, we must convert to 81, 82...
2403
   * In OpenPGP v1, the PINs are named CHV1, CHV2, CHV3.
2404
   * In v2, they are named PW1, PW3 (PW1 operates in 2 modes).
2405
   *
2406
   * The PIN references (P2 in APDU) for "VERIFY" are the same in both versions:
2407
   * 81 (CHV1 or PW1), 82 (CHV2 or PW1-mode 2), 83 (CHV3 or PW3),
2408
   * On the other hand from version 2.0 "CHANGE REFERENCE DATA" and
2409
   * "RESET RETRY COUNTER" don't support PW1-mode 2 (82) and need this
2410
   * value changed to PW1 (81).
2411
   * Both of these commands also differ between card versions in that
2412
   * v1 cards can use only implicit old PIN or CHV3 test for both commands
2413
   * whereas v2 can use both implicit (for PW3) and explicit
2414
   * (for special "Resetting Code") PIN test for "RESET RETRY COUNTER"
2415
   * and only explicit test for "CHANGE REFERENCE DATA".
2416
   *
2417
   * Note that if this function is called from sc_pkcs15_verify_pin() in pkcs15-pin.c,
2418
   * the Ref is already 81, 82, 83.
2419
   */
2420
2421
  /* convert the PIN Reference if needed */
2422
0
  data->pin_reference |= 0x80;
2423
2424
  /* check version-dependent constraints */
2425
0
  if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) {
2426
0
    if (priv->bcd_version >= OPENPGP_CARD_2_0) {
2427
0
      if (data->pin_reference == 0x82)
2428
0
        data->pin_reference = 0x81;
2429
2430
0
      if (data->cmd == SC_PIN_CMD_CHANGE) {
2431
0
        if (data->pin1.len == 0 &&
2432
0
            !(data->flags & SC_PIN_CMD_USE_PINPAD))
2433
0
          LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2434
0
              "v2 cards don't support implicit old PIN for PIN change");
2435
2436
0
        data->flags &= ~SC_PIN_CMD_IMPLICIT_CHANGE;
2437
0
      }
2438
0
    } else {
2439
0
      if (data->pin1.len != 0) {
2440
0
        sc_log(card->ctx,
2441
0
               "v1 cards don't support explicit old or CHV3 PIN, PIN ignored.");
2442
0
        sc_log(card->ctx,
2443
0
               "please make sure that you have verified the relevant PIN first.");
2444
0
        data->pin1.len = 0;
2445
0
      }
2446
2447
0
      data->flags |= SC_PIN_CMD_IMPLICIT_CHANGE;
2448
0
    }
2449
0
  }
2450
2451
0
  if (data->cmd == SC_PIN_CMD_UNBLOCK && data->pin2.len == 0 &&
2452
0
      !(data->flags & SC_PIN_CMD_USE_PINPAD))
2453
0
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2454
0
        "new PIN must be provided for unblock operation");
2455
2456
  /* ensure pin_reference is 81, 82, 83 */
2457
0
  if (data->pin_reference < 0x81 || data->pin_reference > 0x83)
2458
0
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2459
0
        "Invalid key ID; must be 1, 2, or 3");
2460
2461
  /* emulate SC_PIN_CMD_GET_INFO command for cards not supporting it */
2462
0
  if (data->cmd == SC_PIN_CMD_GET_INFO && (card->caps & SC_CARD_CAP_ISO7816_PIN_INFO) == 0) {
2463
0
    u8 c4data[10];
2464
0
    int r;
2465
2466
0
    r = sc_get_data(card, 0x00c4, c4data, sizeof(c4data));
2467
0
    LOG_TEST_RET(card->ctx, r, "reading CHV status bytes failed");
2468
2469
0
    if (r != 7)
2470
0
      LOG_TEST_RET(card->ctx, SC_ERROR_OBJECT_NOT_VALID,
2471
0
        "CHV status bytes have unexpected length");
2472
2473
    /* The definition of fields of DO C4 changed between OpenPGP
2474
     * card specification v1.1 and v2.0. There is no longer a separate
2475
     * CHV2 retry counter but only one retry counter for both PW1 mode 1
2476
     * and mode 2 at byte 5 (count from 1) of the DO.
2477
     */
2478
0
    if (priv->bcd_version >= OPENPGP_CARD_2_0 && data->pin_reference == 0x82)
2479
0
      data->pin_reference = 0x81;
2480
2481
0
    data->pin1.tries_left = c4data[3 + (data->pin_reference & 0x0F)];
2482
0
    data->pin1.max_tries = 3;
2483
0
    data->pin1.logged_in = SC_PIN_STATE_UNKNOWN;
2484
2485
0
    LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
2486
0
  }
2487
2488
0
#ifdef ENABLE_OPENSSL
2489
0
  if (priv->pin_kdf_info) {
2490
0
    ops.pin_cmd = &pgp_kdf_do_pin_cmd;
2491
0
  }
2492
0
#endif /* ENABLE_OPENSSL */
2493
2494
0
  LOG_FUNC_RETURN(card->ctx, ops.pin_cmd(card, data));
2495
0
}
2496
2497
2498
/**
2499
 * ABI: ISO 7816-8 LOGOUT - reset all access rights gained.
2500
 */
2501
int pgp_logout(struct sc_card *card)
2502
0
{
2503
0
  int r = SC_SUCCESS;
2504
0
  struct pgp_priv_data *priv = DRVDATA(card);
2505
2506
0
  LOG_FUNC_CALLED(card->ctx);
2507
2508
0
  if (priv->bcd_version >= OPENPGP_CARD_3_1) {
2509
0
    unsigned char pin_reference;
2510
0
    for (pin_reference = 0x81; pin_reference <= 0x83; pin_reference++) {
2511
0
      int tmp = iso7816_logout(card, pin_reference);
2512
0
      if (r == SC_SUCCESS) {
2513
0
        r = tmp;
2514
0
      }
2515
0
    }
2516
0
  } else {
2517
0
    sc_path_t path;
2518
0
    sc_file_t *file = NULL;
2519
2520
    /* select application "OpenPGP" */
2521
0
    sc_format_path("D276:0001:2401", &path);
2522
0
    path.type = SC_PATH_TYPE_DF_NAME;
2523
0
    r = iso_ops->select_file(card, &path, &file);
2524
0
    sc_file_free(file);
2525
0
  }
2526
2527
0
  LOG_FUNC_RETURN(card->ctx, r);
2528
0
}
2529
2530
2531
/**
2532
 * ABI: ISO 7816-8 SET SECURITY ENVIRONMENT.
2533
 * This is optional in the OpenPGP Card 3.4 specs
2534
 */
2535
static int
2536
pgp_set_security_env(sc_card_t *card,
2537
    const sc_security_env_t *env, int se_num)
2538
0
{
2539
0
  struct pgp_priv_data *priv = DRVDATA(card);
2540
2541
0
  LOG_FUNC_CALLED(card->ctx);
2542
2543
  /* The SC_SEC_ENV_ALG_PRESENT is set always so let it pass for GNUK */
2544
0
  if ((env->flags & SC_SEC_ENV_ALG_PRESENT)
2545
0
    && (env->algorithm != SC_ALGORITHM_RSA)
2546
0
    && (priv->bcd_version < OPENPGP_CARD_3_0)
2547
0
    && (card->type != SC_CARD_TYPE_OPENPGP_GNUK))
2548
0
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2549
0
        "only RSA algorithm supported");
2550
2551
0
  if (!(env->flags & SC_SEC_ENV_KEY_REF_PRESENT) || (env->key_ref_len != 1))
2552
0
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2553
0
        "exactly one key reference required");
2554
2555
0
  if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT)
2556
0
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2557
0
      "passing file references not supported");
2558
2559
0
  sc_log(card->ctx, "Key ref %d", env->key_ref[0]);
2560
0
  switch (env->operation) {
2561
0
  case SC_SEC_OPERATION_SIGN:
2562
0
    sc_log(card->ctx, "Operation: Sign.");
2563
0
    if (env->key_ref[0] != 0x00 && env->key_ref[0] != 0x02) {
2564
0
      LOG_TEST_RET(card->ctx, SC_ERROR_NOT_SUPPORTED,
2565
0
        "Key reference not compatible with "
2566
0
        "requested usage");
2567
0
    }
2568
0
    break;
2569
0
  case SC_SEC_OPERATION_DECIPHER:
2570
0
    sc_log(card->ctx, "Operation: Decipher.");
2571
    /* we allow key ref 2 (auth key) to be used for deciphering */
2572
0
    if (env->key_ref[0] != 0x01 && env->key_ref[0] != 0x02) {
2573
0
      LOG_TEST_RET(card->ctx, SC_ERROR_NOT_SUPPORTED,
2574
0
        "Key reference not compatible with "
2575
0
        "requested usage");
2576
0
    }
2577
0
    break;
2578
0
  case SC_SEC_OPERATION_DERIVE:
2579
0
    sc_log(card->ctx, "Operation: Derive: No particular action needed");
2580
0
    break;
2581
0
  default:
2582
0
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2583
0
        "invalid operation");
2584
0
  }
2585
2586
0
  priv->sec_env = *env;
2587
2588
0
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
2589
0
}
2590
2591
2592
/**
2593
 * set MANAGE SECURITY ENVIRONMENT as documented in 7.2.18 since OpenPGP Card v3.3
2594
 *
2595
 * "This optional command (announced in Extended Capabilities) assigns a specific key to a
2596
 * command. The DEC-key (Key-Ref 2) can be assigned to the command INTERNAL AUTHENTICATE
2597
 * and the AUT-Key (Key.Ref 3) can be linked to the command PSO:DECIPHER also."
2598
 *
2599
 * key: Key-Ref to change (2 for DEC-Key or 3 for AUT-Key)
2600
 * p2: Usage to set (0xb8 for PSO:DECIPHER or 0xa4 for INTERNAL AUTHENTICATE)
2601
 **/
2602
static int
2603
pgp_set_MSE(sc_card_t *card, int key, u8 p2)
2604
0
{
2605
0
  struct pgp_priv_data  *priv = DRVDATA(card);
2606
0
  sc_apdu_t apdu;
2607
0
  u8  apdu_case = SC_APDU_CASE_3;
2608
0
  u8  apdu_data[3];
2609
0
  int r;
2610
2611
0
  LOG_FUNC_CALLED(card->ctx);
2612
2613
  // check if MSE is supported
2614
0
  if (!(priv->ext_caps & EXT_CAP_MSE))
2615
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
2616
2617
  // create apdu
2618
0
  sc_format_apdu(card, &apdu, apdu_case, 0x22, 0x41, p2);
2619
0
  apdu.lc = 3;
2620
0
  apdu_data[0] = 0x83;
2621
0
  apdu_data[1] = 0x01;
2622
0
  apdu_data[2] = key;
2623
0
  apdu.data = apdu_data;
2624
0
  apdu.datalen = 3;
2625
2626
  // transmit apdu
2627
0
  r = sc_transmit_apdu(card, &apdu);
2628
0
  LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
2629
2630
0
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
2631
0
  LOG_TEST_RET(card->ctx, r, "Card returned error");
2632
2633
0
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
2634
0
}
2635
2636
2637
/**
2638
 * ABI: ISO 7816-8 COMPUTE DIGITAL SIGNATURE.
2639
 */
2640
static int
2641
pgp_compute_signature(sc_card_t *card, const u8 *data,
2642
                size_t data_len, u8 * out, size_t outlen)
2643
0
{
2644
0
  struct pgp_priv_data  *priv = DRVDATA(card);
2645
0
  sc_security_env_t *env = &priv->sec_env;
2646
0
  sc_apdu_t   apdu;
2647
0
  u8 apdu_case = (card->type == SC_CARD_TYPE_OPENPGP_GNUK)
2648
0
      ? SC_APDU_CASE_4_SHORT : SC_APDU_CASE_4;
2649
0
  int     r;
2650
2651
0
  LOG_FUNC_CALLED(card->ctx);
2652
2653
0
  if (env->operation != SC_SEC_OPERATION_SIGN)
2654
0
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2655
0
        "invalid operation");
2656
2657
0
  switch (env->key_ref[0]) {
2658
0
  case 0x00: /* signature key */
2659
    /* PSO SIGNATURE */
2660
0
    sc_format_apdu(card, &apdu, apdu_case, 0x2A, 0x9E, 0x9A);
2661
0
    break;
2662
0
  case 0x02: /* authentication key */
2663
    /* INTERNAL AUTHENTICATE */
2664
0
    sc_format_apdu(card, &apdu, apdu_case, 0x88, 0, 0);
2665
0
    break;
2666
0
  case 0x01:
2667
0
  default:
2668
    /* From PKCS #11 point of view, we should be able to use
2669
     * curve25519 to do digital signature, but it is not how it
2670
     * is used in OpenPGP so we will not allow it here */
2671
0
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2672
0
      "invalid key reference");
2673
0
  }
2674
2675
  /* if card/reader does not support extended APDUs, but chaining, then set it */
2676
0
  if (((card->caps & SC_CARD_CAP_APDU_EXT) == 0) && (priv->ext_caps & EXT_CAP_CHAINING))
2677
0
    apdu.flags |= SC_APDU_FLAGS_CHAINING;
2678
2679
0
  apdu.lc = data_len;
2680
0
  apdu.data = (u8 *)data;
2681
0
  apdu.datalen = data_len;
2682
0
  apdu.le = ((outlen >= 256) && !(card->caps & SC_CARD_CAP_APDU_EXT)) ? 256 : outlen;
2683
0
  apdu.resp    = out;
2684
0
  apdu.resplen = outlen;
2685
2686
0
  r = sc_transmit_apdu(card, &apdu);
2687
0
  LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
2688
2689
0
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
2690
0
  LOG_TEST_RET(card->ctx, r, "Card returned error");
2691
2692
0
  LOG_FUNC_RETURN(card->ctx, (int)apdu.resplen);
2693
0
}
2694
2695
2696
/**
2697
 * ABI: ISO 7816-8 DECIPHER - perform deciphering operation.
2698
 */
2699
static int
2700
pgp_decipher(sc_card_t *card, const u8 *in, size_t inlen,
2701
    u8 *out, size_t outlen)
2702
0
{
2703
0
  struct pgp_priv_data  *priv = DRVDATA(card);
2704
0
  sc_security_env_t *env = &priv->sec_env;
2705
0
  sc_apdu_t apdu;
2706
0
  u8 apdu_case = SC_APDU_CASE_4;
2707
0
  u8    *temp = NULL, *p = NULL;
2708
0
  size_t    templen, pklen, dolen;
2709
0
  int   r;
2710
2711
0
  LOG_FUNC_CALLED(card->ctx);
2712
2713
  /* padding according to OpenPGP card spec 1.1 & 2.x section 7.2.9 / 3.x section 7.2.11
2714
   * The longest possible prefix is 10 bytes for ECDH */
2715
0
  templen = inlen + 10;
2716
0
  if (!(temp = malloc(templen)))
2717
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
2718
2719
  /* padding byte: 0xa6 = ECC; 0x00 = RSA; 0x02 = AES */
2720
0
  switch (env->algorithm) {
2721
0
  case SC_ALGORITHM_RSA:
2722
    /* This is just PKCS#1.5 start byte and it should be already
2723
     * provided by the padding routines. But it lets put it here
2724
     * to make sure it does not conflict with following indicators */
2725
0
    temp[0] = 0x00;
2726
0
    memcpy(temp + 1, in, inlen);
2727
0
    inlen += 1;
2728
0
    break;
2729
2730
0
  case SC_ALGORITHM_EC:
2731
0
  case SC_ALGORITHM_XEDDSA:
2732
    /* Calculate length of External Public Key (0x86) */
2733
0
    r = sc_asn1_put_tag(0x86, NULL, inlen, NULL, 0, NULL);
2734
0
    if (r <= 0) {
2735
0
      free(temp);
2736
0
      LOG_FUNC_RETURN(card->ctx, r);
2737
0
    }
2738
0
    pklen = r;
2739
2740
    /* Calculate length of Public Key DO (0x7F49) */
2741
0
    r = sc_asn1_put_tag(0x7f49, NULL, pklen, NULL, 0, NULL);
2742
0
    if (r <= 0) {
2743
0
      free(temp);
2744
0
      LOG_FUNC_RETURN(card->ctx, r);
2745
0
    }
2746
0
    dolen = r;
2747
2748
0
    p = temp;
2749
    /* This is 0xA6 Cipher DO with associated length field */
2750
0
    r = sc_asn1_put_tag(0xA6, NULL, dolen, p, templen - (p - temp), &p);
2751
0
    if (r != SC_SUCCESS) {
2752
0
      free(temp);
2753
0
      LOG_FUNC_RETURN(card->ctx, r);
2754
0
    }
2755
2756
    /* Public Key DO (0x7F49) with associated length field */
2757
0
    r = sc_asn1_put_tag(0x7F49, NULL, pklen, p, templen - (p - temp), &p);
2758
0
    if (r != SC_SUCCESS) {
2759
0
      free(temp);
2760
0
      LOG_FUNC_RETURN(card->ctx, r);
2761
0
    }
2762
2763
    /* External Public Key (0x86) with associated length */
2764
0
    r = sc_asn1_put_tag(0x86, in, inlen, p, templen - (p - temp), &p);
2765
0
    if (r != SC_SUCCESS) {
2766
0
      free(temp);
2767
0
      LOG_FUNC_RETURN(card->ctx, r);
2768
0
    }
2769
0
    inlen = (p - temp);
2770
0
    break;
2771
0
  case SC_ALGORITHM_AES:
2772
    /* not supported yet */
2773
    /*
2774
    temp[0] = 0x02;
2775
    memcpy(temp + 1, in, inlen);
2776
    inlen += 1;
2777
    */
2778
    /* fall through */
2779
0
  default:
2780
0
    free(temp);
2781
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
2782
0
  }
2783
2784
0
  in = temp;
2785
2786
0
  if (env->operation != SC_SEC_OPERATION_DECIPHER &&
2787
0
      env->operation != SC_SEC_OPERATION_DERIVE) {
2788
0
    free(temp);
2789
0
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2790
0
        "invalid operation");
2791
0
  }
2792
2793
0
  switch (env->key_ref[0]) {
2794
0
  case 0x01: /* Decryption key */
2795
0
  case 0x02: /* authentication key */
2796
    /* PSO DECIPHER */
2797
0
    sc_format_apdu(card, &apdu, apdu_case, 0x2A, 0x80, 0x86);
2798
0
    break;
2799
0
  case 0x00: /* signature key */
2800
0
  default:
2801
0
    free(temp);
2802
0
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2803
0
        "invalid key reference");
2804
0
  }
2805
2806
  /* Gnuk only supports short APDU, so we need to use command chaining */
2807
0
  if (card->type == SC_CARD_TYPE_OPENPGP_GNUK) {
2808
0
    apdu.flags |= SC_APDU_FLAGS_CHAINING;
2809
0
  }
2810
  /* if card/reader does not support extended APDUs, but chaining, then set it */
2811
0
  if (((card->caps & SC_CARD_CAP_APDU_EXT) == 0) && (priv->ext_caps & EXT_CAP_CHAINING))
2812
0
    apdu.flags |= SC_APDU_FLAGS_CHAINING;
2813
2814
0
  apdu.lc = inlen;
2815
0
  apdu.data = (u8 *)in;
2816
0
  apdu.datalen = inlen;
2817
0
  apdu.le = ((outlen >= 256) && !(card->caps & SC_CARD_CAP_APDU_EXT)) ? 256 : outlen;
2818
0
  apdu.resp = out;
2819
0
  apdu.resplen = outlen;
2820
2821
  /* For OpenPGP Card >=v3.3, key slot 3 instead of 2 can be used for deciphering,
2822
   * but this has to be set via MSE beforehand on every usage (slot 2 is used by default)
2823
   * see section 7.2.18 of the specification of OpenPGP Card v3.3 */
2824
0
  if (priv->bcd_version >= OPENPGP_CARD_3_3 && env->key_ref[0] == 0x02){
2825
0
    pgp_set_MSE(card, 3, 0xb8);
2826
0
  }
2827
2828
0
  r = sc_transmit_apdu(card, &apdu);
2829
0
  free(temp);
2830
0
  LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
2831
2832
0
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
2833
0
  LOG_TEST_RET(card->ctx, r, "Card returned error");
2834
2835
  /* For OpenPGP Card >=v3.3, use key slot 2 for deciphering again (set to default) */
2836
0
  if (priv->bcd_version >= OPENPGP_CARD_3_3 && env->key_ref[0] == 0x02){
2837
0
    pgp_set_MSE(card, 2, 0xb8);
2838
0
  }
2839
2840
0
  LOG_FUNC_RETURN(card->ctx, (int)apdu.resplen);
2841
0
}
2842
2843
2844
#ifdef ENABLE_OPENSSL
2845
/**
2846
 * Internal: update algorithm attribute for new key size (before generating key).
2847
 **/
2848
static int
2849
pgp_update_new_algo_attr(sc_card_t *card, sc_cardctl_openpgp_key_gen_store_info_t *key_info)
2850
0
{
2851
0
  struct pgp_priv_data *priv = DRVDATA(card);
2852
0
  pgp_blob_t *algo_blob = NULL;
2853
0
  const unsigned int tag = 0x00C0 | key_info->key_id;
2854
0
  int r = SC_SUCCESS;
2855
0
  unsigned int i;
2856
2857
0
  LOG_FUNC_CALLED(card->ctx);
2858
2859
0
  r = pgp_seek_blob(card, priv->mf, tag, &algo_blob);
2860
0
  LOG_TEST_RET(card->ctx, r, "Cannot get old algorithm attributes");
2861
2862
0
  if (priv->ext_caps & EXT_CAP_ALG_ATTR_CHANGEABLE) {
2863
    /* ECDSA and ECDH */
2864
0
    if (key_info->algorithm == SC_OPENPGP_KEYALGO_ECDH
2865
0
        || key_info->algorithm == SC_OPENPGP_KEYALGO_ECDSA
2866
0
        || key_info->algorithm == SC_OPENPGP_KEYALGO_EDDSA){
2867
      /* Note OpenPGP or current cards do not support 448 size keys yet */
2868
0
      unsigned char *aoid = NULL; /* ASN1 */
2869
0
      size_t aoid_len;
2870
0
      struct sc_object_id *scoid = NULL;
2871
2872
0
      scoid = &key_info->u.ec.oid;
2873
      /*
2874
       * Current OpenPGP cards use pre RFC8410 OIDs for ECDH and EdDSA
2875
       * so convert to older versions of the OIDs.
2876
       */
2877
0
      for (i = 0; ec_curves_alt[i].size > 0; i++) {
2878
0
        if (sc_compare_oid(scoid, &ec_curves_alt[i].oid_alt)) {
2879
0
          scoid = &ec_curves_alt[i].oid;
2880
0
          break;
2881
0
        }
2882
0
      }
2883
2884
0
      r = sc_encode_oid(card->ctx, scoid, &aoid, &aoid_len);
2885
0
      LOG_TEST_RET(card->ctx, r, "invalid ec oid");
2886
0
      if (aoid == NULL || aoid_len < 3 || aoid[1] > 127) {
2887
0
        free(aoid);
2888
0
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
2889
0
      }
2890
2891
0
      key_info->data_len = aoid_len + 1 - 2; /* +1 for algorithm -2 drop 06 len */
2892
0
      key_info->data = malloc(key_info->data_len);
2893
0
      if (!key_info->data) {
2894
0
        free(aoid);
2895
0
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ENOUGH_MEMORY);
2896
0
      }
2897
2898
0
      key_info->data[0] = key_info->algorithm;
2899
0
      for (i = 0; i < aoid_len - 2; i++)
2900
0
        key_info->data[i + 1] = aoid[i + 2];
2901
2902
0
      free(aoid);
2903
0
    }
2904
2905
    /* RSA */
2906
0
    else if (key_info->algorithm == SC_OPENPGP_KEYALGO_RSA){
2907
2908
      /* We can not rely on previous key attributes anymore, as it might be ECC */
2909
0
      if (key_info->u.rsa.exponent_len == 0 || key_info->u.rsa.modulus_len == 0)
2910
0
        LOG_FUNC_RETURN(card->ctx,SC_ERROR_INVALID_ARGUMENTS);
2911
2912
0
      key_info->data_len = 6;
2913
0
      key_info->data = malloc(key_info->data_len);
2914
0
      if (!key_info->data)
2915
0
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ENOUGH_MEMORY);
2916
2917
0
      key_info->data[0] = key_info->algorithm;
2918
0
      ushort2bebytes(key_info->data + 1, key_info->u.rsa.modulus_len);
2919
      /* OpenPGP Card only accepts 32bit as exponent length field,
2920
       * although you can import keys with smaller exponent;
2921
       * thus we don't change rsa.exponent_len, but ignore it here */
2922
0
      ushort2bebytes(key_info->data + 3, SC_OPENPGP_MAX_EXP_BITS);
2923
      /* Import-Format of private key (e,p,q) */
2924
0
      key_info->data[5] = SC_OPENPGP_KEYFORMAT_RSA_STD;
2925
0
    }
2926
0
    else {
2927
0
      sc_log(card->ctx, "Unknown algorithm id");
2928
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
2929
0
    }
2930
2931
0
    r = pgp_put_data(card, tag, key_info->data, key_info->data_len);
2932
    /* Note: pgp_put_data calls pgp_set_blob */
2933
0
    LOG_TEST_RET(card->ctx, r, "Cannot set new algorithm attributes");
2934
0
  } else {
2935
0
    sc_cardctl_openpgp_key_gen_store_info_t old_key_info;
2936
2937
0
    if (pgp_parse_algo_attr_blob(card, algo_blob, &old_key_info) != SC_SUCCESS
2938
0
        || old_key_info.algorithm != key_info->algorithm)
2939
0
      LOG_TEST_RET(card->ctx, SC_ERROR_NO_CARD_SUPPORT,
2940
0
          "Requested algorithm not supported");
2941
    /* FIXME check whether the static parameters match the requested ones. */
2942
0
  }
2943
2944
0
  LOG_FUNC_RETURN(card->ctx, r);
2945
0
}
2946
2947
2948
/**
2949
 * Internal: store creation time of key.
2950
 * Pass non-zero outtime to use predefined time.
2951
 * Pass zero/null outtime to calculate current time. outtime then will be output.
2952
 * Pass null outtime to not receive output.
2953
 **/
2954
static int
2955
pgp_store_creationtime(sc_card_t *card, u8 key_id, time_t *outtime)
2956
0
{
2957
0
  int r;
2958
0
  time_t createtime = 0;
2959
0
  const size_t timestrlen = 64;
2960
0
  char timestring[65];
2961
0
  u8 buf[4];
2962
0
  struct tm tm;
2963
2964
0
  LOG_FUNC_CALLED(card->ctx);
2965
2966
0
  if (key_id < 1 || key_id > 3)
2967
0
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2968
0
        "Invalid key ID; must be 1, 2, or 3");
2969
2970
0
  if (outtime != NULL && *outtime != 0)
2971
0
    createtime = *outtime;
2972
0
  else if (outtime != NULL)
2973
    /* set output */
2974
0
    *outtime = createtime = time(NULL);
2975
2976
#ifdef _WIN32
2977
  if (0 != gmtime_s(&tm, &createtime))
2978
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
2979
#else
2980
0
  if (NULL == gmtime_r(&createtime, &tm))
2981
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
2982
0
#endif
2983
0
  strftime(timestring, timestrlen, "%c %Z", &tm);
2984
0
  sc_log(card->ctx, "Creation time %s.", timestring);
2985
  /* Code borrowed from GnuPG */
2986
0
  ulong2bebytes(buf, (unsigned long)createtime);
2987
0
  r = pgp_put_data(card, 0x00CD + key_id, buf, 4);
2988
0
  LOG_TEST_RET(card->ctx, r, "Cannot write to DO");
2989
0
  LOG_FUNC_RETURN(card->ctx, r);
2990
0
}
2991
2992
2993
/**
2994
 * Internal: calculate and store PGP fingerprints.
2995
 * Reference: GnuPG, app-openpgp.c.
2996
 **/
2997
static int
2998
pgp_calculate_and_store_fingerprint(sc_card_t *card, time_t ctime,
2999
    sc_cardctl_openpgp_key_gen_store_info_t *key_info)
3000
0
{
3001
0
  u8 fingerprint[SHA_DIGEST_LENGTH];
3002
0
  u8 *fp_buffer = NULL;  /* fingerprint buffer, not hashed */
3003
0
  size_t fp_buffer_len;
3004
0
  u8 *p; /* use this pointer to set fp_buffer content */
3005
0
  size_t pk_packet_len;
3006
0
  unsigned int tag = 0x00C6 + key_info->key_id;
3007
0
  pgp_blob_t *fpseq_blob = NULL;
3008
0
  u8 *newdata = NULL;
3009
0
  int r;
3010
3011
0
  LOG_FUNC_CALLED(card->ctx);
3012
3013
  /* constructing public-key packet length */
3014
  /* RSA */
3015
0
  if (key_info->algorithm == SC_OPENPGP_KEYALGO_RSA) {
3016
3017
0
    if (key_info->u.rsa.modulus == NULL
3018
0
      || key_info->u.rsa.exponent == NULL
3019
0
      || (key_info->u.rsa.modulus_len) == 0
3020
0
      || (key_info->u.rsa.exponent_len) == 0) {
3021
3022
0
      sc_log(card->ctx, "Null data (modulus or exponent)");
3023
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
3024
0
    }
3025
3026
    /* https://tools.ietf.org/html/rfc4880  page 41, 72 */
3027
0
    pk_packet_len =   1   /* version number */
3028
0
        + 4   /* creation time */
3029
0
        + 1   /* algorithm */
3030
0
        + 2   /* algorithm-specific fields: RSA modulus+exponent */
3031
0
        + (BYTES4BITS(key_info->u.rsa.modulus_len))
3032
0
        + 2
3033
0
        + (BYTES4BITS(key_info->u.rsa.exponent_len));
3034
3035
0
  }
3036
  /* ECC */
3037
0
  else if (key_info->algorithm == SC_OPENPGP_KEYALGO_ECDH || /* also includes XEDDSA */
3038
0
      key_info->algorithm == SC_OPENPGP_KEYALGO_ECDSA ||
3039
0
      key_info->algorithm == SC_OPENPGP_KEYALGO_EDDSA) {
3040
0
    if (key_info->u.ec.ecpointQ == NULL || (key_info->u.ec.ecpointQ_len) == 0) {
3041
0
      sc_log(card->ctx, "Error: ecpoint required!");
3042
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
3043
0
    }
3044
3045
    /* https://tools.ietf.org/html/rfc4880  page 41, 72
3046
     * and https://tools.ietf.org/html/rfc6637 section 9 (page 8 and 9) */
3047
0
    pk_packet_len = 1            /* version number */
3048
0
        + 4            /* creation time */
3049
0
        + 1            /* algorithm */
3050
0
        + 1            /* oid len */
3051
0
        + key_info->u.ec.oidv_len      /* oid */
3052
0
        + key_info->u.ec.ecpointQ_len; /* ecpoint */
3053
3054
    /* KDF parameters for ECDH */
3055
0
    if (key_info->algorithm == SC_OPENPGP_KEYALGO_ECDH) {
3056
      /* https://tools.ietf.org/html/rfc6637#section-8 */
3057
0
      pk_packet_len +=   1  /* number of bytes */
3058
0
           + 1  /* version number */
3059
0
           + 1  /* KDF algo */
3060
0
           + 1; /* KEK algo */
3061
0
    }
3062
0
  } else
3063
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
3064
0
  sc_log(card->ctx, "pk_packet_len is %zu", pk_packet_len);
3065
3066
0
  fp_buffer_len = 3 + pk_packet_len;
3067
0
  p = fp_buffer = calloc(1, fp_buffer_len);
3068
0
  if (p == NULL)
3069
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ENOUGH_MEMORY);
3070
3071
  /* constructing public-key packet */
3072
0
  p[0] = 0x99;   /* http://tools.ietf.org/html/rfc4880  page 71 */
3073
0
  ushort2bebytes(++p, (unsigned short)pk_packet_len);
3074
  /* start pk_packet */
3075
0
  p += 2;
3076
0
  *p = 4;        /* Version 4 key */
3077
0
  ulong2bebytes(++p, (unsigned long)ctime);    /* Creation time */
3078
0
  p += 4;
3079
3080
  /* RSA */
3081
0
  if (key_info->algorithm == SC_OPENPGP_KEYALGO_RSA) {
3082
0
    unsigned short bytes_length = 0;
3083
3084
0
    *p = 1; /* Algorithm ID, RSA */
3085
0
    p += 1;
3086
3087
    /* Modulus */
3088
0
    bytes_length = BYTES4BITS(key_info->u.rsa.modulus_len);
3089
0
    ushort2bebytes(p, (unsigned short)key_info->u.rsa.modulus_len);
3090
0
    p += 2;
3091
0
    memcpy(p, key_info->u.rsa.modulus, bytes_length);
3092
0
    p += bytes_length;
3093
3094
    /* Exponent */
3095
0
    bytes_length = BYTES4BITS(key_info->u.rsa.exponent_len);
3096
0
    ushort2bebytes(p, (unsigned short)key_info->u.rsa.exponent_len);
3097
0
    p += 2;
3098
0
    memcpy(p, key_info->u.rsa.exponent, bytes_length);
3099
0
  }
3100
  /* ECC */
3101
0
  else if (key_info->algorithm == SC_OPENPGP_KEYALGO_ECDH || /* includes XEDDSA */
3102
0
      key_info->algorithm == SC_OPENPGP_KEYALGO_ECDSA ||
3103
0
      key_info->algorithm == SC_OPENPGP_KEYALGO_EDDSA) {
3104
    /* Algorithm ID, see https://tools.ietf.org/html/rfc6637#section-5 */
3105
0
    *p = key_info->algorithm + 6;
3106
0
    p += 1;
3107
0
    *p = key_info->u.ec.oidv_len;
3108
0
    p += 1;
3109
0
    memcpy(p, key_info->u.ec.oidv.value, key_info->u.ec.oidv_len);
3110
0
    p += key_info->u.ec.oidv_len;
3111
0
    memcpy(p, key_info->u.ec.ecpointQ, key_info->u.ec.ecpointQ_len);
3112
3113
    /* KDF parameters for ECDH */
3114
0
    if (key_info->algorithm == SC_OPENPGP_KEYALGO_ECDH) {
3115
      /* https://tools.ietf.org/html/rfc6637#section-8
3116
       * This is copied from GnuPG's ecdh_params() function in app-openpgp.c */
3117
0
      p += BYTES4BITS(key_info->u.ec.ecpointQ_len);
3118
0
      *p = 0x03; /* number of bytes following */
3119
0
      p += 1;
3120
0
      *p = 0x01; /* version of this format */
3121
0
      p += 1;
3122
0
      if (key_info->u.ec.key_length <= 256) { /* ec bit size <= 256 */
3123
0
        *p = 0x08;  /* KDF algo */
3124
0
        *(p+1) = 0x07;  /* KEK algo */
3125
0
      } else if (key_info->u.ec.key_length <= 384) { /* ec bit size <= 384 */
3126
0
        *p = 0x09;  /* KDF algo */
3127
0
        *(p+1) = 0x08;  /* KEK algo */
3128
0
      } else {   /* ec bit size = 512 or 521*/
3129
0
        *p = 0x0a;  /* KDF algo */
3130
0
        *(p+1) = 0x09;  /* KEK algo */
3131
0
      }
3132
0
    }
3133
0
  } else
3134
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
3135
3136
0
  p = NULL;
3137
3138
  /* hash with SHA-1 */
3139
0
  SHA1(fp_buffer, fp_buffer_len, fingerprint);
3140
0
  free(fp_buffer);
3141
3142
  /* store to DO */
3143
0
  sc_log(card->ctx, "Writing to DO %04X.", tag);
3144
0
  r = pgp_put_data(card, tag, fingerprint, SHA_DIGEST_LENGTH);
3145
0
  LOG_TEST_RET(card->ctx, r, "Cannot write to DO");
3146
3147
  /* update the blob containing fingerprints (00C5) */
3148
0
  sc_log(card->ctx, "Updating fingerprint blob 00C5.");
3149
0
  fpseq_blob = pgp_find_blob(card, 0x00C5);
3150
0
  if (fpseq_blob == NULL) {
3151
0
    r = SC_ERROR_OUT_OF_MEMORY;
3152
0
    LOG_TEST_GOTO_ERR(card->ctx, r, "Cannot find blob 00C5");
3153
0
  }
3154
0
  if (20U * key_info->key_id > fpseq_blob->len) {
3155
0
    r = SC_ERROR_OBJECT_NOT_VALID;
3156
0
    LOG_TEST_GOTO_ERR(card->ctx, r, "The 00C5 blob is not large enough");
3157
0
  }
3158
3159
  /* save the fingerprints sequence */
3160
0
  newdata = malloc(fpseq_blob->len);
3161
0
  if (newdata == NULL) {
3162
0
    r = SC_ERROR_OUT_OF_MEMORY;
3163
0
    LOG_TEST_GOTO_ERR(card->ctx, r, "Not enough memory to update fingerprint blob 00C5");
3164
0
  }
3165
3166
0
  memcpy(newdata, fpseq_blob->data, fpseq_blob->len);
3167
  /* move p to the portion holding the fingerprint of the current key */
3168
0
  p = newdata + 20 * (key_info->key_id - 1);
3169
  /* copy new fingerprint value */
3170
0
  memcpy(p, fingerprint, 20);
3171
  /* set blob's data */
3172
0
  pgp_set_blob(fpseq_blob, newdata, fpseq_blob->len);
3173
0
  free(newdata);
3174
3175
0
err:
3176
0
  LOG_FUNC_RETURN(card->ctx, r);
3177
0
}
3178
3179
3180
/**
3181
 * Internal: update pubkey blob.
3182
 * Note that modulus_len, exponent_len is measured in bit.
3183
 **/
3184
static int
3185
pgp_update_pubkey_blob(sc_card_t *card, sc_cardctl_openpgp_key_gen_store_info_t *key_info)
3186
0
{
3187
0
  struct pgp_priv_data *priv = DRVDATA(card);
3188
0
  pgp_blob_t *pk_blob;
3189
0
  unsigned int blob_id = 0;
3190
0
  sc_pkcs15_pubkey_t p15pubkey;
3191
0
  u8 *data = NULL;
3192
0
  size_t len;
3193
0
  int r;
3194
3195
0
  LOG_FUNC_CALLED(card->ctx);
3196
3197
0
  if (key_info->key_id == SC_OPENPGP_KEY_SIGN)
3198
0
    blob_id = DO_SIGN_SYM;
3199
0
  else if (key_info->key_id == SC_OPENPGP_KEY_ENCR)
3200
0
    blob_id = DO_ENCR_SYM;
3201
0
  else if (key_info->key_id == SC_OPENPGP_KEY_AUTH)
3202
0
    blob_id = DO_AUTH_SYM;
3203
0
  else {
3204
0
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
3205
0
        "Invalid key ID; must be 1, 2, or 3");
3206
0
  }
3207
3208
0
  sc_log(card->ctx, "Retrieving blob %04X.", blob_id);
3209
0
  r = pgp_get_blob(card, priv->mf, blob_id, &pk_blob);
3210
0
  LOG_TEST_RET(card->ctx, r, "Cannot get the blob");
3211
3212
  /* encode pubkey */
3213
  /* RSA */
3214
0
  if (key_info->algorithm == SC_OPENPGP_KEYALGO_RSA){
3215
0
    memset(&p15pubkey, 0, sizeof(p15pubkey));
3216
0
    p15pubkey.algorithm = SC_ALGORITHM_RSA;
3217
0
    p15pubkey.u.rsa.modulus.data  = key_info->u.rsa.modulus;
3218
0
    p15pubkey.u.rsa.modulus.len   = BYTES4BITS(key_info->u.rsa.modulus_len);
3219
0
    p15pubkey.u.rsa.exponent.data = key_info->u.rsa.exponent;
3220
0
    p15pubkey.u.rsa.exponent.len  = BYTES4BITS(key_info->u.rsa.exponent_len);
3221
0
  }
3222
  /* ECC */
3223
0
  else if (key_info->algorithm == SC_OPENPGP_KEYALGO_ECDH || /* includes XEDDSA */
3224
0
      key_info->algorithm == SC_OPENPGP_KEYALGO_ECDSA ||
3225
0
      key_info->algorithm == SC_OPENPGP_KEYALGO_EDDSA) {
3226
0
    memset(&p15pubkey, 0, sizeof(p15pubkey));
3227
0
    p15pubkey.algorithm = key_info->key_type;
3228
0
    p15pubkey.u.ec.ecpointQ.value = key_info->u.ec.ecpointQ;
3229
0
    p15pubkey.u.ec.ecpointQ.len = key_info->u.ec.ecpointQ_len;
3230
0
  } else
3231
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
3232
3233
0
  r = sc_pkcs15_encode_pubkey_as_spki(card->ctx, &p15pubkey, &data, &len);
3234
  /*
3235
   * key_info is missing an algo_id. sc_pkcs15_encode_pubkey_as_spki
3236
   * allocates one. Free it here.
3237
   */
3238
0
  free(p15pubkey.alg_id);
3239
0
  p15pubkey.alg_id = NULL;
3240
0
  LOG_TEST_RET(card->ctx, r, "Cannot encode pubkey");
3241
3242
0
  sc_log(card->ctx, "Updating blob %04X's content.", blob_id);
3243
0
  r = pgp_set_blob(pk_blob, data, len);
3244
0
  free(data);
3245
0
  LOG_TEST_RET(card->ctx, r, "Cannot update blob content");
3246
0
  LOG_FUNC_RETURN(card->ctx, r);
3247
0
}
3248
3249
3250
/**
3251
 * Internal: parse response data and set output
3252
 **/
3253
static int
3254
pgp_parse_and_set_pubkey_output(sc_card_t *card, u8 *data, size_t data_len,
3255
    sc_cardctl_openpgp_key_gen_store_info_t *key_info)
3256
0
{
3257
0
  time_t ctime = 0;
3258
0
  u8 *in = data;
3259
0
  int r;
3260
0
  LOG_FUNC_CALLED(card->ctx);
3261
3262
  /* store creation time */
3263
0
  r = pgp_store_creationtime(card, key_info->key_id, &ctime);
3264
0
  if (r != SC_SUCCESS) {
3265
    /* TODO for now with GNUK at least, log but do not return error */
3266
0
    sc_log(card->ctx, "Cannot store creation time");
3267
0
  }
3268
3269
  /* parse response. Ref: pgp_enumerate_blob() */
3270
0
  while (data_len > (size_t) (in - data)) {
3271
0
    unsigned int cla, tag, tmptag;
3272
0
    size_t    len;
3273
0
    u8  *part = in;
3274
3275
    /* parse TLV structure */
3276
0
    r = sc_asn1_read_tag((const u8**)&part, data_len - (in - data), &cla, &tag, &len);
3277
0
    if (part == NULL)
3278
0
      r = SC_ERROR_ASN1_OBJECT_NOT_FOUND;
3279
0
    LOG_TEST_RET(card->ctx, r, "Unexpected end of contents");
3280
    /* undo ASN1's split of tag & class */
3281
0
    for (tmptag = tag; tmptag > 0x0FF; tmptag >>= 8) {
3282
0
      cla <<= 8;
3283
0
    }
3284
0
    tag |= cla;
3285
3286
    /* RSA modulus */
3287
0
    if (tag == 0x0081) {
3288
0
      if (key_info->algorithm != SC_OPENPGP_KEYALGO_RSA) {
3289
0
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
3290
0
      }
3291
0
      if ((BYTES4BITS(key_info->u.rsa.modulus_len) < len)  /* modulus_len is in bits */
3292
0
        || key_info->u.rsa.modulus == NULL) {
3293
3294
0
        free(key_info->u.rsa.modulus);
3295
0
        key_info->u.rsa.modulus = malloc(len);
3296
0
        if (key_info->u.rsa.modulus == NULL)
3297
0
          LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ENOUGH_MEMORY);
3298
0
      }
3299
3300
      /* set values */
3301
0
      memcpy(key_info->u.rsa.modulus, part, len);
3302
0
      key_info->u.rsa.modulus_len = len * 8; /* store length in bits */
3303
0
    }
3304
    /* RSA public exponent */
3305
0
    else if (tag == 0x0082) {
3306
0
      if (key_info->algorithm != SC_OPENPGP_KEYALGO_RSA) {
3307
0
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
3308
0
      }
3309
0
      if ((BYTES4BITS(key_info->u.rsa.exponent_len) < len)  /* exponent_len is in bits */
3310
0
        || key_info->u.rsa.exponent == NULL) {
3311
3312
0
        free(key_info->u.rsa.exponent);
3313
0
        key_info->u.rsa.exponent = malloc(len);
3314
0
        if (key_info->u.rsa.exponent == NULL)
3315
0
          LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ENOUGH_MEMORY);
3316
0
      }
3317
3318
      /* set values */
3319
0
      memcpy(key_info->u.rsa.exponent, part, len);
3320
0
      key_info->u.rsa.exponent_len = len * 8; /* store length in bits */
3321
0
    }
3322
    /* ECC or EDDSA public key */
3323
0
    else if (tag == 0x0086) {
3324
      /* Note: SC_OPENPGP_KEYALGO_ECDH could be either EC or XEDDSA */
3325
0
      if (key_info->algorithm != SC_OPENPGP_KEYALGO_ECDSA &&
3326
0
          key_info->algorithm != SC_OPENPGP_KEYALGO_ECDH &&
3327
0
          key_info->algorithm != SC_OPENPGP_KEYALGO_EDDSA) {
3328
0
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
3329
0
      }
3330
      /* set the output data */
3331
      /* key_info->u.ec.ecpoint_len is already set based on
3332
       * key_info->key_type
3333
       * EC is in 04||x||y format i.e.
3334
       *    (field_length + 7)/8 * 2 + 1 in bytes
3335
       *    len is ecpoint length + format byte
3336
       *    see section 7.2.14 of 3.3.1 specs
3337
       * EDDSA and XEDDSA have no format byte and one number
3338
       *    (field_length + 7)/8 in bytes
3339
       */
3340
      /* GNUK returns 04||x||y */
3341
3342
0
      if (len != key_info->u.ec.ecpointQ_len)
3343
0
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
3344
3345
0
      switch (key_info->key_type) {
3346
0
      case SC_ALGORITHM_EC:
3347
0
      case SC_ALGORITHM_EDDSA:
3348
0
      case SC_ALGORITHM_XEDDSA:
3349
0
        key_info->u.ec.ecpointQ = malloc(len);
3350
0
        if (key_info->u.ec.ecpointQ == NULL)
3351
0
          LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ENOUGH_MEMORY);
3352
0
        memcpy(key_info->u.ec.ecpointQ, part, len);
3353
0
        key_info->u.ec.ecpointQ_len = len;
3354
0
        break;
3355
0
      default:
3356
0
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
3357
0
      }
3358
0
    }
3359
3360
    /* go to next part to parse */
3361
    /* This will be different from pgp_enumerate_blob() a bit */
3362
0
    in = part + ((tag != 0x7F49) ? len : 0);
3363
0
  }
3364
3365
  /* calculate and store fingerprint */
3366
0
  sc_log(card->ctx, "Calculate and store fingerprint");
3367
0
  r = pgp_calculate_and_store_fingerprint(card, ctime, key_info);
3368
0
  LOG_TEST_RET(card->ctx, r, "Cannot store fingerprint");
3369
  /* TODO only try and update pubkey if present */
3370
3371
  /* update pubkey blobs (B601, B801, A401) */
3372
0
  sc_log(card->ctx, "Update blobs holding pubkey info.");
3373
0
  r = pgp_update_pubkey_blob(card, key_info);
3374
3375
0
  LOG_FUNC_RETURN(card->ctx, r);
3376
0
}
3377
3378
3379
/**
3380
 * Internal: update card->algorithms
3381
 */
3382
static int
3383
pgp_update_card_algorithms(sc_card_t *card, sc_cardctl_openpgp_key_gen_store_info_t *key_info)
3384
0
{
3385
0
  sc_algorithm_info_t *algo;
3386
0
  u8 id = key_info->key_id;
3387
0
  struct pgp_priv_data *priv = DRVDATA(card);
3388
3389
0
  LOG_FUNC_CALLED(card->ctx);
3390
3391
  /* protect incompatible cards against non-RSA */
3392
0
  if (key_info->algorithm != SC_OPENPGP_KEYALGO_RSA &&
3393
0
      priv->bcd_version < OPENPGP_CARD_3_0 &&
3394
0
      card->type != SC_CARD_TYPE_OPENPGP_GNUK)
3395
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
3396
3397
0
  if (id > card->algorithm_count) {
3398
0
    sc_log(card->ctx,
3399
0
           "This key ID %u is out of the card's algorithm list.",
3400
0
           (unsigned int)id);
3401
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
3402
0
  }
3403
3404
  /* get the algorithm corresponding to the key ID */
3405
0
  algo = card->algorithms + (id - 1);
3406
  /* update new key attribute */
3407
0
  if (key_info->algorithm == SC_OPENPGP_KEYALGO_RSA) {
3408
0
    algo->algorithm = SC_ALGORITHM_RSA;
3409
0
    algo->key_length = (unsigned int)key_info->u.rsa.modulus_len;
3410
0
  } else if (key_info->algorithm == SC_OPENPGP_KEYALGO_ECDH || /* includes XEDDSA */
3411
0
      key_info->algorithm == SC_OPENPGP_KEYALGO_ECDSA ||
3412
0
      key_info->algorithm == SC_OPENPGP_KEYALGO_EDDSA) {
3413
0
    algo->algorithm = SC_ALGORITHM_EC;
3414
0
    algo->key_length = (unsigned int)((key_info->u.ec.ecpointQ_len));
3415
0
  } else
3416
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
3417
3418
0
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
3419
0
}
3420
3421
3422
/**
3423
 * ABI (card ctl): GENERATE ASYMMETRIC KEY PAIR
3424
 **/
3425
static int
3426
pgp_gen_key(sc_card_t *card, sc_cardctl_openpgp_key_gen_store_info_t *key_info)
3427
0
{
3428
0
  sc_apdu_t apdu;
3429
  /* temporary variables to hold APDU params */
3430
0
  u8 apdu_case;
3431
0
  u8 apdu_data[2] = { 0x00, 0x00 };
3432
0
  size_t apdu_le;
3433
0
  size_t resplen = 0;
3434
0
  int r = SC_SUCCESS;
3435
0
  struct pgp_priv_data *priv = DRVDATA(card);
3436
3437
0
  LOG_FUNC_CALLED(card->ctx);
3438
3439
  /* protect incompatible cards against non-RSA */
3440
0
  if (key_info->algorithm != SC_OPENPGP_KEYALGO_RSA &&
3441
0
      priv->bcd_version < OPENPGP_CARD_3_0 &&
3442
0
      card->type != SC_CARD_TYPE_OPENPGP_GNUK)
3443
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
3444
3445
  /* set Control Reference Template for key */
3446
0
  if (key_info->key_id == SC_OPENPGP_KEY_SIGN)
3447
0
    ushort2bebytes(apdu_data, DO_SIGN);
3448
0
  else if (key_info->key_id == SC_OPENPGP_KEY_ENCR)
3449
0
    ushort2bebytes(apdu_data, DO_ENCR);
3450
0
  else if (key_info->key_id == SC_OPENPGP_KEY_AUTH)
3451
0
    ushort2bebytes(apdu_data, DO_AUTH);
3452
0
  else {
3453
0
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
3454
0
        "Invalid key ID; must be 1, 2, or 3");
3455
0
  }
3456
3457
  /* set attributes for new-generated key */
3458
0
  r = pgp_update_new_algo_attr(card, key_info);
3459
0
  LOG_TEST_RET(card->ctx, r, "Cannot set attributes for new-generated key");
3460
3461
  /* Test whether we will need extended APDU. 1900 is an
3462
   * arbitrary modulus length which for sure fits into a short APDU.
3463
   * This idea is borrowed from GnuPG code.  */
3464
0
  if (card->caps & SC_CARD_CAP_APDU_EXT
3465
0
    && key_info->u.rsa.modulus_len > 1900
3466
0
    && card->type != SC_CARD_TYPE_OPENPGP_GNUK) {
3467
    /* We won't store to apdu variable yet, because it will be reset in
3468
     * sc_format_apdu() */
3469
0
    apdu_le = card->max_recv_size;
3470
0
    apdu_case = SC_APDU_CASE_4_EXT;
3471
0
  }
3472
0
  else {
3473
0
    apdu_case = SC_APDU_CASE_4_SHORT;
3474
0
    apdu_le = 256;
3475
0
    resplen = MAXLEN_RESP_PUBKEY;
3476
0
  }
3477
0
  if (card->type == SC_CARD_TYPE_OPENPGP_GNUK) {
3478
0
    resplen = MAXLEN_RESP_PUBKEY_GNUK;
3479
0
  }
3480
3481
  /* prepare APDU */
3482
0
  sc_format_apdu(card, &apdu, apdu_case, 0x47, 0x80, 0);
3483
0
  apdu.data = apdu_data;
3484
0
  apdu.datalen = sizeof(apdu_data);
3485
0
  apdu.lc = sizeof(apdu_data);
3486
0
  apdu.le = apdu_le;
3487
3488
  /* buffer to receive response */
3489
0
  apdu.resplen = (resplen > 0) ? resplen : apdu_le;
3490
0
  apdu.resp = calloc(1, apdu.resplen);
3491
0
  if (apdu.resp == NULL) {
3492
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ENOUGH_MEMORY);
3493
0
  }
3494
3495
  /* send */
3496
0
  sc_log(card->ctx, "Waiting for the card to generate key...");
3497
0
  r = sc_transmit_apdu(card, &apdu);
3498
0
  sc_log(card->ctx, "Card has done key generation.");
3499
0
  LOG_TEST_GOTO_ERR(card->ctx, r, "APDU transmit failed");
3500
3501
  /* check response */
3502
0
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
3503
  /* instruct more in case of error */
3504
0
  if (r == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {
3505
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Please verify PIN first.");
3506
0
    goto err;
3507
0
  }
3508
0
  LOG_TEST_GOTO_ERR(card->ctx, r, "Card returned error");
3509
3510
  /* parse response data and set output */
3511
0
  r = pgp_parse_and_set_pubkey_output(card, apdu.resp, apdu.resplen, key_info);
3512
0
  LOG_TEST_GOTO_ERR(card->ctx, r, "Failed to parse pubkey output");
3513
0
  r = pgp_update_card_algorithms(card, key_info);
3514
3515
0
err:
3516
0
  free(apdu.resp);
3517
0
  LOG_FUNC_RETURN(card->ctx, r);
3518
0
}
3519
3520
3521
/**
3522
 * Internal: build TLV.
3523
 *
3524
 * FIXME use `sc_asn1_put_tag` or similar instead
3525
 *
3526
 * @param[in]  data   The data ("value") part to build TLV.
3527
 * @param[in]  len    Data length
3528
 * @param[out] out    The buffer of overall TLV. This buffer should be freed later.
3529
 * @param[out] outlen The length of buffer out.
3530
 **/
3531
static int
3532
pgp_build_tlv(sc_context_t *ctx, unsigned int tag, u8 *data, size_t len, u8 **out, size_t *outlen)
3533
0
{
3534
0
  u8 highest_order = 0;
3535
0
  int r;
3536
3537
0
  r = sc_asn1_write_element(ctx, tag, data, len, out, outlen);
3538
0
  LOG_TEST_RET(ctx, r, "Failed to write ASN.1 element");
3539
3540
  /* Restore class bits stripped by sc_asn1_write_element */
3541
  /* determine the leftmost byte of tag, which contains class bits */
3542
0
  while ((tag >> 8*highest_order) != 0) {
3543
0
    highest_order++;
3544
0
  }
3545
0
  if (highest_order != 0)
3546
0
    highest_order--;
3547
3548
  /* restore class bits in output */
3549
0
  if (highest_order < 4)
3550
0
    *out[0] |= (tag >> 8*highest_order);
3551
3552
0
  return SC_SUCCESS;
3553
0
}
3554
3555
3556
/**
3557
 * Internal: set Tag & Length components for TLV, store them in buffer.
3558
 *
3559
 * FIXME use `sc_asn1_put_tag` or similar instead
3560
 *
3561
 * Return the total length of Tag + Length.
3562
 * Note that the Value components is not counted.
3563
 * Ref: add_tlv() of GnuPG code.
3564
 **/
3565
static size_t
3566
set_taglength_tlv(u8 *buffer, unsigned int tag, size_t length)
3567
0
{
3568
0
  u8 *p = buffer;
3569
3570
0
  if (tag > 0xff)
3571
0
    *p++ = (tag >> 8) & 0xFF;
3572
0
  *p++ = tag;
3573
0
  if (length < 128)
3574
0
    *p++ = (u8)length;
3575
0
  else if (length < 256) {
3576
0
    *p++ = 0x81;
3577
0
    *p++ = (u8)length;
3578
0
  }
3579
0
  else {
3580
0
    if (length > 0xffff)
3581
0
      length = 0xffff;
3582
0
    *p++ = 0x82;
3583
0
    *p++ = (length >> 8) & 0xFF;
3584
0
    *p++ = length & 0xFF;
3585
0
  }
3586
3587
0
  return p - buffer;
3588
0
}
3589
3590
3591
/**
3592
 * Internal: build Extended Header list (sec 4.3.3.9 - OpenPGP card spec v.3)
3593
 **/
3594
static int
3595
pgp_build_extended_header_list(sc_card_t *card, sc_cardctl_openpgp_key_gen_store_info_t *key_info,
3596
    u8 **result, size_t *resultlen)
3597
0
{
3598
0
  sc_context_t *ctx = card->ctx;
3599
  /* Cardholder private key template (7F48) part */
3600
0
  const size_t max_prtem_len = 7*(1 + 3);     /* 7 components */
3601
                                              /* 1 for tag name (91, 92... 97)
3602
                                               * 3 for storing length */
3603
0
  u8 pritemplate[7*(1 + 3)];
3604
0
  size_t tpl_len = 0;     /* Actual size of pritemplate */
3605
  /* Concatenation of key data */
3606
0
  u8 kdata[3 + 256 + 256 + 512];  /* Exponent is stored in 3 bytes
3607
                                   * With maximum 4096-bit key,
3608
                                   * p and q can be stored in 256 bytes (2048 bits).
3609
                                   * Maximum 4096-bit modulus is stored in 512 bytes */
3610
0
  size_t kdata_len = 0;   /* Actual size of kdata */
3611
0
  u8 *tlvblock = NULL;
3612
0
  size_t tlvlen = 0;
3613
0
  u8 *tlv_5f48 = NULL;
3614
0
  size_t tlvlen_5f48 = 0;
3615
0
  u8 *tlv_7f48 = NULL;
3616
0
  size_t tlvlen_7f48 = 0;
3617
0
  u8 *data = NULL;
3618
0
  size_t len = 0;
3619
0
  u8 *p = NULL;
3620
0
  u8 *components[4];
3621
0
  size_t componentlens[4];
3622
0
  unsigned int componenttags[4];
3623
0
  char *componentnames[4];
3624
0
  size_t comp_to_add;
3625
0
  u8 i;
3626
0
  int r;
3627
3628
0
  LOG_FUNC_CALLED(ctx);
3629
3630
  /* RSA */
3631
0
  if (key_info->algorithm == SC_OPENPGP_KEYALGO_RSA){
3632
3633
0
    components[0] = key_info->u.rsa.exponent;
3634
0
    components[1] = key_info->u.rsa.p;
3635
0
    components[2] = key_info->u.rsa.q;
3636
0
    componentlens[0] = BYTES4BITS(key_info->u.rsa.exponent_len);
3637
0
    componentlens[1] = key_info->u.rsa.p_len;
3638
0
    componentlens[2] = key_info->u.rsa.q_len;
3639
0
    componenttags[0] = 0x91;
3640
0
    componenttags[1] = 0x92;
3641
0
    componenttags[2] = 0x93;
3642
0
    componentnames[0] = "public exponent";
3643
0
    componentnames[1] = "prime p";
3644
0
    componentnames[2] = "prime q";
3645
0
    comp_to_add = 3;
3646
3647
    /* The maximum exponent length is 32 bit, as set on card
3648
     * we use this variable to check against actual exponent_len */
3649
0
    size_t max_e_len_bytes = BYTES4BITS(SC_OPENPGP_MAX_EXP_BITS);
3650
0
    size_t e_len_bytes = BYTES4BITS(key_info->u.rsa.exponent_len);
3651
3652
0
    if (key_info->u.rsa.keyformat == SC_OPENPGP_KEYFORMAT_RSA_STDN
3653
0
      || key_info->u.rsa.keyformat == SC_OPENPGP_KEYFORMAT_RSA_CRTN){
3654
0
      components[3] = key_info->u.rsa.modulus;
3655
0
      componentlens[3] = key_info->u.rsa.modulus_len;
3656
0
      componenttags[3] = 0x97;
3657
0
      componentnames[3] = "modulus";
3658
0
      comp_to_add = 4;
3659
3660
      /* validate */
3661
0
      if (key_info->u.rsa.modulus == NULL || key_info->u.rsa.modulus_len == 0) {
3662
0
        sc_log(ctx, "Error: Modulus required!");
3663
0
        LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
3664
0
      }
3665
0
    }
3666
3667
    /* Cardholder private key template's data part */
3668
0
    memset(pritemplate, 0, max_prtem_len);
3669
3670
    /* maximum 32 bit exponent length allowed on OpenPGP Card */
3671
0
    if (key_info->u.rsa.exponent_len > SC_OPENPGP_MAX_EXP_BITS)
3672
0
      return SC_ERROR_INTERNAL;
3673
3674
    /* We need to right justify the exponent with allowed exponent length,
3675
     * e.g. from '01 00 01' to '00 01 00 01' */
3676
0
    if (key_info->u.rsa.exponent_len < SC_OPENPGP_MAX_EXP_BITS) {
3677
      /* create new buffer */
3678
0
      p = calloc(1, max_e_len_bytes);
3679
0
      if (!p)
3680
0
        LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_ENOUGH_MEMORY);
3681
3682
0
      memcpy(p + (max_e_len_bytes - e_len_bytes), key_info->u.rsa.exponent, e_len_bytes);
3683
      /* set key_info->u.rsa.e to new buffer */
3684
0
      free(key_info->u.rsa.exponent);
3685
0
      key_info->u.rsa.exponent = p;
3686
0
      components[0] = p;
3687
0
      key_info->u.rsa.exponent_len = SC_OPENPGP_MAX_EXP_BITS; /* we store info in bits */
3688
0
      componentlens[0] = max_e_len_bytes; /* ... but in bytes for header list */
3689
0
    }
3690
0
  }
3691
  /* ECC */
3692
0
  else if (key_info->algorithm == SC_OPENPGP_KEYALGO_ECDH || key_info->algorithm == SC_OPENPGP_KEYALGO_ECDSA || key_info->algorithm == SC_OPENPGP_KEYALGO_EDDSA) {
3693
0
    components[0] = key_info->u.ec.privateD;
3694
0
    componentlens[0] = key_info->u.ec.privateD_len;
3695
0
    componenttags[0] = 0x92;
3696
0
    componentnames[0] = "private key";
3697
0
    comp_to_add = 1;
3698
3699
    /* import public key as well */
3700
0
    if (key_info->u.ec.keyformat == SC_OPENPGP_KEYFORMAT_EC_STDPUB) {
3701
0
      components[1] = key_info->u.ec.ecpointQ;
3702
0
      componentlens[1] = key_info->u.ec.ecpointQ_len;
3703
0
      componenttags[1] = 0x99;
3704
0
      componentnames[1] = "public key";
3705
0
      comp_to_add = 2;
3706
3707
      /* validate */
3708
0
      if ((key_info->u.ec.ecpointQ == NULL || key_info->u.ec.ecpointQ_len == 0)) {
3709
0
        sc_log(ctx, "Error: ecpointQ required!");
3710
0
        LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
3711
0
      }
3712
0
    }
3713
3714
    /* Cardholder private key template's data part */
3715
0
    memset(pritemplate, 0, max_prtem_len);
3716
0
  } else
3717
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
3718
3719
  /* start from beginning of pritemplate */
3720
0
  p = pritemplate;
3721
3722
0
  for (i = 0; i < comp_to_add; i++) {
3723
0
    sc_log(ctx, "Set Tag+Length for %s (%X).", componentnames[i], componenttags[i]);
3724
0
    if (componenttags[i] > 0xffff) {
3725
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_DATA);
3726
0
    }
3727
0
    len = set_taglength_tlv(p, componenttags[i], componentlens[i]);
3728
0
    tpl_len += len;
3729
3730
0
    if (kdata_len + componentlens[i] > sizeof(kdata))
3731
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_DATA);
3732
    /*
3733
     *       <-- kdata_len --><--  Copy here  -->
3734
     * kdata |===============|___________________
3735
     */
3736
0
    memcpy(kdata + kdata_len, components[i], componentlens[i]);
3737
0
    kdata_len += componentlens[i];
3738
3739
    /* Move p to next part and build */
3740
0
    p += len;
3741
0
  }
3742
3743
  /* TODO: Components for CRT format */
3744
3745
  /* TLV block for 7F48 */
3746
0
  r = pgp_build_tlv(ctx, 0x7F48, pritemplate, tpl_len, &tlv_7f48, &tlvlen_7f48);
3747
0
  LOG_TEST_RET(ctx, r, "Failed to build TLV for 7F48");
3748
0
  tlv_7f48[0] |= 0x7F;
3749
0
  r = pgp_build_tlv(ctx, 0x5f48, kdata, kdata_len, &tlv_5f48, &tlvlen_5f48);
3750
0
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to build TLV for 5F48");
3751
3752
  /* data part's length for Extended Header list */
3753
0
  len = 2 + tlvlen_7f48 + tlvlen_5f48;
3754
  /* set data part content */
3755
0
  data = calloc(1, len);
3756
0
  if (data == NULL)
3757
0
    LOG_TEST_GOTO_ERR(ctx, SC_ERROR_NOT_ENOUGH_MEMORY, "Not enough memory");
3758
3759
0
  switch (key_info->key_id) {
3760
0
    case SC_OPENPGP_KEY_SIGN:
3761
0
      ushort2bebytes(data, DO_SIGN);
3762
0
      break;
3763
0
    case SC_OPENPGP_KEY_ENCR:
3764
0
      ushort2bebytes(data, DO_ENCR);
3765
0
      break;
3766
0
    case SC_OPENPGP_KEY_AUTH:
3767
0
      ushort2bebytes(data, DO_AUTH);
3768
0
      break;
3769
0
    default:
3770
0
      LOG_TEST_GOTO_ERR(ctx, SC_ERROR_INVALID_ARGUMENTS,
3771
0
            "Invalid key ID; must be 1, 2, or 3");
3772
0
  }
3773
0
  memcpy(data + 2, tlv_7f48, tlvlen_7f48);
3774
0
  memcpy(data + 2 + tlvlen_7f48, tlv_5f48, tlvlen_5f48);
3775
0
  r = pgp_build_tlv(ctx, 0x4D, data, len, &tlvblock, &tlvlen);
3776
0
  LOG_TEST_GOTO_ERR(ctx, r, "Cannot build TLV for Extended Header list");
3777
3778
  /* set output */
3779
0
  if (result != NULL) {
3780
0
    *result = tlvblock;
3781
0
    *resultlen = tlvlen;
3782
0
  } else {
3783
0
    free(tlvblock);
3784
0
  }
3785
3786
0
err:
3787
0
  free(data);
3788
0
  free(tlv_5f48);
3789
0
  free(tlv_7f48);
3790
0
  LOG_FUNC_RETURN(ctx, r);
3791
0
}
3792
3793
3794
/**
3795
 * ABI (card ctl): store key
3796
 **/
3797
static int
3798
pgp_store_key(sc_card_t *card, sc_cardctl_openpgp_key_gen_store_info_t *key_info)
3799
0
{
3800
0
  u8 *data = NULL;
3801
0
  size_t len = 0;
3802
0
  int r = 0;
3803
0
  int has_pubkey = 0, has_privkey = 0;
3804
0
  struct pgp_priv_data *priv = DRVDATA(card);
3805
3806
0
  LOG_FUNC_CALLED(card->ctx);
3807
3808
  /* PKCS11 loads privkey separately from pubkey as two different operations
3809
   * So this routine will be called twice to create two different objects.
3810
   * pkcs15init only calls once, with both.
3811
   * OpenPGP 4.3.1 says modulus and ecpointQ are optional when
3812
   * creating the extended header.
3813
   * So we can tell the difference and only do appropriate parts of this
3814
   * routine.
3815
   */
3816
3817
  /* protect incompatible cards against non-RSA */
3818
0
  if (key_info->algorithm != SC_OPENPGP_KEYALGO_RSA &&
3819
0
      priv->bcd_version < OPENPGP_CARD_3_0 &&
3820
0
      card->type != SC_CARD_TYPE_OPENPGP_GNUK)
3821
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
3822
3823
  /* Validate */
3824
0
  if (key_info->key_id < 1 || key_info->key_id > 3)
3825
0
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
3826
0
        "Invalid key ID; must be 1, 2, or 3");
3827
3828
  /* set algorithm attributes */
3829
  /* RSA */
3830
0
  if (key_info->algorithm == SC_OPENPGP_KEYALGO_RSA){
3831
0
    has_pubkey = (key_info->u.rsa.modulus && key_info->u.rsa.modulus_len &&
3832
0
        key_info->u.rsa.exponent && key_info->u.rsa.exponent_len);
3833
0
    has_privkey = (has_pubkey &&
3834
0
        key_info->u.rsa.p && key_info->u.rsa.p_len &&
3835
0
        key_info->u.rsa.q && key_info->u.rsa.q_len);
3836
3837
0
    if (!has_pubkey && !has_privkey)
3838
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
3839
3840
    /* we just support standard key format */
3841
0
    if (has_privkey) {
3842
0
      switch (key_info->u.rsa.keyformat) {
3843
0
      case SC_OPENPGP_KEYFORMAT_RSA_STD:
3844
0
      case SC_OPENPGP_KEYFORMAT_RSA_STDN:
3845
0
        break;
3846
3847
0
      case SC_OPENPGP_KEYFORMAT_RSA_CRT:
3848
0
      case SC_OPENPGP_KEYFORMAT_RSA_CRTN:
3849
0
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
3850
3851
0
      default:
3852
0
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
3853
0
      }
3854
0
    }
3855
3856
    /* we only support exponent of maximum 32 bits */
3857
0
    if (key_info->u.rsa.exponent_len > SC_OPENPGP_MAX_EXP_BITS) {
3858
0
      sc_log(card->ctx, "Exponent %zu-bit (>32) is not supported.",
3859
0
          key_info->u.rsa.exponent_len);
3860
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
3861
0
    }
3862
0
  }
3863
  /* ECC */
3864
0
  else if (key_info->algorithm == SC_OPENPGP_KEYALGO_ECDSA ||
3865
0
      key_info->algorithm == SC_OPENPGP_KEYALGO_ECDH || /* includes XEDDSA */
3866
0
      key_info->algorithm == SC_OPENPGP_KEYALGO_EDDSA) {
3867
0
    has_pubkey = (key_info->u.ec.ecpointQ && key_info->u.ec.ecpointQ_len);
3868
0
    has_privkey = (key_info->u.ec.privateD && key_info->u.ec.privateD_len);
3869
3870
0
    if (!has_pubkey && !has_privkey)
3871
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
3872
3873
0
    r = pgp_update_new_algo_attr(card, key_info);
3874
3875
0
    LOG_TEST_RET(card->ctx, r, "Failed to update new algorithm attributes");
3876
0
  }
3877
3878
0
  if (has_privkey) {
3879
    /* build Extended Header list */
3880
0
    r = pgp_build_extended_header_list(card, key_info, &data, &len);
3881
0
    LOG_TEST_GOTO_ERR(card->ctx, r, "Failed to build Extended Header list");
3882
3883
    /* write to DO */
3884
0
    r = pgp_put_data(card, 0x4D, data, len);
3885
0
    LOG_TEST_GOTO_ERR(card->ctx, r, "Failed to write to DO 004D");
3886
3887
    /* store creation time */
3888
0
    r = pgp_store_creationtime(card, key_info->key_id, &key_info->creationtime);
3889
0
    LOG_TEST_RET(card->ctx, r, "Cannot store creation time");
3890
0
  }
3891
3892
0
  if (has_pubkey) {
3893
    /* calculate and store fingerprint */
3894
0
    sc_log(card->ctx, "Calculate and store fingerprint");
3895
0
    r = pgp_calculate_and_store_fingerprint(card, key_info->creationtime, key_info);
3896
0
    LOG_TEST_RET(card->ctx, r, "Cannot store fingerprint");
3897
3898
    /* update pubkey blobs (B601,B801, A401) */
3899
0
    sc_log(card->ctx, "Update blobs holding pubkey info.");
3900
0
    r = pgp_update_pubkey_blob(card, key_info);
3901
3902
0
    sc_log(card->ctx, "Update card algorithms");
3903
0
    pgp_update_card_algorithms(card, key_info);
3904
0
  }
3905
3906
0
err:
3907
0
  free(data);
3908
0
  LOG_FUNC_RETURN(card->ctx, r);
3909
0
}
3910
3911
#endif /* ENABLE_OPENSSL */
3912
3913
3914
/**
3915
 * ABI (card ctl): erase card
3916
 **/
3917
static int
3918
pgp_erase_card(sc_card_t *card)
3919
0
{
3920
  /* Special series of commands to erase OpenPGP card,
3921
   * according to https://www.crypto-stick.com/en/faq
3922
   * (How to reset a Crypto Stick? question).
3923
   * Gnuk is known not to support this feature. */
3924
0
  const char *apdu_hex[] = {
3925
    /* block PIN1 */
3926
0
    "00:20:00:81:08:40:40:40:40:40:40:40:40",
3927
0
    "00:20:00:81:08:40:40:40:40:40:40:40:40",
3928
0
    "00:20:00:81:08:40:40:40:40:40:40:40:40",
3929
0
    "00:20:00:81:08:40:40:40:40:40:40:40:40",
3930
    /* block PIN3 */
3931
0
    "00:20:00:83:08:40:40:40:40:40:40:40:40",
3932
0
    "00:20:00:83:08:40:40:40:40:40:40:40:40",
3933
0
    "00:20:00:83:08:40:40:40:40:40:40:40:40",
3934
0
    "00:20:00:83:08:40:40:40:40:40:40:40:40",
3935
    /* TERMINATE */
3936
0
    "00:e6:00:00",
3937
0
    NULL
3938
0
  };
3939
0
  sc_apdu_t apdu;
3940
0
  int i;
3941
0
  int r = SC_SUCCESS;
3942
0
  struct pgp_priv_data *priv = DRVDATA(card);
3943
3944
0
  LOG_FUNC_CALLED(card->ctx);
3945
3946
0
  if ((priv->ext_caps & EXT_CAP_LCS) == 0) {
3947
0
    LOG_TEST_RET(card->ctx, SC_ERROR_NO_CARD_SUPPORT,
3948
0
        "Card does not offer life cycle management");
3949
0
  }
3950
3951
0
  switch (priv->state) {
3952
0
    case CARD_STATE_ACTIVATED:
3953
      /* iterate over the commands above */
3954
0
      for (i = 0; apdu_hex[i] != NULL; i++) {
3955
0
        u8 apdu_bin[25];  /* large enough to convert apdu_hex */
3956
0
        size_t apdu_bin_len = sizeof(apdu_bin);
3957
0
        u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
3958
3959
        /* convert hex array to bin array */
3960
0
        r = sc_hex_to_bin(apdu_hex[i], apdu_bin, &apdu_bin_len);
3961
0
        LOG_TEST_RET(card->ctx, r, "Failed to convert APDU bytes");
3962
3963
        /* build APDU from binary array */
3964
0
        r = sc_bytes2apdu(card->ctx, apdu_bin, apdu_bin_len, &apdu);
3965
0
        if (r)
3966
0
          LOG_TEST_RET(card->ctx, SC_ERROR_INTERNAL,
3967
0
              "Failed to build APDU");
3968
3969
0
        apdu.resp = rbuf;
3970
0
        apdu.resplen = sizeof(rbuf);
3971
3972
        /* send APDU to card */
3973
0
        sc_log(card->ctx, "Sending APDU%d %s", i, apdu_hex[i]);
3974
0
        r = sc_transmit_apdu(card, &apdu);
3975
0
        LOG_TEST_RET(card->ctx, r, "Transmitting APDU failed");
3976
0
      }
3977
      /* fall through */
3978
0
    case CARD_STATE_INITIALIZATION:
3979
0
      sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x44, 0, 0);
3980
0
      r = sc_transmit_apdu(card, &apdu);
3981
0
      LOG_TEST_RET(card->ctx, r, "Transmitting APDU failed");
3982
0
      break;
3983
0
    default:
3984
0
      LOG_TEST_RET(card->ctx, SC_ERROR_NO_CARD_SUPPORT,
3985
0
          "Card does not offer life cycle management");
3986
0
  }
3987
3988
0
  if (r == SC_SUCCESS && priv->mf) {
3989
0
    pgp_blob_t *new_mf = pgp_new_blob(card, NULL, priv->mf->id, priv->mf->file);
3990
0
    if (new_mf == NULL) {
3991
0
      LOG_TEST_RET(card->ctx, SC_ERROR_INTERNAL, "Failed to allocate the new MF blob");
3992
0
    }
3993
0
    priv->mf->file = NULL;
3994
3995
0
    pgp_free_blobs(priv->mf);
3996
0
    priv->mf = new_mf;
3997
0
    populate_blobs_to_mf(card, priv);
3998
0
  }
3999
4000
0
  LOG_FUNC_RETURN(card->ctx, r);
4001
0
}
4002
4003
4004
/**
4005
 * ABI: ISO 7816-9 CARD CTL - perform special card-specific operations.
4006
 */
4007
static int
4008
pgp_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
4009
0
{
4010
0
  int r;
4011
4012
0
  LOG_FUNC_CALLED(card->ctx);
4013
4014
0
  switch(cmd) {
4015
0
  case SC_CARDCTL_GET_SERIALNR:
4016
0
    memmove((sc_serial_number_t *) ptr, &card->serialnr, sizeof(card->serialnr));
4017
0
    LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
4018
0
    break;
4019
0
  case SC_CARDCTL_OPENPGP_SELECT_DATA:
4020
0
    r = pgp_select_data(card, *((u8 *) ptr));
4021
0
    LOG_FUNC_RETURN(card->ctx, r);
4022
0
    break;
4023
0
#ifdef ENABLE_OPENSSL
4024
0
  case SC_CARDCTL_OPENPGP_GENERATE_KEY:
4025
0
    r = pgp_gen_key(card, (sc_cardctl_openpgp_key_gen_store_info_t *)ptr);
4026
0
    LOG_FUNC_RETURN(card->ctx, r);
4027
0
    break;
4028
0
  case SC_CARDCTL_OPENPGP_STORE_KEY:
4029
0
    r = pgp_store_key(card, (sc_cardctl_openpgp_key_gen_store_info_t *)ptr);
4030
0
    LOG_FUNC_RETURN(card->ctx, r);
4031
0
    break;
4032
0
#endif /* ENABLE_OPENSSL */
4033
0
  case SC_CARDCTL_ERASE_CARD:
4034
0
    r = pgp_erase_card(card);
4035
0
    LOG_FUNC_RETURN(card->ctx, r);
4036
0
    break;
4037
0
  }
4038
4039
0
  LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
4040
0
}
4041
4042
4043
/**
4044
 * Internal: delete key (GnuK only).
4045
 */
4046
static int
4047
gnuk_delete_key(sc_card_t *card, u8 key_id)
4048
0
{
4049
0
  sc_context_t *ctx = card->ctx;
4050
0
  int r = SC_SUCCESS;
4051
0
  u8 data[4] = { 0x4D, 0x02, 0x00, 0x00 };
4052
4053
0
  LOG_FUNC_CALLED(ctx);
4054
4055
0
  if (key_id < 1 || key_id > 3)
4056
0
    LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS,
4057
0
        "Invalid key ID; must be 1, 2, or 3");
4058
4059
  /* delete fingerprint */
4060
0
  sc_log(ctx, "Delete fingerprints");
4061
0
  r = pgp_put_data(card, 0xC6 + key_id, NULL, 0);
4062
0
  LOG_TEST_RET(ctx, r, "Failed to delete fingerprints");
4063
  /* delete creation time */
4064
0
  sc_log(ctx, "Delete creation time");
4065
0
  r = pgp_put_data(card, 0xCD + key_id, NULL, 0);
4066
0
  LOG_TEST_RET(ctx, r, "Failed to delete creation time");
4067
4068
  /* rewrite Extended Header List */
4069
0
  sc_log(ctx, "Rewrite Extended Header List");
4070
4071
0
  if (key_id == SC_OPENPGP_KEY_SIGN)
4072
0
    ushort2bebytes(data+2, DO_SIGN);
4073
0
  else if (key_id == SC_OPENPGP_KEY_ENCR)
4074
0
    ushort2bebytes(data+2, DO_ENCR);
4075
0
  else if (key_id == SC_OPENPGP_KEY_AUTH)
4076
0
    ushort2bebytes(data+2, DO_AUTH);
4077
4078
0
  r = pgp_put_data(card, 0x4D, data, sizeof(data));
4079
4080
0
  LOG_FUNC_RETURN(ctx, r);
4081
0
}
4082
4083
4084
/**
4085
 * ABI: ISO 7816-9 DELETE FILE - delete EF or DF given.
4086
 */
4087
static int
4088
pgp_delete_file(sc_card_t *card, const sc_path_t *path)
4089
0
{
4090
0
  struct pgp_priv_data *priv = DRVDATA(card);
4091
0
  pgp_blob_t *blob;
4092
0
  sc_file_t *file;
4093
0
  int r;
4094
4095
0
  LOG_FUNC_CALLED(card->ctx);
4096
4097
  /* sc_pkcs15init_delete_by_path() sets the path type to SC_PATH_TYPE_FILE_ID */
4098
0
  r = pgp_select_file(card, path, &file);
4099
0
  LOG_TEST_RET(card->ctx, r, "Cannot select file");
4100
4101
  /* save "current" blob */
4102
0
  blob = priv->current;
4103
4104
  /* don't try to delete MF */
4105
0
  if (blob == priv->mf) {
4106
0
    sc_file_free(file);
4107
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
4108
0
  }
4109
4110
0
  if (card->type != SC_CARD_TYPE_OPENPGP_GNUK &&
4111
0
    (file->id == DO_SIGN_SYM || file->id == DO_ENCR_SYM || file->id == DO_AUTH_SYM)) {
4112
    /* These tags are just symbolic. We don't really delete them. */
4113
0
    r = SC_SUCCESS;
4114
0
  }
4115
0
  else if (card->type == SC_CARD_TYPE_OPENPGP_GNUK && file->id == DO_SIGN_SYM) {
4116
0
    r = gnuk_delete_key(card, 1);
4117
0
  }
4118
0
  else if (card->type == SC_CARD_TYPE_OPENPGP_GNUK && file->id == DO_ENCR_SYM) {
4119
0
    r = gnuk_delete_key(card, 2);
4120
0
  }
4121
0
  else if (card->type == SC_CARD_TYPE_OPENPGP_GNUK && file->id == DO_AUTH_SYM) {
4122
0
    r = gnuk_delete_key(card, 3);
4123
0
  }
4124
0
  else {
4125
    /* call pgp_put_data() with zero-sized NULL-buffer to zap the DO contents */
4126
0
    r = pgp_put_data(card, file->id, NULL, 0);
4127
0
  }
4128
0
  sc_file_free(file);
4129
4130
  /* set "current" blob to parent */
4131
0
  priv->current = blob->parent;
4132
4133
0
  LOG_FUNC_RETURN(card->ctx, r);
4134
0
}
4135
4136
4137
/**
4138
 * ABI: ISO 7816-4 UPDATE BINARY - update data in current EF.
4139
 */
4140
static int
4141
pgp_update_binary(sc_card_t *card, unsigned int idx,
4142
      const u8 *buf, size_t count, unsigned long flags)
4143
0
{
4144
0
  struct pgp_priv_data *priv = DRVDATA(card);
4145
0
  pgp_blob_t *blob = priv->current;
4146
0
  int r = SC_SUCCESS;
4147
4148
0
  LOG_FUNC_CALLED(card->ctx);
4149
4150
  /* We will use PUT DATA to write to DO.
4151
   * As PUT DATA does not support idx, we don't either */
4152
0
  if (idx > 0)
4153
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
4154
4155
  /* When a dummy file, e.g "11001101", is selected, the current blob
4156
   * is set to NULL. We don't really put data to dummy file. */
4157
0
  if (blob != NULL) {
4158
0
    r = pgp_put_data(card, blob->id, buf, count);
4159
0
  }
4160
4161
0
  LOG_FUNC_RETURN(card->ctx, r);
4162
0
}
4163
4164
4165
/**
4166
 * ABI: card reader lock obtained - re-select card applet if necessary.
4167
 */
4168
static int pgp_card_reader_lock_obtained(sc_card_t *card, int was_reset)
4169
767k
{
4170
767k
  struct pgp_priv_data *priv = DRVDATA(card); /* may be null during initialization */
4171
767k
  int r = SC_SUCCESS;
4172
4173
767k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
4174
4175
767k
  if (card->flags & SC_CARD_FLAG_KEEP_ALIVE
4176
0
      && was_reset <= 0
4177
0
      && priv != NULL && priv->mf && priv->mf->file) {
4178
    /* check whether applet is still selected */
4179
0
    unsigned char aid[16];
4180
4181
0
    r = sc_get_data(card, 0x004F, aid, sizeof aid);
4182
0
    if ((size_t) r != priv->mf->file->namelen
4183
0
        || 0 != memcmp(aid, priv->mf->file->name, r)) {
4184
      /* reselect is required */
4185
0
      was_reset = 1;
4186
0
    }
4187
0
    r = SC_SUCCESS;
4188
0
  }
4189
4190
767k
  if (was_reset > 0) {
4191
0
    sc_file_t *file = NULL;
4192
0
    sc_path_t path;
4193
    /* select application "OpenPGP" */
4194
0
    sc_format_path("D276:0001:2401", &path);
4195
0
    path.type = SC_PATH_TYPE_DF_NAME;
4196
0
    r = iso_ops->select_file(card, &path, &file);
4197
0
    sc_file_free(file);
4198
0
  }
4199
4200
767k
  LOG_FUNC_RETURN(card->ctx, r);
4201
767k
}
4202
4203
4204
/**
4205
 * API: integrate OpenPGP driver into OpenSC's driver list.
4206
 */
4207
struct sc_card_driver *
4208
sc_get_openpgp_driver(void)
4209
8.82k
{
4210
8.82k
  struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
4211
4212
8.82k
  iso_ops = iso_drv->ops;
4213
4214
8.82k
  pgp_ops = *iso_ops;
4215
8.82k
  pgp_ops.match_card  = pgp_match_card;
4216
8.82k
  pgp_ops.init    = pgp_init;
4217
8.82k
  pgp_ops.finish    = pgp_finish;
4218
8.82k
  pgp_ops.select_file = pgp_select_file;
4219
8.82k
  pgp_ops.list_files  = pgp_list_files;
4220
8.82k
  pgp_ops.get_challenge = pgp_get_challenge;
4221
8.82k
  pgp_ops.read_binary = pgp_read_binary;
4222
8.82k
  pgp_ops.write_binary  = NULL;
4223
8.82k
  pgp_ops.pin_cmd   = pgp_pin_cmd;
4224
8.82k
  pgp_ops.logout    = pgp_logout;
4225
8.82k
  pgp_ops.get_data  = pgp_get_data;
4226
8.82k
  pgp_ops.put_data  = pgp_put_data;
4227
8.82k
  pgp_ops.set_security_env= pgp_set_security_env;
4228
8.82k
  pgp_ops.compute_signature= pgp_compute_signature;
4229
8.82k
  pgp_ops.decipher  = pgp_decipher;
4230
8.82k
  pgp_ops.card_ctl  = pgp_card_ctl;
4231
8.82k
  pgp_ops.delete_file = pgp_delete_file;
4232
8.82k
  pgp_ops.update_binary = pgp_update_binary;
4233
8.82k
  pgp_ops.card_reader_lock_obtained = pgp_card_reader_lock_obtained;
4234
4235
8.82k
  return &pgp_drv;
4236
8.82k
}