Coverage Report

Created: 2026-10-28 06:53

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
12.5k
{
308
12.5k
  int r = SC_ERROR_INVALID_ARGUMENTS;
309
310
12.5k
  if (file != NULL) {
311
    /* explicitly get the full aid */
312
12.5k
    r = sc_get_data(card, 0x004F, file->name, sizeof file->name);
313
12.5k
    file->namelen = MAX(r, 0);
314
12.5k
  }
315
316
12.5k
  return r;
317
12.5k
}
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
29.6k
{
327
29.6k
  int i;
328
329
29.6k
  LOG_FUNC_CALLED(card->ctx);
330
331
29.6k
  i = _sc_match_atr(card, pgp_atrs, &card->type);
332
29.6k
  if (i >= 0) {
333
501
    card->name = pgp_atrs[i].name;
334
501
    LOG_FUNC_RETURN(card->ctx, 1);
335
501
  }
336
29.1k
  else {
337
29.1k
    sc_path_t partial_aid;
338
29.1k
    sc_file_t *file = NULL;
339
340
    /* select application "OpenPGP" */
341
29.1k
    sc_format_path("D276:0001:2401", &partial_aid);
342
29.1k
    partial_aid.type = SC_PATH_TYPE_DF_NAME;
343
    /* OpenPGP card only supports selection *with* requested FCI */
344
29.1k
    i = iso_ops->select_file(card, &partial_aid, &file);
345
29.1k
    if (SC_SUCCESS == i) {
346
6.12k
      card->type = SC_CARD_TYPE_OPENPGP_BASE;
347
6.12k
      card->name = default_cardname;
348
349
6.12k
      if (file->namelen != 16)
350
6.11k
        (void) get_full_pgp_aid(card, file);
351
6.12k
      if (file->namelen == 16) {
352
246
        unsigned char major = BCD2UCHAR(file->name[6]);
353
354
246
        switch (major) {
355
27
          case 1:
356
27
            card->type = SC_CARD_TYPE_OPENPGP_V1;
357
27
            card->name = default_cardname_v1;
358
27
            break;
359
58
          case 2:
360
58
            card->type = SC_CARD_TYPE_OPENPGP_V2;
361
58
            card->name = default_cardname_v2;
362
58
            break;
363
57
          case 3:
364
57
            card->type = SC_CARD_TYPE_OPENPGP_V3;
365
57
            card->name = default_cardname_v3;
366
57
            break;
367
104
          default:
368
104
            break;
369
246
        }
370
246
      }
371
6.12k
      sc_file_free(file);
372
6.12k
      LOG_FUNC_RETURN(card->ctx, 1);
373
6.12k
    }
374
29.1k
  }
375
23.0k
  LOG_FUNC_RETURN(card->ctx, 0);
376
23.0k
}
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
6.39k
{
382
6.39k
  pgp_do_info_t *info;
383
384
6.39k
  if (priv->mf == NULL)
385
0
    return SC_ERROR_INTERNAL;
386
387
377k
  for (info = priv->pgp_objects; (info != NULL) && (info->id > 0); info++) {
388
371k
    if (((info->access & READ_MASK) != READ_NEVER) && (info->get_fn != NULL)) {
389
120k
      pgp_blob_t *child = NULL;
390
120k
      sc_file_t *file = sc_file_new();
391
392
120k
      child = pgp_new_blob(card, priv->mf, info->id, file);
393
394
      /* catch out of memory condition */
395
120k
      if (child == NULL) {
396
0
        sc_file_free(file);
397
0
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
398
0
      }
399
120k
    }
400
371k
  }
401
6.39k
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
402
6.39k
}
403
404
/**
405
 * ABI: initialize driver & allocate private data.
406
 */
407
static int
408
pgp_init(sc_card_t *card)
409
6.62k
{
410
6.62k
  struct pgp_priv_data *priv;
411
6.62k
  sc_path_t path;
412
6.62k
  sc_file_t *file = NULL;
413
6.62k
  int   r, i;
414
415
6.62k
  LOG_FUNC_CALLED(card->ctx);
416
417
6.62k
  priv = calloc (1, sizeof *priv);
418
6.62k
  if (!priv)
419
6.62k
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
420
6.62k
  card->drv_data = priv;
421
422
6.62k
  card->cla = 0x00;
423
424
  /* select application "OpenPGP" */
425
6.62k
  sc_format_path("D276:0001:2401", &path);
426
6.62k
  path.type = SC_PATH_TYPE_DF_NAME;
427
6.62k
  if ((r = iso_ops->select_file(card, &path, &file)) < 0) {
428
179
    sc_file_free(file);
429
179
    pgp_finish(card);
430
179
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD);
431
179
  }
432
433
  /* defensive programming check */
434
6.44k
  if (!file)   {
435
0
    pgp_finish(card);
436
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD);
437
0
  }
438
439
6.44k
  if (file->namelen != 16) {
440
    /* explicitly get the full aid */
441
6.44k
    r = get_full_pgp_aid(card, file);
442
6.44k
    if (r < 0) {
443
48
      sc_file_free(file);
444
48
      pgp_finish(card);
445
48
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD);
446
48
    }
447
6.44k
  }
448
449
  /* read information from AID */
450
6.39k
  if (file->namelen == 16) {
451
4.10k
    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
4.10k
    priv->bcd_version = bebytes2ushort(file->name + 6);
455
4.10k
    card->version.fw_major = card->version.hw_major = BCD2UCHAR(file->name[6]);
456
4.10k
    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
4.10k
    if (card->name == default_cardname_v1 ||
460
4.09k
        card->name == default_cardname_v2 ||
461
4.08k
        card->name == default_cardname_v3) {
462
58
      snprintf(card_name, sizeof(card_name),
463
58
         "OpenPGP card v%u.%u (%04X %08lX)",
464
58
         card->version.hw_major, card->version.hw_minor,
465
58
         bebytes2ushort(file->name + 8),
466
58
         bebytes2ulong(file->name + 10));
467
58
    }
468
4.04k
    else if (card->name != NULL) {
469
      /* for other cards, append serial number to the card name */
470
4.04k
      snprintf(card_name, sizeof(card_name),
471
4.04k
         "%s (%04X %08lX)",
472
4.04k
         card->name,
473
4.04k
         bebytes2ushort(file->name + 8),
474
4.04k
         bebytes2ulong(file->name + 10));
475
4.04k
    }
476
4.10k
    card->name = card_name;
477
478
    /* GPG compatibility: set card's serial number to manufacturer ID + serial number */
479
4.10k
    memcpy(card->serialnr.value, file->name + 8, 6);
480
4.10k
    card->serialnr.len = 6;
481
4.10k
  } else {
482
    /* set detailed card version */
483
2.29k
    switch (card->type) {
484
28
      case SC_CARD_TYPE_OPENPGP_V3:
485
28
        priv->bcd_version = OPENPGP_CARD_3_0;
486
28
        break;
487
305
      case SC_CARD_TYPE_OPENPGP_GNUK:
488
340
      case SC_CARD_TYPE_OPENPGP_V2:
489
340
        priv->bcd_version = OPENPGP_CARD_2_0;
490
340
        break;
491
1.92k
      default:
492
1.92k
        priv->bcd_version = OPENPGP_CARD_1_1;
493
1.92k
        break;
494
2.29k
    }
495
2.29k
  }
496
497
  /* set pointer to correct list of card objects */
498
6.39k
  priv->pgp_objects = (priv->bcd_version < OPENPGP_CARD_2_0) ? pgp1x_objects
499
6.39k
        : (priv->bcd_version < OPENPGP_CARD_2_1) ? pgp20_objects
500
4.23k
        : (priv->bcd_version < OPENPGP_CARD_3_0) ? pgp21_objects
501
3.87k
        : (priv->bcd_version < OPENPGP_CARD_3_3) ? pgp30_objects
502
3.66k
        : (priv->bcd_version < OPENPGP_CARD_3_4) ? pgp33_objects
503
3.60k
        :              pgp34_objects;
504
505
  /* With gnuk, we use different curves */
506
6.39k
  if (card->type == SC_CARD_TYPE_OPENPGP_GNUK) {
507
459
    priv->ec_curves = ec_curves_gnuk;
508
5.94k
  } else if (priv->bcd_version >= OPENPGP_CARD_3_4) {
509
3.48k
    priv->ec_curves = ec_curves_openpgp34;
510
3.48k
  } else {
511
2.45k
    priv->ec_curves = ec_curves_openpgp;
512
2.45k
  }
513
514
  /* change file path to MF for reuse in MF */
515
6.39k
  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
6.39k
  priv->mf = pgp_new_blob(card, NULL, 0x3f00, file);
520
6.39k
  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
6.39k
  priv->current = priv->mf;
528
529
6.39k
  r = populate_blobs_to_mf(card, priv);
530
6.39k
  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
6.39k
  if (pgp_get_card_features(card)) {
537
628
    LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
538
628
  }
539
540
  /* if algorithm attributes can be changed,
541
   * add supported algorithms based on specification for pkcs15-init */
542
5.77k
  if (priv->ext_caps & EXT_CAP_ALG_ATTR_CHANGEABLE) {
543
605
    unsigned long flags_rsa, flags_ecc, ext_flags;
544
605
    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
605
    flags_rsa = SC_ALGORITHM_RSA_PAD_PKCS1|
548
605
          SC_ALGORITHM_RSA_HASH_NONE|
549
605
          SC_ALGORITHM_ONBOARD_KEY_GEN;
550
605
    flags_ecc = SC_ALGORITHM_ECDSA_RAW|
551
605
          SC_ALGORITHM_ECDH_CDH_RAW|
552
605
          SC_ALGORITHM_ECDSA_HASH_NONE|
553
605
          SC_ALGORITHM_ONBOARD_KEY_GEN;
554
605
    ext_flags = SC_ALGORITHM_EXT_EC_NAMEDCURVE;
555
556
605
    flags_eddsa = SC_ALGORITHM_EDDSA_RAW |
557
605
            SC_ALGORITHM_ONBOARD_KEY_GEN;
558
    /* xeddsa may allow signing at some time */
559
605
    flags_xeddsa = SC_ALGORITHM_ECDH_CDH_RAW |
560
605
             SC_ALGORITHM_ONBOARD_KEY_GEN;
561
562
605
    switch (card->type) {
563
18
      case SC_CARD_TYPE_OPENPGP_V3:
564
        /* RSA 1024 was removed for v3+ */
565
18
        _sc_card_add_rsa_alg(card, 4096, flags_rsa, 0);
566
18
        _sc_card_add_rsa_alg(card, 3072, flags_rsa, 0);
567
        /* fallthrough */
568
93
      case SC_CARD_TYPE_OPENPGP_GNUK:
569
93
        _sc_card_add_rsa_alg(card, 2048, flags_rsa, 0);
570
745
        for (i=0; priv->ec_curves[i].oid.value[0] >= 0; i++)
571
652
        {
572
652
          if (priv->ec_curves[i].key_type == SC_ALGORITHM_EC)
573
312
            _sc_card_add_ec_alg(card, priv->ec_curves[i].size,
574
312
                flags_ecc, ext_flags, &priv->ec_curves[i].oid);
575
340
          else if (priv->ec_curves[i].key_type == SC_ALGORITHM_EDDSA)
576
170
            _sc_card_add_eddsa_alg(card, priv->ec_curves[i].size,
577
170
                flags_eddsa, ext_flags, &priv->ec_curves[i].oid);
578
170
          else if (priv->ec_curves[i].key_type == SC_ALGORITHM_XEDDSA)
579
170
            _sc_card_add_xeddsa_alg(card, priv->ec_curves[i].size,
580
170
                flags_xeddsa, ext_flags, &priv->ec_curves[i].oid);
581
0
          else
582
0
            LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
583
652
        }
584
93
        break;
585
93
      case SC_CARD_TYPE_OPENPGP_V2:
586
512
      default:
587
512
        _sc_card_add_rsa_alg(card, 1024, flags_rsa, 0);
588
512
        _sc_card_add_rsa_alg(card, 2048, flags_rsa, 0);
589
512
        _sc_card_add_rsa_alg(card, 3072, flags_rsa, 0);
590
512
        _sc_card_add_rsa_alg(card, 4096, flags_rsa, 0);
591
512
        break;
592
605
    }
593
605
  }
594
595
5.77k
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
596
5.77k
}
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
1.09k
{
605
1.09k
  struct pgp_priv_data *priv = DRVDATA(card);
606
1.09k
  const u8 *ptr;
607
608
  /* IS07816-4 hist bytes: 3rd function table */
609
1.09k
  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
649
    if (ptr[2] & 0x40) {
612
133
      card->caps |= SC_CARD_CAP_APDU_EXT;
613
133
      priv->ext_caps |= EXT_CAP_APDU_EXT;
614
133
    }
615
    /* bit 0x80 in byte 3 of TL 0x73 means "Command chaining" */
616
649
    if (ptr[2] & 0x80) {
617
556
      priv->ext_caps |= EXT_CAP_CHAINING;
618
556
    }
619
649
  }
620
621
1.09k
  if ((priv->bcd_version >= OPENPGP_CARD_3_0) &&
622
434
      ((ptr = sc_compacttlv_find_tag(ctlv, ctlv_len, 0x31, NULL)) != NULL)) {
623
    // ToDo ...
624
174
  }
