Coverage Report

Created: 2025-07-01 06:08

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