625
1.09k
}
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
88.5k
{
635
88.5k
  struct pgp_priv_data *priv = DRVDATA(card);
636
88.5k
  struct sc_object_id oid;
637
88.5k
  unsigned int j, r;
638
639
88.5k
  LOG_FUNC_CALLED(card->ctx);
640
641
88.5k
  if (blob == NULL || blob->data == NULL || blob->len == 0 ||
642
65.3k
      blob->id < 0x00c1 || blob->id > 0x00c3 || key_info == NULL) {
643
23.2k
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
644
23.2k
  }
645
646
65.3k
  key_info->key_id = blob->id - 0x00c0; /* attribute algorithm blobs are C1 - C3 */
647
648
65.3k
  switch (blob->data[0]) {
649
8.53k
    case SC_OPENPGP_KEYALGO_RSA:
650
8.53k
      if (blob->len < 5) {
651
3.02k
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
652
3.02k
      }
653
654
5.51k
      key_info->algorithm = SC_OPENPGP_KEYALGO_RSA;
655
5.51k
      key_info->u.rsa.modulus_len = bebytes2ushort(blob->data + 1);
656
5.51k
      key_info->u.rsa.exponent_len = bebytes2ushort(blob->data + 3);
657
658
5.51k
      key_info->u.rsa.keyformat = (blob->len > 5)
659
5.51k
              ? blob->data[5]
660
5.51k
              : SC_OPENPGP_KEYFORMAT_RSA_STD;
661
5.51k
      break;
662
22.2k
    case SC_OPENPGP_KEYALGO_ECDH:
663
39.3k
    case SC_OPENPGP_KEYALGO_ECDSA:
664
50.4k
    case SC_OPENPGP_KEYALGO_EDDSA:
665
666
      /* SC_OPENPGP_KEYALGO_ECDH || SC_OPENPGP_KEYALGO_ECDSA || SC_OPENPGP_KEYALGO_EDDSA */
667
50.4k
      key_info->algorithm = blob->data[0];
668
669
      /* last byte is set to 0xFF if pubkey import is supported */
670
50.4k
      if (blob->data[blob->len-1] == SC_OPENPGP_KEYFORMAT_EC_STDPUB){
671
10.2k
        if (blob->len < 3)
672
2.53k
          return SC_ERROR_INCORRECT_PARAMETERS;
673
7.75k
        key_info->u.ec.oidv_len = blob->len - 2;
674
7.75k
        key_info->u.ec.keyformat = SC_OPENPGP_KEYFORMAT_EC_STDPUB;
675
7.75k
      }
676
40.1k
      else {
677
        /* otherwise, last byte could be 00, so let's ignore it, as
678
         * it is not part of OID */
679
40.1k
        if (blob->len < 2)
680
3.68k
          return SC_ERROR_INCORRECT_PARAMETERS;
681
36.4k
        if (blob->data[blob->len-1] == SC_OPENPGP_KEYFORMAT_EC_STD)
682
10.8k
          key_info->u.ec.oidv_len = blob->len - 2;
683
25.5k
        else
684
25.5k
          key_info->u.ec.oidv_len = blob->len - 1;
685
36.4k
        key_info->u.ec.keyformat = SC_OPENPGP_KEYFORMAT_EC_STD;
686
36.4k
      }
687
688
      /* Create copy of oid from blob */
689
44.2k
      sc_init_oid(&oid);
690
44.2k
      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
44.2k
      if (r > 0){
694
19.9k
        return r;
695
19.9k
      }
696
      /* compare with list of supported ec_curves */
697
200k
      for (j = 0; priv->ec_curves[j].oid.value[0] >= 0; j++) {
698
189k
        if (sc_compare_oid(&priv->ec_curves[j].oid, &oid)) {
699
13.1k
          sc_log(card->ctx, "Matched EC oid %s (%d)",
700
13.1k
            sc_dump_oid(&oid), j);
701
13.1k
          key_info->u.ec.oid = priv->ec_curves[j].oid;
702
13.1k
          key_info->u.ec.key_length = priv->ec_curves[j].size;
703
13.1k
          break;
704
13.1k
        }
705
189k
      }
706
      /* We did not match the OID */
707
24.3k
      if (priv->ec_curves[j].oid.value[0] < 0) {
708
11.1k
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
709
11.1k
      }
710
13.1k
      break;
711
13.1k
    default:
712
6.34k
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
713
65.3k
  }
714
715
18.6k
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
716
18.6k
}
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
8.32k
{
722
8.32k
  if (!card || !key_info)
723
0
    return 0;
724
8.32k
  if (!sc_compare_oid(&key_info->u.ec.oid, &curve25519_oid) &&
725
8.32k
      !sc_compare_oid(&key_info->u.ec.oid, &X25519_oid))
726
2.71k
    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
5.60k
  _sc_card_add_xeddsa_alg(card, key_info->u.ec.key_length,
732
5.60k
      SC_ALGORITHM_ECDH_CDH_RAW | SC_ALGORITHM_ONBOARD_KEY_GEN, 0, &key_info->u.ec.oid);
733
5.60k
  sc_log(card->ctx, "DO %uX: Added XEDDSA algorithm (%d), mod_len = %zu",
734
5.60k
      do_num, SC_ALGORITHM_XEDDSA, key_info->u.ec.key_length);
735
5.60k
  return 1;
736
8.32k
}
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
18.6k
{
741
18.6k
  unsigned long flags = 0, ext_flags = 0;
742
743
18.6k
  if (!card || !key_info)
744
0
    return 0;
745
746
  /* [RFC 4880], [draft-ietf-openpgp-crypto-refresh] */
747
18.6k
  switch (key_info->algorithm) {
748
5.51k
  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
5.51k
    flags = SC_ALGORITHM_RSA_PAD_PKCS1 |
752
5.51k
      SC_ALGORITHM_RSA_HASH_NONE |
753
5.51k
      SC_ALGORITHM_ONBOARD_KEY_GEN; /* key gen on card */
754
755
5.51k
    _sc_card_add_rsa_alg(card, key_info->u.rsa.modulus_len, flags, 0);
756
5.51k
    sc_log(card->ctx, "DO %uX: Added RSA algorithm, mod_len = %zu",
757
5.51k
        do_num, key_info->u.rsa.modulus_len);
758
5.51k
    break;
759
3.70k
  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
3.70k
    if (_pgp_handle_curve25519(card, key_info, do_num))
763
2.08k
      break;
764
    /* fall through */
765
6.43k
  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
6.43k
    flags = SC_ALGORITHM_ECDH_CDH_RAW;
771
6.43k
    flags |= SC_ALGORITHM_ECDSA_RAW;
772
6.43k
    flags |= SC_ALGORITHM_ECDSA_HASH_NONE;
773
6.43k
    flags |= SC_ALGORITHM_ONBOARD_KEY_GEN;
774
6.43k
    ext_flags = SC_ALGORITHM_EXT_EC_NAMEDCURVE;
775
776
6.43k
    _sc_card_add_ec_alg(card, key_info->u.ec.key_length, flags, ext_flags,
777
6.43k
      &key_info->u.ec.oid);
778
6.43k
    sc_log(card->ctx, "DO %uX: Added EC algorithm (%d), mod_len = %zu" ,
779
6.43k
      do_num, key_info->algorithm, key_info->u.ec.key_length);
780
6.43k
    break;
781
4.61k
  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
4.61k
    if (_pgp_handle_curve25519(card, key_info, do_num))
785
3.52k
      break;
786
1.08k
    _sc_card_add_eddsa_alg(card, key_info->u.ec.key_length,
787
1.08k
        SC_ALGORITHM_EDDSA_RAW | SC_ALGORITHM_ONBOARD_KEY_GEN, 0, &key_info->u.ec.oid);
788
789
1.08k
    sc_log(card->ctx, "DO %uX: Added EDDSA algorithm (%d), mod_len = %zu" ,
790
1.08k
      do_num, key_info->algorithm, key_info->u.ec.key_length);
791
1.08k
    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
18.6k
  }
798
  /* return true */
799
18.6k
  return 1;
800
18.6k
}
801
802
#ifdef ENABLE_OPENSSL
803
static int
804
pgp_decode_kdf_do(sc_card_t *card, struct pgp_priv_data *priv)
805
285
{
806
285
  pgp_pin_kdf_info_t *pin_kdf_info = (pgp_pin_kdf_info_t *)calloc(1, sizeof(pgp_pin_kdf_info_t));
807
285
  int r = SC_ERROR_OUT_OF_MEMORY;
808
285
  pgp_blob_t *kdf_blob;
809
285
  const uint8_t *data;
810
285
  size_t data_len;
811
285
  size_t tag_len;
812
285
  const uint8_t *p;
813
285
  pgp_blob_t *blob;
814
815
285
  if (!pin_kdf_info) {
816
0
    return r;
817
0
  }
818
819
285
  r = SC_ERROR_INVALID_DATA;
820
285
  priv->pin_kdf_info = NULL;
821
285
  if ((pgp_get_blob(card, priv->mf, DO_KDF, &kdf_blob) != SC_SUCCESS) || (kdf_blob->len < 3)) {
822
156
    sc_log(card->ctx, "KDF DO does not exists or contains invalid data but card claims to support it");
823
156
    goto out;
824
156
  }
825
826
129
  data = kdf_blob->data;
827
129
  data_len = kdf_blob->len;
828
129
  p = sc_asn1_find_tag(card->ctx, data, data_len, 0x81, &tag_len);
829
129
  if (!p) {
830
36
    sc_log(card->ctx, "KDF algorithm byte not found");
831
36
    goto out;
832
36
  }
833
93
  if (tag_len != 1) {
834
14
    sc_log(card->ctx, "Unexpected KDF algorithm byte length, expects 1, got %zu", tag_len);
835
14
    goto out;
836
14
  }
837
838
79
  if (*p != 0x3) {
839
27
    if (*p == 0x0) {
840
10
      r = SC_SUCCESS;
841
10
      sc_log(card->ctx, "KDF derived PIN format disabled");
842
17
    } else {
843
17
      sc_log(card->ctx, "Unknown KDF algorithm ID %x", *p);
844
17
    }
845
27
    goto out;
846
27
  }
847
848
52
  p = sc_asn1_find_tag(card->ctx, data, data_len, 0x82, &tag_len);
849
52
  if (!p) {
850
8
    sc_log(card->ctx, "KDF hash algorithm byte not found");
851
8
    goto out;
852
8
  }
853
44
  if (tag_len != 1) {
854
8
    sc_log(card->ctx, "Unexpected KDF hash algorithm byte length, expects 1, got %zu", tag_len);
855
8
    goto out;
856
8
  }
857
858
36
  switch (*p) {
859
15
  case 0x08:
860
15
    pin_kdf_info->hash_algo = "SHA256";
861
15
    break;
862
14
  case 0x0A:
863
14
    pin_kdf_info->hash_algo = "SHA512";
864
14
    break;
865
7
  default:
866
7
    sc_log(card->ctx, "Unknown KDF hash algorithm ID %x", *p);
867
7
    goto out;
868
36
  }
869
870
29
  p = sc_asn1_find_tag(card->ctx, data, data_len, 0x83, &tag_len);
871
29
  if (!p) {
872
8
    sc_log(card->ctx, "KDF iteration count not found");
873
8
    goto out;
874
8
  }
875
21
  if (tag_len != 4) {
876
6
    sc_log(card->ctx, "Unexpected KDF iteration count length, expects 4, got %zu", tag_len);
877
6
    goto out;
878
6
  }
879
15
  pin_kdf_info->iterations = (uint32_t)bebytes2ulong(p);
880
881
15
  r = pgp_get_blob(card, kdf_blob, 0x84, &blob);
882
15
  if (r != SC_SUCCESS) {
883
7
    sc_log(card->ctx, "Failed to get salt bytes of user password");
884
7
    goto out;
885
7
  }
886
8
  pin_kdf_info->userpw_salt = blob;
887
888
8
  r = pgp_get_blob(card, kdf_blob, 0x86, &blob);
889
8
  if (r != SC_SUCCESS) {
890
4
    sc_log(card->ctx, "Failed to get salt bytes of admin password");
891
4
    goto out;
892
4
  }
893
4
  pin_kdf_info->adminpw_salt = blob;
894
895
4
  sc_log(card->ctx, "KDF derived PIN format enabled");
896
4
  priv->pin_kdf_info = pin_kdf_info;
897
4
  return r;
898
281
out:
899
281
  free(pin_kdf_info);
900
281
  return r;
901
8
}
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
6.39k
{
910
6.39k
  struct pgp_priv_data *priv = DRVDATA(card);
911
6.39k
  u8 *hist_bytes = card->reader->atr_info.hist_bytes;
912
6.39k
  size_t hist_bytes_len = card->reader->atr_info.hist_bytes_len;
913
6.39k
  unsigned int i;
914
6.39k
  pgp_blob_t *blob, *blob6e, *blob73, *blobfa;
915
6.39k
  int handled_algos = 0;
916
917
6.39k
  LOG_FUNC_CALLED(card->ctx);
918
919
  /* parse card capabilities from historical bytes in ATR */
920
6.39k
  if (hist_bytes_len > 0) {
921
    /* category indicator 0x00, 0x10 or 0x80 => compact TLV (ISO) */
922
1.30k
    switch (hist_bytes[0]) {
923
795
      case 0x00:
924
795
        if (hist_bytes_len > 4) {
925
597
          pgp_parse_hist_bytes(card, hist_bytes+1, hist_bytes_len-4);
926
597
        }
927
795
        break;
928
207
      case 0x80:
929
207
        if (hist_bytes_len > 1) {
930
199
          pgp_parse_hist_bytes(card, hist_bytes+1, hist_bytes_len-1);
931
199
        }
932
207
        break;
933
29
      case 0x10:
934
29
        if (hist_bytes_len > 2) {
935
19
          pgp_parse_hist_bytes(card, hist_bytes+2, hist_bytes_len-2);
936
19
        }
937
29
        break;
938
1.30k
    }
939
1.30k
  }
940
941
  /* v1.1 does not support lifecycle via ACTIVATE & TERMINATE: set default */
942
6.39k
  priv->ext_caps &= ~EXT_CAP_LCS;
943
944
6.39k
  if (priv->bcd_version >= OPENPGP_CARD_2_0) {
945
    /* get card capabilities from "historical bytes" DO */
946
4.23k
    if ((pgp_get_blob(card, priv->mf, 0x5f52, &blob) >= 0) &&
947
4.23k
        (blob->data != NULL) && (blob->data[0] == 0x00)) {
948
949
303
      if (blob->len > 4) {
950
276
        pgp_parse_hist_bytes(card, blob->data+1, blob->len-4);
951
276
      }
952
953
      /* get card status from historical bytes status indicator */
954
303
      if ((blob->data[0] == 0x00) && (blob->len >= 4)) {
955
285
        priv->state = blob->data[blob->len-3];
956
        /* state not CARD_STATE_UNKNOWN => LCS supported */
957
285
        if (priv->state != CARD_STATE_UNKNOWN)
958
215
          priv->ext_caps |= EXT_CAP_LCS;
959
285
      }
960
303
    }
961
4.23k
  }
962
963
6.39k
  if (priv->bcd_version >= OPENPGP_CARD_3_1) {
964
3.61k
    card->caps |= SC_CARD_CAP_ISO7816_PIN_INFO;
965
3.61k
  }
966
967
6.39k
  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
3.56k
    if (pgp_get_blob(card, priv->mf, 0x00fa, &blobfa) >= 0) {
971
3.56k
      pgp_blob_t *child;
972
3.56k
      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
157k
      for (child = blobfa->files; child; child = child->next) {
976
153k
        if ((child->id < 0x00c1) || (child->id > 0x00c3))
977
66.2k
          continue;
978
87.3k
        sc_cardctl_openpgp_key_gen_store_info_t key_info;
979
87.3k
        if (pgp_parse_algo_attr_blob(card, child, &key_info) >= 0)
980
18.3k
          handled_algos += _pgp_add_algo(card, &key_info, 0x00fa);
981
87.3k
      }
982
3.56k
    }
983
3.56k
  }
984
985
  /* v1.1 & v2.x: special DOs are limited to 254 bytes */
986
6.39k
  priv->max_specialDO_size = 254;
987
988
6.39k
  if ((pgp_get_blob(card, priv->mf, 0x006e, &blob6e) >= 0) &&
989
6.39k
      (pgp_get_blob(card, blob6e, 0x0073, &blob73) >= 0)) {
990
991
    /* get "extended capabilities" DO */
992
1.49k
    if ((pgp_get_blob(card, blob73, 0x00c0, &blob) >= 0) &&
993
870
        (blob->data != NULL) && (blob->len > 0)) {
994
858
      if ((blob->data[0] & 0x01) && (priv->bcd_version >= OPENPGP_CARD_3_3)) {
995
285
        priv->ext_caps |= EXT_CAP_KDF_DO;
996
285
      }
997
      /* v2.0+: bit 0x04 in first byte means "algorithm attributes changeable" */
998
858
      if ((blob->data[0] & 0x04) &&
999
673
          (priv->bcd_version >= OPENPGP_CARD_2_0))
1000
606
        priv->ext_caps |= EXT_CAP_ALG_ATTR_CHANGEABLE;
1001
      /* bit 0x08 in first byte means "support for private use DOs" */
1002
858
      if (blob->data[0] & 0x08)
1003
329
        priv->ext_caps |= EXT_CAP_PRIVATE_DO;
1004
      /* bit 0x10 in first byte means "support for CHV status byte changeable" */
1005
858
      if (blob->data[0] & 0x10)
1006
316
        priv->ext_caps |= EXT_CAP_C4_CHANGEABLE;
1007
      /* bit 0x20 in first byte means "support for Key Import" */
1008
858
      if (blob->data[0] & 0x20)
1009
374
        priv->ext_caps |= EXT_CAP_KEY_IMPORT;
1010
      /* bit 0x40 in first byte means "support for Get Challenge" */
1011
858
      if (blob->data[0] & 0x40) {
1012
359
        card->caps |= SC_CARD_CAP_RNG;
1013
359
        priv->ext_caps |= EXT_CAP_GET_CHALLENGE;
1014
359
      }
1015
      /* v2.0+: bit 0x80 in first byte means "support Secure Messaging" */
1016
858
      if ((blob->data[0] & 0x80) &&
1017
364
          (priv->bcd_version >= OPENPGP_CARD_2_0))
1018
305
        priv->ext_caps |= EXT_CAP_SM;
1019
1020
858
      if ((priv->bcd_version >= OPENPGP_CARD_2_0) && (blob->len >= 10)) {
1021
        /* v2.0+: max. challenge size is at bytes 3-4 */
1022
659
        priv->max_challenge_size = bebytes2ushort(blob->data + 2);
1023
        /* v2.0+: max. cert size it at bytes 5-6 */
1024
659
        priv->max_cert_size = bebytes2ushort(blob->data + 4);
1025
1026
659
        if (priv->bcd_version < OPENPGP_CARD_3_0) {
1027
          /* v2.x: SM algorithm is at byte 2: 0 == 3DES */
1028
157
          priv->sm_algo = blob->data[1];
1029
157
          if ((priv->sm_algo == SM_ALGO_NONE) && (priv->ext_caps & EXT_CAP_SM))
1030
52
            priv->sm_algo = SM_ALGO_3DES;
1031
1032
          /* v2.x: max. send/receive sizes are at bytes 7-8 resp. 9-10 */
1033
157
          card->max_send_size = bebytes2ushort(blob->data + 6);
1034
157
          card->max_recv_size = bebytes2ushort(blob->data + 8);
1035
157
        }
1036
502
        else {
1037
          /* v3.0+: SM algorithm is at byte 2: 0 == UNKNOWN */
1038
502
          priv->sm_algo = blob->data[1];
1039
502
          if ((priv->sm_algo == SM_ALGO_NONE) && (priv->ext_caps & EXT_CAP_SM))
1040
46
            priv->sm_algo = SM_ALGO_UNKNOWN;
1041
1042
          /* v3.0+: max. size of special DOs is at bytes 7-8 */
1043
502
          priv->max_specialDO_size = bebytes2ushort(blob->data + 6);
1044
502
        }
1045
659
        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
486
          if (blob->data[9])
1048
302
            priv->ext_caps |= EXT_CAP_MSE;
1049
486
        }
1050
659
      }
1051
858
    }
1052
1053
    /* get max. PIN length from "CHV status bytes" DO */
1054
1.49k
    if ((pgp_get_blob(card, blob73, 0x00c4, &blob) >= 0) &&
1055
653
      (blob->data != NULL) && (blob->len > 1)) {
1056
      /* 2nd byte in "CHV status bytes" DO means "max. PIN length" */
1057
455
      card->max_pin_len = blob->data[1];
1058
455
    }
1059
1060
1.49k
    if (priv->bcd_version >= OPENPGP_CARD_3_0) {
1061
      /* v3.0+: get length info from "extended length information" DO */
1062
837
      if ((pgp_get_blob(card, blob6e, 0x7f66, &blob) >= 0) &&
1063
11
        (blob->data != NULL) && (blob->len >= 8)) {
1064
        /* kludge: treat as SIMPLE DO and use appropriate offsets */
1065
4
        card->max_send_size = bebytes2ushort(blob->data + 2);
1066
4
        card->max_recv_size = bebytes2ushort(blob->data + 6);
1067
4
      }
1068
837
    }
1069
1070
1.49k
#ifdef ENABLE_OPENSSL
1071
1.49k
    if (priv->ext_caps & EXT_CAP_KDF_DO) {
1072
285
      int r = pgp_decode_kdf_do(card, priv);
1073
285
      if (r != SC_SUCCESS) {
1074
271
        sc_log(card->ctx, "Failed to decode KDF DO: %s", sc_strerror(r));
1075
271
      }
1076
285
    }
1077
1.49k
#endif /* ENABLE_OPENSSL */
1078
1079
    /* if we found at least one usable algo, let's skip other ways to find them */
1080
1.49k
    if (handled_algos) {
1081
27
      sc_log(card->ctx, "Algo list populated from Algorithm Information DO");
1082
27
      LOG_FUNC_RETURN(card->ctx, handled_algos);
1083
27
    }
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
5.86k
    for (i = 0x00c1; i <= 0x00c3; i++) {
1092
4.39k
      sc_cardctl_openpgp_key_gen_store_info_t key_info;
1093
1094
4.39k
      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
4.39k
      if ((pgp_get_blob(card, blob73, i, &blob) >= 0) &&
1098
1.21k
          (pgp_parse_algo_attr_blob(card, blob, &key_info) >= 0)) {
1099
323
        if (!_pgp_add_algo(card, &key_info, i))
1100
323
          LOG_TEST_RET(card->ctx, SC_ERROR_INTERNAL, "Cannot add algorithm");
1101
323
      }
1102
4.39k
    }
1103
1104
1.46k
  }
1105
1106
6.37k
  LOG_FUNC_RETURN(card->ctx, handled_algos);
1107
6.37k
}
1108
1109
1110
/**
1111
 * ABI: terminate driver & free private data.
1112
 */
1113
static int
1114
pgp_finish(sc_card_t *card)
1115
6.62k
{
1116
6.62k
  if (card != NULL) {
1117
6.62k
    struct pgp_priv_data *priv = DRVDATA(card);
1118
1119
6.62k
    if (priv != NULL) {
1120
      /* delete fake file hierarchy */
1121
6.62k
      pgp_free_blobs(priv->mf);
1122
1123
      /* delete kdf do related data if exists */
1124
6.62k
      free(priv->pin_kdf_info);
1125
1126
      /* delete private data */
1127
6.62k
      free(priv);
1128
6.62k
    }
1129
6.62k
    card->drv_data = NULL;
1130
6.62k
  }
1131
6.62k
  return SC_SUCCESS;
1132
6.62k
}
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.92M
{
1141
1.92M
  if (blob->data)
1142
87
    free(blob->data);
1143
1.92M
  blob->data = NULL;
1144
1.92M
  blob->len    = 0;
1145
1.92M
  blob->status = 0;
1146
1147
1.92M
  if (len > 0) {
1148
495k
    void *tmp = calloc(1, len);
1149
1150
495k
    if (tmp == NULL)
1151
0
      return SC_ERROR_OUT_OF_MEMORY;
1152
1153
495k
    blob->data = tmp;
1154
495k
    blob->len  = (unsigned int)len;
1155
495k
    if (data != NULL)
1156
495k
      memcpy(blob->data, data, len);
1157
495k
  }
1158
1159
1.92M
  if (blob->file)
1160
1.92M
    blob->file->size = len;
1161
1162
1.92M
  return SC_SUCCESS;
1163
1.92M
}
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
1.15M
{
1173
1.15M
  unsigned int method = SC_AC_NONE;
1174
1.15M
  unsigned long key_ref = SC_AC_KEY_REF_NONE;
1175
1176
  /* Write access */
1177
1.15M
  switch (info->access & WRITE_MASK) {
1178
914k
  case WRITE_NEVER:
1179
914k
    method = SC_AC_NEVER;
1180
914k
    break;
1181
0
  case WRITE_PIN1:
1182
0
    method = SC_AC_CHV;
1183
0
    key_ref = 0x01;
1184
0
    break;
1185
12.7k
  case WRITE_PIN2:
1186
12.7k
    method = SC_AC_CHV;
1187
12.7k
    key_ref = 0x02;
1188
12.7k
    break;
1189
226k
  case WRITE_PIN3:
1190
226k
    method = SC_AC_CHV;
1191
226k
    key_ref = 0x03;
1192
226k
    break;
1193
1.15M
  }
1194
1195
1.15M
  if (method != SC_AC_NONE || key_ref != SC_AC_KEY_REF_NONE) {
1196
1.15M
    sc_file_add_acl_entry(file, SC_AC_OP_WRITE, method, key_ref);
1197
1.15M
    sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, method, key_ref);
1198
1.15M
    sc_file_add_acl_entry(file, SC_AC_OP_DELETE, method, key_ref);
1199
1.15M
    sc_file_add_acl_entry(file, SC_AC_OP_CREATE, method, key_ref);
1200
1.15M
  }
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
1.15M
  method = SC_AC_NONE;
1208
1.15M
  key_ref = SC_AC_KEY_REF_NONE;
1209
  /* Read access */
1210
1.15M
  switch (info->access & READ_MASK) {
1211
76.8k
  case READ_NEVER:
1212
76.8k
    method = SC_AC_NEVER;
1213
76.8k
    break;
1214
0
  case READ_PIN1:
1215
0
    method = SC_AC_CHV;
1216
0
    key_ref = 0x01;
1217
0
    break;
1218
6.39k
  case READ_PIN2:
1219
6.39k
    method = SC_AC_CHV;
1220
6.39k
    key_ref = 0x02;
1221
6.39k
    break;
1222
6.39k
  case READ_PIN3:
1223
6.39k
    method = SC_AC_CHV;
1224
6.39k
    key_ref = 0x03;
1225
6.39k
    break;
1226
1.15M
  }
1227
1228
1.15M
  if (method != SC_AC_NONE || key_ref != SC_AC_KEY_REF_NONE) {
1229
89.6k
    sc_file_add_acl_entry(file, SC_AC_OP_READ, method, key_ref);
1230
89.6k
  }
1231
1.15M
}
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.94M
{
1241
1.94M
  pgp_blob_t *blob = NULL;
1242
1243
1.94M
  if (file == NULL)
1244
0
    return NULL;
1245
1246
1.94M
  if ((blob = calloc(1, sizeof(pgp_blob_t))) != NULL) {
1247
1.94M
    struct pgp_priv_data *priv = DRVDATA(card);
1248
1.94M
    pgp_do_info_t *info;
1249
1250
1.94M
    blob->file = file;
1251
1252
1.94M
    blob->file->type         = SC_FILE_TYPE_WORKING_EF; /* default */
1253
1.94M
    blob->file->ef_structure = SC_FILE_EF_TRANSPARENT;
1254
1.94M
    blob->file->id           = file_id;
1255
1256
1.94M
    blob->id     = file_id;
1257
1.94M
    blob->parent = parent;
1258
1259
1.94M
    if (parent != NULL) {
1260
1.93M
      pgp_blob_t **p;
1261
1262
      /* set file's path = parent's path + file's id */
1263
1.93M
      blob->file->path = parent->file->path;
1264
1.93M
      sc_append_file_id(&blob->file->path, file_id);
1265
1266
      /* append blob to list of parent's children */
1267
58.7M
      for (p = &parent->files; *p != NULL; p = &(*p)->next)
1268
56.7M
        ;
1269
1.93M
      *p = blob;
1270
1.93M
    }
1271
6.39k
    else {
1272
6.39k
      char path[10] = "0000"; /* long enough */
1273
1274
      /* no parent: set file's path = file's id */
1275
6.39k
      if (4 != snprintf(path, sizeof(path), "%04X", file_id & 0xFFFF)) {
1276
0
        free(blob);
1277
0
        return NULL;
1278
0
      }
1279
1280
6.39k
      sc_format_path(path, &blob->file->path);
1281
6.39k
    }
1282
1283
    /* find matching DO info: set file type depending on it */
1284
53.7M
    for (info = priv->pgp_objects; (info != NULL) && (info->id > 0); info++) {
1285
52.9M
      if (info->id == file_id) {
1286
1.15M
        blob->info = info;
1287
1.15M
        blob->file->type = blob->info->type;
1288
1.15M
        pgp_attach_acl(card, blob->file, info);
1289
1.15M
        break;
1290
1.15M
      }
1291
52.9M
    }
1292
1.94M
  }
1293
1294
1.94M
  return blob;
1295
1.94M
}
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.94M
{
1304
1.94M
  if (blob) {
1305
1.94M
    if (blob->parent) {
1306
1.93M
      pgp_blob_t **p;
1307
1308
      /* remove blob from list of parent's children */
1309
1.93M
      for (p = &blob->parent->files; *p != NULL && *p != blob; p = &(*p)->next)
1310
0
        ;
1311
1.93M
      if (*p == blob)
1312
1.93M
        *p = blob->next;
1313
1.93M
    }
1314
1315
1.94M
    sc_file_free(blob->file);
1316
1.94M
    if (blob->data)
1317
494k
      free(blob->data);
1318
1.94M
    free(blob);
1319
1.94M
  }
1320
1.94M
}
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.94M
{
1329
1.94M
  if (blob) {
1330
1.94M
    pgp_blob_t *child = blob->files;
1331
1332
3.87M
    while (child != NULL) {
1333
1.93M
      pgp_blob_t *next = child->next;
1334
1335
1.93M
      pgp_free_blobs(child);
1336
1.93M
      child = next;
1337
1.93M
    }
1338
1.94M
    pgp_free_blob(blob);
1339
1.94M
  }
1340
1.94M
}
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.61M
{
1349
1.61M
  struct pgp_priv_data *priv = DRVDATA(card);
1350
1351
1.61M
  if (blob->data != NULL)
1352
333k
    return SC_SUCCESS;
1353
1.27M
  if (blob->info == NULL)
1354
459k
    return blob->status;
1355
1356
819k
  if (blob->info->get_fn) { /* readable, top-level DO */
1357
816k
    u8  buffer[MAX_OPENPGP_DO_SIZE];
1358
816k
    size_t  buf_len = sizeof(buffer);
1359
816k
    int r = SC_SUCCESS;
1360
1361
    /* buffer length for certificate */
1362
816k
    if (blob->id == DO_CERT && priv->max_cert_size > 0) {
1363
139
      buf_len = MIN(priv->max_cert_size, sizeof(buffer));
1364
139
    }
1365
1366
    /* buffer length for Gnuk pubkey */
1367
816k
    if (card->type == SC_CARD_TYPE_OPENPGP_GNUK &&
1368
8.76k
        (blob->id == DO_AUTH ||
1369
8.66k
         blob->id == DO_SIGN ||
1370
8.58k
         blob->id == DO_ENCR ||
1371
8.48k
         blob->id == DO_AUTH_SYM ||
1372
8.48k
         blob->id == DO_SIGN_SYM ||
1373
8.47k
         blob->id == DO_ENCR_SYM)) {
1374
291
      buf_len = MIN(MAXLEN_RESP_PUBKEY_GNUK, sizeof(buffer));
1375
291
    }
1376
1377
816k
    r = blob->info->get_fn(card, blob->id, buffer, buf_len);
1378
1379
816k
    if (r < 0) { /* an error occurred */
1380
708k
      blob->status = r;
1381
708k
      return r;
1382
708k
    }
1383
1384
107k
    return pgp_set_blob(blob, buffer, r);
1385
816k
  }
1386
2.94k
  else {   /* un-readable DO or part of a constructed DO */
1387
2.94k
    return SC_SUCCESS;
1388
2.94k
  }
1389
819k
}
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.62M
{
1399
1.62M
  const u8  *in;
1400
1.62M
  int   r;
1401
1.62M
  sc_file_t *file = NULL;
1402
1403
1.62M
  if (blob->files != NULL)
1404
54.4k
    return SC_SUCCESS;
1405
1406
1.57M
  if ((r = pgp_read_blob(card, blob)) < 0)
1407
694k
    return r;
1408
1409
876k
  in = blob->data;
1410
1411
2.98M
  while ((int) blob->len > (in - blob->data)) {
1412
2.42M
    unsigned int  cla, tag, tmptag;
1413
2.42M
    size_t    len;
1414
2.42M
    const u8  *data = in;
1415
2.42M
    pgp_blob_t  *new;
1416
1417
2.42M
    if (!in)
1418
0
      return SC_ERROR_OBJECT_NOT_VALID;
1419
1420
2.42M
    r = sc_asn1_read_tag(&data, blob->len - (in - blob->data),
1421
2.42M
          &cla, &tag, &len);
1422
2.42M
    if (r == SC_ERROR_INVALID_ASN1_OBJECT) {
1423
55.1k
      sc_log(card->ctx, "Invalid ASN.1 object");
1424
55.1k
      return SC_ERROR_OBJECT_NOT_VALID;
1425
55.1k
    }
1426
    /* Check for unknown error, or empty data */
1427
2.37M
    if (((r < 0) && (r != SC_ERROR_ASN1_END_OF_CONTENTS)) ||
1428
2.37M
        (data == NULL)) {
1429
156k
      sc_log(card->ctx, "Unexpected end of contents");
1430
156k
      return SC_ERROR_OBJECT_NOT_VALID;
1431
156k
    }
1432
1433
    /* undo ASN1's split of tag & class */
1434
2.28M
    for (tmptag = tag; tmptag > 0x0FF; tmptag >>= 8) {
1435
74.2k
      cla <<= 8;
1436
74.2k
    }
1437
2.21M
    tag |= cla;
1438
    /* Check for length mismatch */
1439
2.21M
    if ((r == SC_ERROR_ASN1_END_OF_CONTENTS) ||
1440
2.10M
        (data + len > blob->data + blob->len)) {
1441
      // Check if it is not known Yubikey 5 issue
1442
111k
      if ((tag != blob->id) || (tag != 0xfa)) {
1443
110k
        sc_log(card->ctx, "Unexpected end of contents");
1444
110k
        return SC_ERROR_OBJECT_NOT_VALID;
1445
110k
      }
1446
111k
    }
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
2.10M
    if (tag == blob->id) {
1452
288k
      in = data;
1453
288k
      continue;
1454
288k
    }
1455
1456
    /* create fake file system hierarchy by
1457
     * using constructed DOs as DF */
1458
1.81M
    file = sc_file_new();
1459
1.81M
    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.81M
    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.81M
    in = data + len;
1468
1.81M
  }
1469
1470
554k
  return SC_SUCCESS;
1471
876k
}
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.62M
{
1481
1.62M
  pgp_blob_t    *child;
1482
1.62M
  int     r;
1483
1484
1.62M
  if ((r = pgp_enumerate_blob(card, blob)) < 0)
1485
1.01M
    return r;
1486
1487
1.20M
  for (child = blob->files; child; child = child->next) {
1488
633k
    if (child->id == id) {
1489
34.3k
      (void) pgp_read_blob(card, child);
1490
34.3k
      *ret = child;
1491
34.3k
      return SC_SUCCESS;
1492
34.3k
    }
1493
633k
  }
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
572k
  if (blob->id == DO_CARDHOLDER && (id == DO_NAME || id == DO_LANG_PREF || id == DO_SEX)) {
1501
809
    sc_log(card->ctx, "Create blob %X under %X", id, blob->id);
1502
809
    child = pgp_new_blob(card, blob, id, sc_file_new());
1503
809
    if (child) {
1504
809
      pgp_set_blob(child, NULL, 0);
1505
809
      *ret = child;
1506
809
      return SC_SUCCESS;
1507
809
    }
1508
0
    else
1509
0
      sc_log(card->ctx,
1510
809
             "Not enough memory to create blob for DO %X",
1511
809
             id);
1512
809
  }
1513
1514
571k
  return SC_ERROR_FILE_NOT_FOUND;
1515
572k
}
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.56M
{
1525
1.56M
  pgp_blob_t  *child;
1526
1.56M
  int     r;
1527
1528
1.56M
  if ((r = pgp_get_blob(card, root, id, ret)) == 0)
1529
    /* the sought blob is right under root */
1530
703
    return r;
1531
1532
  /* not found, seek deeper */
1533
3.21M
  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.65M
    if ((child->info && child->info->type == SIMPLE) || child->id == DO_CERT)
1537
92.2k
      continue;
1538
1.55M
    r = pgp_seek_blob(card, child, id, ret);
1539
1.55M
    if (r == 0)
1540
1.29k
      return r;
1541
1.55M
  }
1542
1543
1.55M
  return SC_ERROR_FILE_NOT_FOUND;
1544
1.56M
}
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.66k
{
1553
1.66k
  struct pgp_priv_data *priv = DRVDATA(card);
1554
1.66k
  pgp_blob_t *blob = NULL;
1555
1.66k
  int r;
1556
1557
  /* check if current selected blob is which we want to test */
1558
1.66k
  if (priv->current->id == tag) {
1559
24
    return priv->current;
1560
24
  }
1561
  /* look for the blob representing the DO */
1562
1.64k
  r = pgp_seek_blob(card, priv->mf, tag, &blob);
1563
1.64k
  if (r < 0) {
1564
1.17k
    sc_log(card->ctx, "Failed to seek the blob representing the tag %04X. Error %d.", tag, r);
1565
1.17k
    return NULL;
1566
1.17k
  }
1567
463
  return blob;
1568
1.64k
}
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
1.16k
{
1577
1.16k
  struct pgp_priv_data *priv = DRVDATA(card);
1578
1.16k
  pgp_do_info_t *info;
1579
1580
59.1k
  for (info = priv->pgp_objects; (info != NULL) && (info->id > 0); info++)
1581
58.1k
    if (tag == info->id)
1582
211
      return info;
1583
1584
952
  return NULL;
1585
1.16k
}
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
25.2k
{
1596
25.2k
  unsigned int start_point = 0;
1597
  /* start_point will move through the path string */
1598
25.2k
  if (path->len == 0)
1599
0
    return 0;
1600
1601
  /* ignore 3F00 (MF) at the beginning */
1602
25.2k
  start_point = (memcmp(path->value, "\x3f\x00", 2) == 0) ? 2 : 0;
1603
  /* strip path of PKCS15-App DF (5015) */
1604
25.2k
  start_point += (memcmp(path->value + start_point, "\x50\x15", 2) == 0) ? 2 : 0;
1605
25.2k
  return start_point;
1606
25.2k
}
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
34.9k
{
1615
34.9k
  struct pgp_priv_data *priv = DRVDATA(card);
1616
34.9k
  pgp_blob_t  *blob;
1617
34.9k
  unsigned int  path_start = 0;
1618
34.9k
  unsigned int  n;
1619
34.9k
  sc_path_t dummy_path;
1620
1621
34.9k
  LOG_FUNC_CALLED(card->ctx);
1622
1623
34.9k
  if (path->type == SC_PATH_TYPE_DF_NAME)
1624
34.9k
    LOG_FUNC_RETURN(card->ctx, iso_ops->select_file(card, path, ret));
1625
1626
25.2k
  if (path->len < 2 || (path->len & 1))
1627
25.2k
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
1628
25.2k
        "invalid path length");
1629
1630
25.2k
  if (path->type == SC_PATH_TYPE_FILE_ID && path->len != 2)
1631
25.2k
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
1632
25.2k
        "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
25.2k
  sc_format_path("11001101", &dummy_path);
1641
25.2k
  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
25.2k
  path_start = pgp_strip_path(card, path);
1653
1654
  /* starting with the MF ... */
1655
25.2k
  blob = priv->mf;
1656
  /* ... recurse through the tree following the path */
1657
40.9k
  for (n = path_start; n < path->len; n += 2) {
1658
30.7k
    unsigned int  id = bebytes2ushort(path->value + n);
1659
30.7k
    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
30.7k
    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
30.7k
    if (r < 0) { /* failure */
1675
15.0k
      LOG_FUNC_RETURN(card->ctx, r);
1676
15.0k
    }
1677
30.7k
  }
1678
1679
  /* success: select file = set "current" pointer to blob found */
1680
10.2k
  priv->current = blob;
1681
1682
10.2k
  if (ret)
1683
4.39k
    sc_file_dup(ret, blob->file);
1684
1685
10.2k
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
1686
10.2k
}
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.21k
{
1695
1.21k
  struct pgp_priv_data *priv = DRVDATA(card);
1696
1.21k
  pgp_blob_t  *blob;
1697
1.21k
  unsigned int  k;
1698
1.21k
  int   r;
1699
1700
1.21k
  LOG_FUNC_CALLED(card->ctx);
1701
1702
  /* jump to selected file */
1703
1.21k
  blob = priv->current;
1704
1705
1.21k
  if (blob->file->type != SC_FILE_TYPE_DF)
1706
1.21k
    LOG_TEST_RET(card->ctx, SC_ERROR_OBJECT_NOT_VALID,
1707
1.21k
        "invalid file type");
1708
1709
1.21k
  if ((r = pgp_enumerate_blob(card, blob)) < 0)
1710
1.21k
    LOG_FUNC_RETURN(card->ctx, r);
1711
1712
22.7k
  for (k = 0, blob = blob->files; blob != NULL; blob = blob->next) {
1713
21.5k
    if (blob->info != NULL && (blob->info->access & READ_MASK) != READ_NEVER) {
1714
21.5k
      if (k + 2 > buflen)
1715
21.5k
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_BUFFER_TOO_SMALL);
1716
1717
21.5k
      ushort2bebytes(buf + k, blob->id);
1718
21.5k
      k += 2;
1719
21.5k
    }
1720
21.5k
  }
1721
1722
1.21k
  LOG_FUNC_RETURN(card->ctx, k);
1723
1.21k
}
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.68k
{
1732
1.68k
  struct pgp_priv_data *priv;
1733
1734
1.68k
  LOG_FUNC_CALLED(card->ctx);
1735
1736
1.68k
  priv = DRVDATA(card);
1737
1.68k
  if (0 == (priv->ext_caps & EXT_CAP_GET_CHALLENGE)) {
1738
694
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
1739
694
  }
1740
1741
990
  if (priv->max_challenge_size > 0 && len > priv->max_challenge_size) {
1742
201
    len = priv->max_challenge_size;
1743
201
  }
1744
1745
990
  LOG_FUNC_RETURN(card->ctx, iso_ops->get_challenge(card, rnd, len));
1746
990
}
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
6.37k
{
1756
6.37k
  struct pgp_priv_data *priv = DRVDATA(card);
1757
6.37k
  pgp_blob_t  *blob;
1758
6.37k
  int   r;
1759
1760
6.37k
  LOG_FUNC_CALLED(card->ctx);
1761
1762
  /* jump to selected file */
1763
6.37k
  blob = priv->current;
1764
1765
6.37k
  if (blob == NULL)
1766
6.37k
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND);
1767
1768
6.37k
  if (blob->file->type != SC_FILE_TYPE_WORKING_EF)
1769
6.37k
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND);
1770
1771
6.37k
  if ((r = pgp_read_blob(card, blob)) < 0)
1772
6.37k
    LOG_FUNC_RETURN(card->ctx, r);
1773
1774
6.11k
  if (idx > blob->len)
1775
6.11k
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
1776
1777
6.11k
  if (idx + count > blob->len)
1778
101
    count = blob->len - idx;
1779
6.11k
  memcpy(buf, blob->data + idx, count);
1780
1781
6.11k
  LOG_FUNC_RETURN(card->ctx, (int)count);
1782
6.11k
}
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
3.66k
{
1791
3.66k
  sc_apdu_t apdu;
1792
3.66k
  u8 apdu_case = (card->type == SC_CARD_TYPE_OPENPGP_GNUK)
1793
3.66k
      ? SC_APDU_CASE_4_SHORT : SC_APDU_CASE_4;
1794
3.66k
  u8    idbuf[2];
1795
3.66k
  int   r;
1796
1797
3.66k
  sc_log(card->ctx, "called, tag=%04x\n", tag);
1798
1799
3.66k
  sc_format_apdu(card, &apdu, apdu_case, 0x47, 0x81, 0);
1800
3.66k
  apdu.lc = 2;
1801
3.66k
  apdu.data = ushort2bebytes(idbuf, tag);
1802
3.66k
  apdu.datalen = 2;
1803
3.66k
  apdu.le = ((buf_len >= 256) && !(card->caps & SC_CARD_CAP_APDU_EXT)) ? 256 : buf_len;
1804
3.66k
  apdu.resp = buf;
1805
3.66k
  apdu.resplen = buf_len;
1806
1807
3.66k
  r = sc_transmit_apdu(card, &apdu);
1808
3.66k
  LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
1809
1810
3.61k
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1811
3.61k
  LOG_TEST_RET(card->ctx, r, "Card returned error");
1812
1813
173
  LOG_FUNC_RETURN(card->ctx, (int)apdu.resplen);
1814
173
}
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
27
{
1823
27
  struct pgp_priv_data *priv = DRVDATA(card);
1824
27
  pgp_blob_t  *blob, *mod_blob, *exp_blob, *pubkey_blob, *blob6e, *blob73, *aa_blob;
1825
27
  sc_pkcs15_pubkey_t p15pubkey;
1826
27
  sc_cardctl_openpgp_key_gen_store_info_t key_info;
1827
27
  unsigned int  aa_tag = 0;
1828
27
  u8    *data = NULL;
1829
27
  size_t    len = 0;
1830
27
  int   r;
1831
1832
27
  sc_log(card->ctx, "called, tag=%04x\n", tag);
1833
27
  memset(&p15pubkey, 0, sizeof(p15pubkey));
1834
1835
27
  if ((r = pgp_get_blob(card, priv->mf, tag & 0xFFFE, &blob)) < 0
1836
27
    || (r = pgp_get_blob(card, blob, 0x7F49, &blob)) < 0)
1837
27
    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
313
{
1957
313
  sc_apdu_t apdu;
1958
313
  u8  apdu_data[6];
1959
313
  int r;
1960
313
  struct pgp_priv_data *priv = DRVDATA(card);
1961
1962
313
  LOG_FUNC_CALLED(card->ctx);
1963
1964
313
  if (priv->bcd_version < OPENPGP_CARD_3_0)
1965
313
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
1966
1967
129
  sc_log(card->ctx, "select data with: %u", p1);
1968
1969
  // create apdu data (taken from spec: SELECT DATA 7.2.5.)
1970
129
  apdu_data[0] = 0x60;
1971
129
  apdu_data[1] = 0x04;
1972
129
  apdu_data[2] = 0x5c;
1973
129
  apdu_data[3] = 0x02;
1974
129
  apdu_data[4] = 0x7f;
1975
129
  apdu_data[5] = 0x21;
1976
1977
  // apdu, cla, ins, p1, p2, data, datalen, resp, resplen
1978
129
  sc_format_apdu_ex(&apdu, 0x00, 0xA5, p1, 0x04, apdu_data, sizeof(apdu_data), NULL, 0);
1979
1980
  // transmit apdu
1981
129
  r = sc_transmit_apdu(card, &apdu);
1982
129
  LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
1983
116
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1984
116
  LOG_TEST_RET(card->ctx, r, "Card returned error");
1985
34
  LOG_FUNC_RETURN(card->ctx, r);
1986
34
}
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
825k
{
1995
825k
  sc_apdu_t apdu;
1996
825k
  int   r;
1997
1998
825k
  LOG_FUNC_CALLED(card->ctx);
1999
2000
825k
  sc_format_apdu(card, &apdu, SC_APDU_CASE_2, 0xCA, tag >> 8, tag);
2001
825k
  apdu.le = ((buf_len >= 256) && !(card->caps & SC_CARD_CAP_APDU_EXT)) ? 256 : buf_len;
2002
825k
  apdu.resp = buf;
2003
825k
  apdu.resplen = buf_len;
2004
2005
825k
  r = sc_transmit_apdu(card, &apdu);
2006
825k
  LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
2007
2008
807k
  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
807k
  if (card->type == SC_CARD_TYPE_OPENPGP_GNUK &&
2013
9.41k
      (tag == DO_CERT  ||
2014
9.07k
       tag == DO_PRIV1 ||
2015
9.02k
       tag == DO_PRIV2 ||
2016
8.98k
       tag == DO_PRIV3 ||
2017
8.95k
       tag == DO_PRIV4)) {
2018
492
    if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) {
2019
4
      r = SC_SUCCESS;
2020
4
      apdu.resplen = 0;
2021
4
    }
2022
492
  }
2023
807k
  LOG_TEST_RET(card->ctx, r, "Card returned error");
2024
2025
115k
  LOG_FUNC_RETURN(card->ctx, (int)apdu.resplen);
2026
115k
}
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
80
{
2034
80
  size_t i = 0;
2035
80
  sc_apdu_t apdu;
2036
80
  int r = SC_SUCCESS;
2037
2038
80
  LOG_FUNC_CALLED(card->ctx);
2039
2040
  /* If null data is passed, delete certificate */
2041
80
  if (buf == NULL || length == 0) {
2042
19
    sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xD6, 0x85, 0);
2043
19
    r = sc_transmit_apdu(card, &apdu);
2044
19
    LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
2045
    /* Check response */
2046
18
    LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
2047
18
  }
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
585
  for (i = 0; i*256 < length; i++) {
2053
565
    u8 *part = (u8 *)buf + i*256;
2054
565
    size_t plen = MIN(length - i*256, 256);
2055
565
    u8 roundbuf[256]; /* space to build APDU data with even length for Gnuk */
2056
2057
565
    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
565
    sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xD6, (i == 0) ? 0x85 : (int)i, 0);
2061
565
    apdu.flags |= SC_APDU_FLAGS_CHAINING;
2062
565
    apdu.data = part;
2063
565
    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
565
    if (plen < 256 && (plen % 2) != 0) {
2068
22
      memcpy(roundbuf, part, plen);
2069
22
      roundbuf[plen++] = 0;
2070
22
      apdu.data = roundbuf;
2071
22
      apdu.datalen = apdu.lc = plen;
2072
22
    }
2073
2074
565
    r = sc_transmit_apdu(card, &apdu);
2075
565
    LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
2076
    /* Check response */
2077
541
    LOG_TEST_RET(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2), "UPDATE BINARY returned error");
2078
541
  }
2079
2080
20
  LOG_FUNC_RETURN(card->ctx, (int)length);
2081
20
}
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
575
{
2090
575
  struct pgp_priv_data *priv = DRVDATA(card);
2091
575
  sc_apdu_t apdu;
2092
575
  u8 ins = 0xDA;
2093
575
  u8 p1 = tag >> 8;
2094
575
  u8 p2 = tag & 0xFF;
2095
575
  u8 apdu_case = (card->type == SC_CARD_TYPE_OPENPGP_GNUK)
2096
575
      ? SC_APDU_CASE_3_SHORT : SC_APDU_CASE_3;
2097
575
  int r;
2098
2099
575
  LOG_FUNC_CALLED(card->ctx);
2100
2101
  /* Extended Header list (DO 004D) needs a variant of PUT DATA command */
2102
575
  if (tag == 0x004D) {
2103
3
    ins = 0xDB;
2104
3
    p1 = 0x3F;
2105
3
    p2 = 0xFF;
2106
3
  }
2107
2108
  /* build APDU */
2109
575
  if (buf != NULL && buf_len > 0) {
2110
466
    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
466
    if (((card->caps & SC_CARD_CAP_APDU_EXT) == 0) && (priv->ext_caps & EXT_CAP_CHAINING))
2114
30
      apdu.flags |= SC_APDU_FLAGS_CHAINING;
2115
2116
466
    apdu.data = (u8 *)buf;
2117
466
    apdu.datalen = buf_len;
2118
466
    apdu.lc = buf_len;
2119
466
  }
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
575
  r = sc_transmit_apdu(card, &apdu);
2127
575
  LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
2128
  /* check response */
2129
560
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
2130
560
  LOG_TEST_RET(card->ctx, r, "Card returned error");
2131
2132
206
  LOG_FUNC_RETURN(card->ctx, (int)buf_len);
2133
206
}
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.64k
{
2142
1.64k
  struct pgp_priv_data *priv = DRVDATA(card);
2143
1.64k
  pgp_blob_t *affected_blob = NULL;
2144
1.64k
  pgp_do_info_t *dinfo = NULL;
2145
1.64k
  int r;
2146
2147
1.64k
  LOG_FUNC_CALLED(card->ctx);
2148
2149
  /* Check if there is a blob for the given tag */
2150
1.64k
  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.64k
  if (affected_blob == NULL)
2154
1.16k
    dinfo = pgp_get_info_by_tag(card, tag);
2155
482
  else
2156
482
    dinfo = affected_blob->info;
2157
2158
  /* Make sure the DO exists and is writeable */
2159
1.64k
  if (dinfo == NULL) {
2160
965
    sc_log(card->ctx, "The DO %04X does not exist.", tag);
2161
965
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
2162
965
  }
2163
680
  else if ((dinfo->access & WRITE_MASK) == WRITE_NEVER) {
2164
17
    sc_log(card->ctx, "DO %04X is not writable.", tag);
2165
17
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ALLOWED);
2166
17
  }
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
663
  if (tag == DO_CERT && buf_len > priv->max_cert_size) {
2174
8
    sc_log(card->ctx, "Data size %zu exceeds DO size limit %zu.", buf_len, priv->max_cert_size);
2175
8
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_WRONG_LENGTH);
2176
8
  }
2177
2178
655
  if (tag == DO_CERT && card->type == SC_CARD_TYPE_OPENPGP_GNUK) {
2179
    /* Gnuk need a special way to write certificate. */
2180
80
    r = gnuk_write_certificate(card, buf, buf_len);
2181
80
  }
2182
575
  else {
2183
575
    r = pgp_put_data_plain(card, tag, buf, buf_len);
2184
575
  }
2185
2186
  /* instruct more in case of error */
2187
655
  if (r == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {
2188
2
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Please verify PIN first.");
2189
2
  }
2190
655
  LOG_TEST_RET(card->ctx, r, "PUT DATA returned error");
2191
2192
226
  if (affected_blob) {
2193
    /* update the corresponding file */
2194
189
    sc_log(card->ctx, "Updating the corresponding blob data");
2195
189
    r = pgp_set_blob(affected_blob, buf, buf_len);
2196
189
    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
189
  }
2200
2201
226
  LOG_FUNC_RETURN(card->ctx, (int)buf_len);
2202
226
}
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
1.77k
{
2389
1.77k
  struct pgp_priv_data *priv = DRVDATA(card);
2390
1.77k
  struct sc_card_operations ops = {.pin_cmd = iso_ops->pin_cmd};
2391
2392
1.77k
  LOG_FUNC_CALLED(card->ctx);
2393
2394
1.77k
  if (data->pin_type != SC_AC_CHV)
2395
1.77k
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2396
1.77k
        "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
1.77k
  data->pin_reference |= 0x80;
2423
2424
  /* check version-dependent constraints */
2425
1.77k
  if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) {
2426
204
    if (priv->bcd_version >= OPENPGP_CARD_2_0) {
2427
187
      if (data->pin_reference == 0x82)
2428
83
        data->pin_reference = 0x81;
2429
2430
187
      if (data->cmd == SC_PIN_CMD_CHANGE) {
2431
104
        if (data->pin1.len == 0 &&
2432
0
            !(data->flags & SC_PIN_CMD_USE_PINPAD))
2433
104
          LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2434
104
              "v2 cards don't support implicit old PIN for PIN change");
2435
2436
104
        data->flags &= ~SC_PIN_CMD_IMPLICIT_CHANGE;
2437
104
      }
2438
187
    } else {
2439
17
      if (data->pin1.len != 0) {
2440
17
        sc_log(card->ctx,
2441
17
               "v1 cards don't support explicit old or CHV3 PIN, PIN ignored.");
2442
17
        sc_log(card->ctx,
2443
17
               "please make sure that you have verified the relevant PIN first.");
2444
17
        data->pin1.len = 0;
2445
17
      }
2446
2447
17
      data->flags |= SC_PIN_CMD_IMPLICIT_CHANGE;
2448
17
    }
2449
204
  }
2450
2451
1.77k
  if (data->cmd == SC_PIN_CMD_UNBLOCK && data->pin2.len == 0 &&
2452
0
      !(data->flags & SC_PIN_CMD_USE_PINPAD))
2453
1.77k
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2454
1.77k
        "new PIN must be provided for unblock operation");
2455
2456
  /* ensure pin_reference is 81, 82, 83 */
2457
1.77k
  if (data->pin_reference < 0x81 || data->pin_reference > 0x83)
2458
1.77k
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2459
1.74k
        "Invalid key ID; must be 1, 2, or 3");
2460
2461
  /* emulate SC_PIN_CMD_GET_INFO command for cards not supporting it */
2462
1.74k
  if (data->cmd == SC_PIN_CMD_GET_INFO && (card->caps & SC_CARD_CAP_ISO7816_PIN_INFO) == 0) {
2463
481
    u8 c4data[10];
2464
481
    int r;
2465
2466
481
    r = sc_get_data(card, 0x00c4, c4data, sizeof(c4data));
2467
481
    LOG_TEST_RET(card->ctx, r, "reading CHV status bytes failed");
2468
2469
84
    if (r != 7)
2470
84
      LOG_TEST_RET(card->ctx, SC_ERROR_OBJECT_NOT_VALID,
2471
29
        "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
29
    if (priv->bcd_version >= OPENPGP_CARD_2_0 && data->pin_reference == 0x82)
2479
8
      data->pin_reference = 0x81;
2480
2481
29
    data->pin1.tries_left = c4data[3 + (data->pin_reference & 0x0F)];
2482
29
    data->pin1.max_tries = 3;
2483
29
    data->pin1.logged_in = SC_PIN_STATE_UNKNOWN;
2484
2485
29
    LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
2486
29
  }
2487
2488
1.26k
#ifdef ENABLE_OPENSSL
2489
1.26k
  if (priv->pin_kdf_info) {
2490
0
    ops.pin_cmd = &pgp_kdf_do_pin_cmd;
2491
0
  }
2492
1.26k
#endif /* ENABLE_OPENSSL */
2493
2494
1.26k
  LOG_FUNC_RETURN(card->ctx, ops.pin_cmd(card, data));
2495
1.26k
}
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
379
{
2539
379
  struct pgp_priv_data *priv = DRVDATA(card);
2540
2541
379
  LOG_FUNC_CALLED(card->ctx);
2542
2543
  /* The SC_SEC_ENV_ALG_PRESENT is set always so let it pass for GNUK */
2544
379
  if ((env->flags & SC_SEC_ENV_ALG_PRESENT)
2545
379
    && (env->algorithm != SC_ALGORITHM_RSA)
2546
0
    && (priv->bcd_version < OPENPGP_CARD_3_0)
2547
0
    && (card->type != SC_CARD_TYPE_OPENPGP_GNUK))
2548
379
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2549
379
        "only RSA algorithm supported");
2550
2551
379
  if (!(env->flags & SC_SEC_ENV_KEY_REF_PRESENT) || (env->key_ref_len != 1))
2552
379
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2553
379
        "exactly one key reference required");
2554
2555
379
  if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT)
2556
379
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2557
379
      "passing file references not supported");
2558
2559
379
  sc_log(card->ctx, "Key ref %d", env->key_ref[0]);
2560
379
  switch (env->operation) {
2561
291
  case SC_SEC_OPERATION_SIGN:
2562
291
    sc_log(card->ctx, "Operation: Sign.");
2563
291
    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
291
    break;
2569
291
  case SC_SEC_OPERATION_DECIPHER:
2570
88
    sc_log(card->ctx, "Operation: Decipher.");
2571
    /* we allow key ref 2 (auth key) to be used for deciphering */
2572
88
    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
88
    break;
2578
88
  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
379
        "invalid operation");
2584
379
  }
2585
2586
379
  priv->sec_env = *env;
2587
2588
379
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
2589
379
}
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
18
{
2605
18
  struct pgp_priv_data  *priv = DRVDATA(card);
2606
18
  sc_apdu_t apdu;
2607
18
  u8  apdu_case = SC_APDU_CASE_3;
2608
18
  u8  apdu_data[3];
2609
18
  int r;
2610
2611
18
  LOG_FUNC_CALLED(card->ctx);
2612
2613
  // check if MSE is supported
2614
18
  if (!(priv->ext_caps & EXT_CAP_MSE))
2615
18
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
2616
2617
  // create apdu
2618
18
  sc_format_apdu(card, &apdu, apdu_case, 0x22, 0x41, p2);
2619
18
  apdu.lc = 3;
2620
18
  apdu_data[0] = 0x83;
2621
18
  apdu_data[1] = 0x01;
2622
18
  apdu_data[2] = key;
2623
18
  apdu.data = apdu_data;
2624
18
  apdu.datalen = 3;
2625
2626
  // transmit apdu
2627
18
  r = sc_transmit_apdu(card, &apdu);
2628
18
  LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
2629
2630
15
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
2631
15
  LOG_TEST_RET(card->ctx, r, "Card returned error");
2632
2633
3
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
2634
3
}
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
291
{
2644
291
  struct pgp_priv_data  *priv = DRVDATA(card);
2645
291
  sc_security_env_t *env = &priv->sec_env;
2646
291
  sc_apdu_t   apdu;
2647
291
  u8 apdu_case = (card->type == SC_CARD_TYPE_OPENPGP_GNUK)
2648
291
      ? SC_APDU_CASE_4_SHORT : SC_APDU_CASE_4;
2649
291
  int     r;
2650
2651
291
  LOG_FUNC_CALLED(card->ctx);
2652
2653
291
  if (env->operation != SC_SEC_OPERATION_SIGN)
2654
291
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2655
291
        "invalid operation");
2656
2657
291
  switch (env->key_ref[0]) {
2658
113
  case 0x00: /* signature key */
2659
    /* PSO SIGNATURE */
2660
113
    sc_format_apdu(card, &apdu, apdu_case, 0x2A, 0x9E, 0x9A);
2661
113
    break;
2662
178
  case 0x02: /* authentication key */
2663
    /* INTERNAL AUTHENTICATE */
2664
178
    sc_format_apdu(card, &apdu, apdu_case, 0x88, 0, 0);
2665
178
    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
291
      "invalid key reference");
2673
291
  }
2674
2675
  /* if card/reader does not support extended APDUs, but chaining, then set it */
2676
291
  if (((card->caps & SC_CARD_CAP_APDU_EXT) == 0) && (priv->ext_caps & EXT_CAP_CHAINING))
2677
105
    apdu.flags |= SC_APDU_FLAGS_CHAINING;
2678
2679
291
  apdu.lc = data_len;
2680
291
  apdu.data = (u8 *)data;
2681
291
  apdu.datalen = data_len;
2682
291
  apdu.le = ((outlen >= 256) && !(card->caps & SC_CARD_CAP_APDU_EXT)) ? 256 : outlen;
2683
291
  apdu.resp    = out;
2684
291
  apdu.resplen = outlen;
2685
2686
291
  r = sc_transmit_apdu(card, &apdu);
2687
291
  LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
2688
2689
169
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
2690
169
  LOG_TEST_RET(card->ctx, r, "Card returned error");
2691
2692
38
  LOG_FUNC_RETURN(card->ctx, (int)apdu.resplen);
2693
38
}
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
83
{
2703
83
  struct pgp_priv_data  *priv = DRVDATA(card);
2704
83
  sc_security_env_t *env = &priv->sec_env;
2705
83
  sc_apdu_t apdu;
2706
83
  u8 apdu_case = SC_APDU_CASE_4;
2707
83
  u8    *temp = NULL, *p = NULL;
2708
83
  size_t    templen, pklen, dolen;
2709
83
  int   r;
2710
2711
83
  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
83
  templen = inlen + 10;
2716
83
  if (!(temp = malloc(templen)))
2717
83
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
2718
2719
  /* padding byte: 0xa6 = ECC; 0x00 = RSA; 0x02 = AES */
2720
83
  switch (env->algorithm) {
2721
83
  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
83
    temp[0] = 0x00;
2726
83
    memcpy(temp + 1, in, inlen);
2727
83
    inlen += 1;
2728
83
    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
83
  }
2783
2784
83
  in = temp;
2785
2786
83
  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
83
  switch (env->key_ref[0]) {
2794
70
  case 0x01: /* Decryption key */
2795
83
  case 0x02: /* authentication key */
2796
    /* PSO DECIPHER */
2797
83
    sc_format_apdu(card, &apdu, apdu_case, 0x2A, 0x80, 0x86);
2798
83
    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
83
        "invalid key reference");
2804
83
  }
2805
2806
  /* Gnuk only supports short APDU, so we need to use command chaining */
2807
83
  if (card->type == SC_CARD_TYPE_OPENPGP_GNUK) {
2808
22
    apdu.flags |= SC_APDU_FLAGS_CHAINING;
2809
22
  }
2810
  /* if card/reader does not support extended APDUs, but chaining, then set it */
2811
83
  if (((card->caps & SC_CARD_CAP_APDU_EXT) == 0) && (priv->ext_caps & EXT_CAP_CHAINING))
2812
26
    apdu.flags |= SC_APDU_FLAGS_CHAINING;
2813
2814
83
  apdu.lc = inlen;
2815
83
  apdu.data = (u8 *)in;
2816
83
  apdu.datalen = inlen;
2817
83
  apdu.le = ((outlen >= 256) && !(card->caps & SC_CARD_CAP_APDU_EXT)) ? 256 : outlen;
2818
83
  apdu.resp = out;
2819
83
  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
83
  if (priv->bcd_version >= OPENPGP_CARD_3_3 && env->key_ref[0] == 0x02){
2825
13
    pgp_set_MSE(card, 3, 0xb8);
2826
13
  }
2827
2828
83
  r = sc_transmit_apdu(card, &apdu);
2829
83
  free(temp);
2830
83
  LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
2831
2832
69
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
2833
69
  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
14
  if (priv->bcd_version >= OPENPGP_CARD_3_3 && env->key_ref[0] == 0x02){
2837
5
    pgp_set_MSE(card, 2, 0xb8);
2838
5
  }
2839
2840
14
  LOG_FUNC_RETURN(card->ctx, (int)apdu.resplen);
2841
14
}
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
274
{
2851
274
  struct pgp_priv_data *priv = DRVDATA(card);
2852
274
  pgp_blob_t *algo_blob = NULL;
2853
274
  const unsigned int tag = 0x00C0 | key_info->key_id;
2854
274
  int r = SC_SUCCESS;
2855
274
  unsigned int i;
2856
2857
274
  LOG_FUNC_CALLED(card->ctx);
2858
2859
274
  r = pgp_seek_blob(card, priv->mf, tag, &algo_blob);
2860
274
  LOG_TEST_RET(card->ctx, r, "Cannot get old algorithm attributes");
2861
2862
240
  if (priv->ext_caps & EXT_CAP_ALG_ATTR_CHANGEABLE) {
2863
    /* ECDSA and ECDH */
2864
231
    if (key_info->algorithm == SC_OPENPGP_KEYALGO_ECDH
2865
231
        || key_info->algorithm == SC_OPENPGP_KEYALGO_ECDSA
2866
218
        || key_info->algorithm == SC_OPENPGP_KEYALGO_EDDSA){
2867
      /* Note OpenPGP or current cards do not support 448 size keys yet */
2868
13
      unsigned char *aoid = NULL; /* ASN1 */
2869
13
      size_t aoid_len;
2870
13
      struct sc_object_id *scoid = NULL;
2871
2872
13
      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
39
      for (i = 0; ec_curves_alt[i].size > 0; i++) {
2878
26
        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
26
      }
2883
2884
13
      r = sc_encode_oid(card->ctx, scoid, &aoid, &aoid_len);
2885
13
      LOG_TEST_RET(card->ctx, r, "invalid ec oid");
2886
13
      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
13
      key_info->data_len = aoid_len + 1 - 2; /* +1 for algorithm -2 drop 06 len */
2892
13
      key_info->data = malloc(key_info->data_len);
2893
13
      if (!key_info->data) {
2894
0
        free(aoid);
2895
0
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ENOUGH_MEMORY);
2896
0
      }
2897
2898
13
      key_info->data[0] = key_info->algorithm;
2899
117
      for (i = 0; i < aoid_len - 2; i++)
2900
104
        key_info->data[i + 1] = aoid[i + 2];
2901
2902
13
      free(aoid);
2903
13
    }
2904
2905
    /* RSA */
2906
218
    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
218
      if (key_info->u.rsa.exponent_len == 0 || key_info->u.rsa.modulus_len == 0)
2910
218
        LOG_FUNC_RETURN(card->ctx,SC_ERROR_INVALID_ARGUMENTS);
2911
2912
218
      key_info->data_len = 6;
2913
218
      key_info->data = malloc(key_info->data_len);
2914
218
      if (!key_info->data)
2915
218
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ENOUGH_MEMORY);
2916
2917
218
      key_info->data[0] = key_info->algorithm;
2918
218
      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
218
      ushort2bebytes(key_info->data + 3, SC_OPENPGP_MAX_EXP_BITS);
2923
      /* Import-Format of private key (e,p,q) */
2924
218
      key_info->data[5] = SC_OPENPGP_KEYFORMAT_RSA_STD;
2925
218
    }
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
231
    r = pgp_put_data(card, tag, key_info->data, key_info->data_len);
2932
    /* Note: pgp_put_data calls pgp_set_blob */
2933
231
    LOG_TEST_RET(card->ctx, r, "Cannot set new algorithm attributes");
2934
231
  } else {
2935
9
    sc_cardctl_openpgp_key_gen_store_info_t old_key_info;
2936
2937
9
    if (pgp_parse_algo_attr_blob(card, algo_blob, &old_key_info) != SC_SUCCESS
2938
5
        || old_key_info.algorithm != key_info->algorithm)
2939
9
      LOG_TEST_RET(card->ctx, SC_ERROR_NO_CARD_SUPPORT,
2940
9
          "Requested algorithm not supported");
2941
    /* FIXME check whether the static parameters match the requested ones. */
2942
9
  }
2943
2944
135
  LOG_FUNC_RETURN(card->ctx, r);
2945
135
}
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
128
{
2957
128
  int r;
2958
128
  time_t createtime = 0;
2959
128
  const size_t timestrlen = 64;
2960
128
  char timestring[65];
2961
128
  u8 buf[4];
2962
128
  struct tm tm;
2963
2964
128
  LOG_FUNC_CALLED(card->ctx);
2965
2966
128
  if (key_id < 1 || key_id > 3)
2967
128
    LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
2968
128
        "Invalid key ID; must be 1, 2, or 3");
2969
2970
128
  if (outtime != NULL && *outtime != 0)
2971
0
    createtime = *outtime;
2972
128
  else if (outtime != NULL)
2973
    /* set output */
2974
128
    *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
128
  if (NULL == gmtime_r(&createtime, &tm))
2981
128
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
2982
128
#endif
2983
128
  strftime(timestring, timestrlen, "%c %Z", &tm);
2984
128
  sc_log(card->ctx, "Creation time %s.", timestring);
2985
  /* Code borrowed from GnuPG */
2986
128
  ulong2bebytes(buf, (unsigned long)createtime);
2987
128
  r = pgp_put_data(card, 0x00CD + key_id, buf, 4);
2988
128
  LOG_TEST_RET(card->ctx, r, "Cannot write to DO");
2989
23
  LOG_FUNC_RETURN(card->ctx, r);
2990
23
}
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
58
{
3001
58
  u8 fingerprint[SHA_DIGEST_LENGTH];
3002
58
  u8 *fp_buffer = NULL;  /* fingerprint buffer, not hashed */
3003
58
  size_t fp_buffer_len;
3004
58
  u8 *p; /* use this pointer to set fp_buffer content */
3005
58
  size_t pk_packet_len;
3006
58
  unsigned int tag = 0x00C6 + key_info->key_id;
3007
58
  pgp_blob_t *fpseq_blob = NULL;
3008
58
  u8 *newdata = NULL;
3009
58
  int r;
3010
3011
58
  LOG_FUNC_CALLED(card->ctx);
3012
3013
  /* constructing public-key packet length */
3014
  /* RSA */
3015
58
  if (key_info->algorithm == SC_OPENPGP_KEYALGO_RSA) {
3016
3017
56
    if (key_info->u.rsa.modulus == NULL
3018
56
      || key_info->u.rsa.exponent == NULL
3019
56
      || (key_info->u.rsa.modulus_len) == 0
3020
55
      || (key_info->u.rsa.exponent_len) == 0) {
3021
3022
3
      sc_log(card->ctx, "Null data (modulus or exponent)");
3023
3
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
3024
3
    }
3025
3026
    /* https://tools.ietf.org/html/rfc4880  page 41, 72 */
3027
53
    pk_packet_len =   1   /* version number */
3028
53
        + 4   /* creation time */
3029
53
        + 1   /* algorithm */
3030
53
        + 2   /* algorithm-specific fields: RSA modulus+exponent */
3031
53
        + (BYTES4BITS(key_info->u.rsa.modulus_len))
3032
53
        + 2
3033
53
        + (BYTES4BITS(key_info->u.rsa.exponent_len));
3034
3035
53
  }
3036
  /* ECC */
3037
2
  else if (key_info->algorithm == SC_OPENPGP_KEYALGO_ECDH || /* also includes XEDDSA */
3038
2
      key_info->algorithm == SC_OPENPGP_KEYALGO_ECDSA ||
3039
2
      key_info->algorithm == SC_OPENPGP_KEYALGO_EDDSA) {
3040
2
    if (key_info->u.ec.ecpointQ == NULL || (key_info->u.ec.ecpointQ_len) == 0) {
3041
2
      sc_log(card->ctx, "Error: ecpoint required!");
3042
2
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
3043
2
    }
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
53
  sc_log(card->ctx, "pk_packet_len is %zu", pk_packet_len);
3065
3066
53
  fp_buffer_len = 3 + pk_packet_len;
3067
53
  p = fp_buffer = calloc(1, fp_buffer_len);
3068
53
  if (p == NULL)
3069
53
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ENOUGH_MEMORY);
3070
3071
  /* constructing public-key packet */
3072
53
  p[0] = 0x99;   /* http://tools.ietf.org/html/rfc4880  page 71 */
3073
53
  ushort2bebytes(++p, (unsigned short)pk_packet_len);
3074
  /* start pk_packet */
3075
53
  p += 2;
3076
53
  *p = 4;        /* Version 4 key */
3077
53
  ulong2bebytes(++p, (unsigned long)ctime);    /* Creation time */
3078
53
  p += 4;
3079
3080
  /* RSA */
3081
53
  if (key_info->algorithm == SC_OPENPGP_KEYALGO_RSA) {
3082
53
    unsigned short bytes_length = 0;
3083
3084
53
    *p = 1; /* Algorithm ID, RSA */
3085
53
    p += 1;
3086
3087
    /* Modulus */
3088
53
    bytes_length = BYTES4BITS(key_info->u.rsa.modulus_len);
3089
53
    ushort2bebytes(p, (unsigned short)key_info->u.rsa.modulus_len);
3090
53
    p += 2;
3091
53
    memcpy(p, key_info->u.rsa.modulus, bytes_length);
3092
53
    p += bytes_length;
3093
3094
    /* Exponent */
3095
53
    bytes_length = BYTES4BITS(key_info->u.rsa.exponent_len);
3096
53
    ushort2bebytes(p, (unsigned short)key_info->u.rsa.exponent_len);
3097
53
    p += 2;
3098
53
    memcpy(p, key_info->u.rsa.exponent, bytes_length);
3099
53
  }
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
53
  p = NULL;
3137
3138
  /* hash with SHA-1 */
3139
53
  SHA1(fp_buffer, fp_buffer_len, fingerprint);
3140
53
  free(fp_buffer);
3141
3142
  /* store to DO */
3143
53
  sc_log(card->ctx, "Writing to DO %04X.", tag);
3144
53
  r = pgp_put_data(card, tag, fingerprint, SHA_DIGEST_LENGTH);
3145
53
  LOG_TEST_RET(card->ctx, r, "Cannot write to DO");
3146
3147
  /* update the blob containing fingerprints (00C5) */
3148
20
  sc_log(card->ctx, "Updating fingerprint blob 00C5.");
3149
20
  fpseq_blob = pgp_find_blob(card, 0x00C5);
3150
20
  if (fpseq_blob == NULL) {
3151
15
    r = SC_ERROR_OUT_OF_MEMORY;
3152
15
    LOG_TEST_GOTO_ERR(card->ctx, r, "Cannot find blob 00C5");
3153
15
  }
3154
5
  if (20U * key_info->key_id > fpseq_blob->len) {
3155
1
    r = SC_ERROR_OBJECT_NOT_VALID;
3156
1
    LOG_TEST_GOTO_ERR(card->ctx, r, "The 00C5 blob is not large enough");
3157
1
  }
3158
3159
  /* save the fingerprints sequence */
3160
4
  newdata = malloc(fpseq_blob->len);
3161
4
  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
4
  memcpy(newdata, fpseq_blob->data, fpseq_blob->len);
3167
  /* move p to the portion holding the fingerprint of the current key */
3168
4
  p = newdata + 20 * (key_info->key_id - 1);
3169
  /* copy new fingerprint value */
3170
4
  memcpy(p, fingerprint, 20);
3171
  /* set blob's data */
3172
4
  pgp_set_blob(fpseq_blob, newdata, fpseq_blob->len);
3173
4
  free(newdata);
3174
3175
20
err:
3176
20
  LOG_FUNC_RETURN(card->ctx, r);
3177
20
}
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
4
{
3187
4
  struct pgp_priv_data *priv = DRVDATA(card);
3188
4
  pgp_blob_t *pk_blob;
3189
4
  unsigned int blob_id = 0;
3190
4
  sc_pkcs15_pubkey_t p15pubkey;
3191
4
  u8 *data = NULL;
3192
4
  size_t len;
3193
4
  int r;
3194
3195
4
  LOG_FUNC_CALLED(card->ctx);
3196
3197
4
  if (key_info->key_id == SC_OPENPGP_KEY_SIGN)
3198
0
    blob_id = DO_SIGN_SYM;
3199
4
  else if (key_info->key_id == SC_OPENPGP_KEY_ENCR)
3200
0
    blob_id = DO_ENCR_SYM;
3201
4
  else if (key_info->key_id == SC_OPENPGP_KEY_AUTH)
3202
4
    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
4
  sc_log(card->ctx, "Retrieving blob %04X.", blob_id);
3209
4
  r = pgp_get_blob(card, priv->mf, blob_id, &pk_blob);
3210
4
  LOG_TEST_RET(card->ctx, r, "Cannot get the blob");
3211
3212
  /* encode pubkey */
3213
  /* RSA */
3214
4
  if (key_info->algorithm == SC_OPENPGP_KEYALGO_RSA){
3215
4
    memset(&p15pubkey, 0, sizeof(p15pubkey));
3216
4
    p15pubkey.algorithm = SC_ALGORITHM_RSA;
3217
4
    p15pubkey.u.rsa.modulus.data  = key_info->u.rsa.modulus;
3218
4
    p15pubkey.u.rsa.modulus.len   = BYTES4BITS(key_info->u.rsa.modulus_len);
3219
4
    p15pubkey.u.rsa.exponent.data = key_info->u.rsa.exponent;
3220
4
    p15pubkey.u.rsa.exponent.len  = BYTES4BITS(key_info->u.rsa.exponent_len);
3221
4
  }
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
4
  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
4
  free(p15pubkey.alg_id);
3239
4
  p15pubkey.alg_id = NULL;
3240
4
  LOG_TEST_RET(card->ctx, r, "Cannot encode pubkey");
3241
3242
4
  sc_log(card->ctx, "Updating blob %04X's content.", blob_id);
3243
4
  r = pgp_set_blob(pk_blob, data, len);
3244
4
  free(data);
3245
4
  LOG_TEST_RET(card->ctx, r, "Cannot update blob content");
3246
4
  LOG_FUNC_RETURN(card->ctx, r);
3247
4
}
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
128
{
3257
128
  time_t ctime = 0;
3258
128
  u8 *in = data;
3259
128
  int r;
3260
128
  LOG_FUNC_CALLED(card->ctx);
3261
3262
  /* store creation time */
3263
128
  r = pgp_store_creationtime(card, key_info->key_id, &ctime);
3264
128
  if (r != SC_SUCCESS) {
3265
    /* TODO for now with GNUK at least, log but do not return error */
3266
128
    sc_log(card->ctx, "Cannot store creation time");
3267
128
  }
3268
3269
  /* parse response. Ref: pgp_enumerate_blob() */
3270
868
  while (data_len > (size_t) (in - data)) {
3271
810
    unsigned int cla, tag, tmptag;
3272
810
    size_t    len;
3273
810
    u8  *part = in;
3274
3275
    /* parse TLV structure */
3276
810
    r = sc_asn1_read_tag((const u8**)&part, data_len - (in - data), &cla, &tag, &len);
3277
810
    if (part == NULL)
3278
43
      r = SC_ERROR_ASN1_OBJECT_NOT_FOUND;
3279
810
    LOG_TEST_RET(card->ctx, r, "Unexpected end of contents");
3280
    /* undo ASN1's split of tag & class */
3281
933
    for (tmptag = tag; tmptag > 0x0FF; tmptag >>= 8) {
3282
189
      cla <<= 8;
3283
189
    }
3284
744
    tag |= cla;
3285
3286
    /* RSA modulus */
3287
744
    if (tag == 0x0081) {
3288
52
      if (key_info->algorithm != SC_OPENPGP_KEYALGO_RSA) {
3289
1
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
3290
1
      }
3291
51
      if ((BYTES4BITS(key_info->u.rsa.modulus_len) < len)  /* modulus_len is in bits */
3292
37
        || key_info->u.rsa.modulus == NULL) {
3293
3294
14
        free(key_info->u.rsa.modulus);
3295
14
        key_info->u.rsa.modulus = malloc(len);
3296
14
        if (key_info->u.rsa.modulus == NULL)
3297
14
          LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ENOUGH_MEMORY);
3298
14
      }
3299
3300
      /* set values */
3301
51
      memcpy(key_info->u.rsa.modulus, part, len);
3302
51
      key_info->u.rsa.modulus_len = len * 8; /* store length in bits */
3303
51
    }
3304
    /* RSA public exponent */
3305
692
    else if (tag == 0x0082) {
3306
111
      if (key_info->algorithm != SC_OPENPGP_KEYALGO_RSA) {
3307
1
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
3308
1
      }
3309
110
      if ((BYTES4BITS(key_info->u.rsa.exponent_len) < len)  /* exponent_len is in bits */
3310
64
        || key_info->u.rsa.exponent == NULL) {
3311
3312
46
        free(key_info->u.rsa.exponent);
3313
46
        key_info->u.rsa.exponent = malloc(len);
3314
46
        if (key_info->u.rsa.exponent == NULL)
3315
46
          LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ENOUGH_MEMORY);
3316
46
      }
3317
3318
      /* set values */
3319
110
      memcpy(key_info->u.rsa.exponent, part, len);
3320
110
      key_info->u.rsa.exponent_len = len * 8; /* store length in bits */
3321
110
    }
3322
    /* ECC or EDDSA public key */
3323
581
    else if (tag == 0x0086) {
3324
      /* Note: SC_OPENPGP_KEYALGO_ECDH could be either EC or XEDDSA */
3325
2
      if (key_info->algorithm != SC_OPENPGP_KEYALGO_ECDSA &&
3326
1
          key_info->algorithm != SC_OPENPGP_KEYALGO_ECDH &&
3327
1
          key_info->algorithm != SC_OPENPGP_KEYALGO_EDDSA) {
3328
1
        LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
3329
1
      }
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
1
      if (len != key_info->u.ec.ecpointQ_len)
3343
1
        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
740
    in = part + ((tag != 0x7F49) ? len : 0);
3363
740
  }
3364
3365
  /* calculate and store fingerprint */
3366
58
  sc_log(card->ctx, "Calculate and store fingerprint");
3367
58
  r = pgp_calculate_and_store_fingerprint(card, ctime, key_info);
3368
58
  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
4
  sc_log(card->ctx, "Update blobs holding pubkey info.");
3373
4
  r = pgp_update_pubkey_blob(card, key_info);
3374
3375
4
  LOG_FUNC_RETURN(card->ctx, r);
3376
4
}
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
4
{
3385
4
  sc_algorithm_info_t *algo;
3386
4
  u8 id = key_info->key_id;
3387
4
  struct pgp_priv_data *priv = DRVDATA(card);
3388
3389
4
  LOG_FUNC_CALLED(card->ctx);
3390
3391
  /* protect incompatible cards against non-RSA */
3392
4
  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
4
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
3396
3397
4
  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
4
  algo = card->algorithms + (id - 1);
3406
  /* update new key attribute */
3407
4
  if (key_info->algorithm == SC_OPENPGP_KEYALGO_RSA) {
3408
4
    algo->algorithm = SC_ALGORITHM_RSA;
3409
4
    algo->key_length = (unsigned int)key_info->u.rsa.modulus_len;
3410
4
  } 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
4
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
3419
4
}
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
275
{
3428
275
  sc_apdu_t apdu;
3429
  /* temporary variables to hold APDU params */
3430
275
  u8 apdu_case;
3431
275
  u8 apdu_data[2] = { 0x00, 0x00 };
3432
275
  size_t apdu_le;
3433
275
  size_t resplen = 0;
3434
275
  int r = SC_SUCCESS;
3435
275
  struct pgp_priv_data *priv = DRVDATA(card);
3436
3437
275
  LOG_FUNC_CALLED(card->ctx);
3438
3439
  /* protect incompatible cards against non-RSA */
3440
275
  if (key_info->algorithm != SC_OPENPGP_KEYALGO_RSA &&
3441
24
      priv->bcd_version < OPENPGP_CARD_3_0 &&
3442
1
      card->type != SC_CARD_TYPE_OPENPGP_GNUK)
3443
275
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
3444
3445
  /* set Control Reference Template for key */
3446
274
  if (key_info->key_id == SC_OPENPGP_KEY_SIGN)
3447
0
    ushort2bebytes(apdu_data, DO_SIGN);
3448
274
  else if (key_info->key_id == SC_OPENPGP_KEY_ENCR)
3449
0
    ushort2bebytes(apdu_data, DO_ENCR);
3450
274
  else if (key_info->key_id == SC_OPENPGP_KEY_AUTH)
3451
274
    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
274
  r = pgp_update_new_algo_attr(card, key_info);
3459
274
  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
135
  if (card->caps & SC_CARD_CAP_APDU_EXT
3465
4
    && key_info->u.rsa.modulus_len > 1900
3466
1
    && 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
1
    apdu_le = card->max_recv_size;
3470
1
    apdu_case = SC_APDU_CASE_4_EXT;
3471
1
  }
3472
134
  else {
3473
134
    apdu_case = SC_APDU_CASE_4_SHORT;
3474
134
    apdu_le = 256;
3475
134
    resplen = MAXLEN_RESP_PUBKEY;
3476
134
  }
3477
135
  if (card->type == SC_CARD_TYPE_OPENPGP_GNUK) {
3478
2
    resplen = MAXLEN_RESP_PUBKEY_GNUK;
3479
2
  }
3480
3481
  /* prepare APDU */
3482
135
  sc_format_apdu(card, &apdu, apdu_case, 0x47, 0x80, 0);
3483
135
  apdu.data = apdu_data;
3484
135
  apdu.datalen = sizeof(apdu_data);
3485
135
  apdu.lc = sizeof(apdu_data);
3486
135
  apdu.le = apdu_le;
3487
3488
  /* buffer to receive response */
3489
135
  apdu.resplen = (resplen > 0) ? resplen : apdu_le;
3490
135
  apdu.resp = calloc(1, apdu.resplen);
3491
135
  if (apdu.resp == NULL) {
3492
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_ENOUGH_MEMORY);
3493
0
  }
3494
3495
  /* send */
3496
135
  sc_log(card->ctx, "Waiting for the card to generate key...");
3497
135
  r = sc_transmit_apdu(card, &apdu);
3498
135
  sc_log(card->ctx, "Card has done key generation.");
3499
135
  LOG_TEST_GOTO_ERR(card->ctx, r, "APDU transmit failed");
3500
3501
  /* check response */
3502
134
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
3503
  /* instruct more in case of error */
3504
134
  if (r == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {
3505
1
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Please verify PIN first.");
3506
1
    goto err;
3507
1
  }
3508
133
  LOG_TEST_GOTO_ERR(card->ctx, r, "Card returned error");
3509
3510
  /* parse response data and set output */
3511
128
  r = pgp_parse_and_set_pubkey_output(card, apdu.resp, apdu.resplen, key_info);
3512
128
  LOG_TEST_GOTO_ERR(card->ctx, r, "Failed to parse pubkey output");
3513
4
  r = pgp_update_card_algorithms(card, key_info);
3514
3515
135
err:
3516
135
  free(apdu.resp);
3517
135
  LOG_FUNC_RETURN(card->ctx, r);
3518
135
}
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
2.18k
{
4010
2.18k
  int r;
4011
4012
2.18k
  LOG_FUNC_CALLED(card->ctx);
4013
4014
2.18k
  switch(cmd) {
4015
525
  case SC_CARDCTL_GET_SERIALNR:
4016
525
    memmove((sc_serial_number_t *) ptr, &card->serialnr, sizeof(card->serialnr));
4017
525
    LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
4018
0
    break;
4019
313
  case SC_CARDCTL_OPENPGP_SELECT_DATA:
4020
313
    r = pgp_select_data(card, *((u8 *) ptr));
4021
313
    LOG_FUNC_RETURN(card->ctx, r);
4022
0
    break;
4023
0
#ifdef ENABLE_OPENSSL
4024
275
  case SC_CARDCTL_OPENPGP_GENERATE_KEY:
4025
275
    r = pgp_gen_key(card, (sc_cardctl_openpgp_key_gen_store_info_t *)ptr);
4026
275
    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
2.18k
  }
4038
4039
1.07k
  LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
4040
1.07k
}
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
31
{
4144
31
  struct pgp_priv_data *priv = DRVDATA(card);
4145
31
  pgp_blob_t *blob = priv->current;
4146
31
  int r = SC_SUCCESS;
4147
4148
31
  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
31
  if (idx > 0)
4153
31
    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
21
  if (blob != NULL) {
4158
21
    r = pgp_put_data(card, blob->id, buf, count);
4159
21
  }
4160
4161
21
  LOG_FUNC_RETURN(card->ctx, r);
4162
21
}
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
863k
{
4170
863k
  struct pgp_priv_data *priv = DRVDATA(card); /* may be null during initialization */
4171
863k
  int r = SC_SUCCESS;
4172
4173
863k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
4174
4175
863k
  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
863k
  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
863k
  LOG_FUNC_RETURN(card->ctx, r);
4201
863k
}
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
126k
{
4210
126k
  struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
4211
4212
126k
  iso_ops = iso_drv->ops;
4213
4214
126k
  pgp_ops = *iso_ops;
4215
126k
  pgp_ops.match_card  = pgp_match_card;
4216
126k
  pgp_ops.init    = pgp_init;
4217
126k
  pgp_ops.finish    = pgp_finish;
4218
126k
  pgp_ops.select_file = pgp_select_file;
4219
126k
  pgp_ops.list_files  = pgp_list_files;
4220
126k
  pgp_ops.get_challenge = pgp_get_challenge;
4221
126k
  pgp_ops.read_binary = pgp_read_binary;
4222
126k
  pgp_ops.write_binary  = NULL;
4223
126k
  pgp_ops.pin_cmd   = pgp_pin_cmd;
4224
126k
  pgp_ops.logout    = pgp_logout;
4225
126k
  pgp_ops.get_data  = pgp_get_data;
4226
126k
  pgp_ops.put_data  = pgp_put_data;
4227
126k
  pgp_ops.set_security_env= pgp_set_security_env;
4228
126k
  pgp_ops.compute_signature= pgp_compute_signature;
4229
126k
  pgp_ops.decipher  = pgp_decipher;
4230
126k
  pgp_ops.card_ctl  = pgp_card_ctl;
4231
126k
  pgp_ops.delete_file = pgp_delete_file;
4232
126k
  pgp_ops.update_binary = pgp_update_binary;
4233
126k
  pgp_ops.card_reader_lock_obtained = pgp_card_reader_lock_obtained;
4234
4235
126k
  return &pgp_drv;
4236
126k
}