Coverage Report

Created: 2026-12-03 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/opensc/src/libopensc/pkcs15-openpgp.c
Line
Count
Source
1
/*
2
 * PKCS15 emulation layer for OpenPGP card.
3
 * To see how this works, run p15dump on your OpenPGP card.
4
 *
5
 * Copyright (C) 2003, Olaf Kirch <okir@suse.de>
6
 *
7
 * This library is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * This library is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21
22
#ifdef HAVE_CONFIG_H
23
#include "config.h"
24
#endif
25
26
#include <stdlib.h>
27
#include <string.h>
28
#include <stdio.h>
29
30
#include "common/compat_strlcpy.h"
31
#include "internal.h"
32
#include "pkcs15.h"
33
#include "log.h"
34
#include "card-openpgp.h"
35
36
static int sc_pkcs15emu_openpgp_add_data(sc_pkcs15_card_t *);
37
38
39
#define PGP_USER_PIN_FLAGS  (SC_PKCS15_PIN_FLAG_CASE_SENSITIVE \
40
        | SC_PKCS15_PIN_FLAG_INITIALIZED \
41
        | SC_PKCS15_PIN_FLAG_LOCAL)
42
#define PGP_ADMIN_PIN_FLAGS (PGP_USER_PIN_FLAGS \
43
        | SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED \
44
        | SC_PKCS15_PIN_FLAG_SO_PIN)
45
46
115
#define PGP_NUM_PRIVDO       4
47
128
#define PGP_MAX_NUM_CERTS    3
48
49
typedef struct _pgp_pin_cfg {
50
  const char  *label;
51
  int   reference;
52
  unsigned int  flags;
53
  int   min_length;
54
  int   do_index;
55
} pgp_pin_cfg_t;
56
57
// clang-format off
58
/* OpenPGP cards v1:
59
 * "Signature PIN2 & "Encryption PIN" are two different PINs - not sync'ed by hardware
60
 */
61
static const pgp_pin_cfg_t  pin_cfg_v1[3] = {
62
  { "Encryption PIN", 0x02, PGP_USER_PIN_FLAGS,  6, 1 },  // used for PSO:DEC, INT-AUT, {GET,PUT} DATA
63
  { "Signature PIN",  0x01, PGP_USER_PIN_FLAGS,  6, 0 },  // used for PSO:CDS
64
  { "Admin PIN",      0x03, PGP_ADMIN_PIN_FLAGS, 8, 2 }
65
};
66
/* OpenPGP cards v2:
67
 * "User PIN (sig)" & "User PIN" are the same PIN, but use different references depending on action
68
 */
69
static const pgp_pin_cfg_t  pin_cfg_v2[3] = {
70
  { "User PIN",       0x02, PGP_USER_PIN_FLAGS,  6, 0 },  // used for PSO:DEC, INT-AUT, {GET,PUT} DATA
71
  { "User PIN (sig)", 0x01, PGP_USER_PIN_FLAGS,  6, 0 },  // used for PSO:CDS
72
  { "Admin PIN",      0x03, PGP_ADMIN_PIN_FLAGS, 8, 2 }
73
};
74
// clang-format on
75
76
static struct sc_object_id curve25519_oid = {{1, 3, 6, 1, 4, 1, 3029, 1, 5, 1, -1}};
77
78
8
#define PGP_SIG_PRKEY_USAGE (SC_PKCS15_PRKEY_USAGE_SIGN \
79
8
        | SC_PKCS15_PRKEY_USAGE_SIGNRECOVER \
80
8
        | SC_PKCS15_PRKEY_USAGE_NONREPUDIATION)
81
66
#define PGP_ENC_PRKEY_USAGE (SC_PKCS15_PRKEY_USAGE_DECRYPT \
82
66
        | SC_PKCS15_PRKEY_USAGE_UNWRAP)
83
#define PGP_AUTH_PRKEY_USAGE  (SC_PKCS15_PRKEY_USAGE_NONREPUDIATION)
84
85
18
#define PGP_SIG_PUBKEY_USAGE  (SC_PKCS15_PRKEY_USAGE_VERIFY \
86
18
        | SC_PKCS15_PRKEY_USAGE_VERIFYRECOVER)
87
6
#define PGP_ENC_PUBKEY_USAGE  (SC_PKCS15_PRKEY_USAGE_ENCRYPT \
88
6
        | SC_PKCS15_PRKEY_USAGE_WRAP)
89
#define PGP_AUTH_PUBKEY_USAGE (SC_PKCS15_PRKEY_USAGE_VERIFY)
90
91
typedef struct _pgp_key_cfg {
92
  const char  *label;
93
  const char  *pubkey_path;
94
  int   prkey_pin;
95
  int   prkey_usage;
96
  int   pubkey_usage;
97
} pgp_key_cfg_t;
98
99
typedef struct cdata_st {
100
  const char *label;
101
  int     authority;
102
  const char *path;
103
  const char *id;
104
  int         obj_flags;
105
} cdata;
106
107
// clang-format off
108
static const pgp_key_cfg_t key_cfg[3] = {
109
  { "Signature key",      "B601", 1, PGP_SIG_PRKEY_USAGE,  PGP_SIG_PUBKEY_USAGE  },
110
  { "Encryption key",     "B801", 2, PGP_ENC_PRKEY_USAGE,  PGP_ENC_PUBKEY_USAGE  },
111
  { "Authentication key", "A401", 2, PGP_AUTH_PRKEY_USAGE | PGP_ENC_PRKEY_USAGE, PGP_AUTH_PUBKEY_USAGE | PGP_ENC_PUBKEY_USAGE }
112
};
113
114
static const cdata certs[PGP_MAX_NUM_CERTS] = {
115
  {"AUT certificate", 0, "3F007F21", "3", SC_PKCS15_CO_FLAG_MODIFIABLE},
116
  {"DEC certificate", 0, "3F007F21", "2", SC_PKCS15_CO_FLAG_MODIFIABLE},
117
  {"SIG certificate", 0, "3F007F21", "1", SC_PKCS15_CO_FLAG_MODIFIABLE}
118
};
119
// clang-format on
120
121
typedef struct _pgp_manuf_map {
122
  unsigned short    id;
123
  const char  *name;
124
} pgp_manuf_map_t;
125
126
// clang-format off
127
static const pgp_manuf_map_t manuf_map[] = {
128
  { 0x0001, "PPC Card Systems"    },
129
  { 0x0002, "Prism"     },
130
  { 0x0003, "OpenFortress"    },
131
  { 0x0004, "Wewid AB"      },
132
  { 0x0005, "ZeitControl"     },
133
  { 0x0006, "Yubico"      },
134
  { 0x0007, "OpenKMS"     },
135
  { 0x0008, "LogoEmail"     },
136
  { 0x0009, "Fidesmo"     },
137
  { 0x000A, "Dangerous Things"    },
138
  { 0x000B, "Feitian Technologies"  },
139
  { 0x002A, "Magrathea"     },
140
  { 0x0042, "GnuPG e.V."      },
141
  { 0x1337, "Warsaw Hackerspace"    },
142
  { 0x2342, "warpzone"      },
143
  { 0x4354, "Confidential Technologies" },
144
  { 0x5443, "TIF-IT e.V."     },
145
  { 0x63AF, "Trustica"      },
146
  { 0xBA53, "c-base e.V."     },
147
  { 0xBD0E, "Paranoidlabs"    },
148
  { 0xF517, "FSIJ"      },
149
  { 0xF5EC, "F-Secure"      },
150
  { 0x0000, "test card"     },
151
  { 0xffff, "test card"     },
152
  { 0, NULL }
153
};
154
// clang-format on
155
156
/*
157
 * This function pretty much follows what find_tlv in the GNUpg
158
 * code does.
159
 */
160
static int
161
read_file(sc_card_t *card, const char *path_name, void *buf, size_t len)
162
2.28k
{
163
2.28k
  sc_path_t path;
164
2.28k
  sc_file_t *file;
165
2.28k
  int   r;
166
167
2.28k
  sc_format_path(path_name, &path);
168
2.28k
  if ((r = sc_select_file(card, &path, &file)) < 0)
169
707
    return r;
170
171
1.57k
  if (file->size < len)
172
1.49k
    len = file->size;
173
174
1.57k
  sc_file_free(file);
175
176
1.57k
  return sc_read_binary(card, 0, (u8 *) buf, len, 0);
177
2.28k
}
178
179
static int
180
sc_pkcs15emu_openpgp_init(sc_pkcs15_card_t *p15card)
181
828
{
182
828
  sc_card_t *card = p15card->card;
183
828
  sc_context_t  *ctx = card->ctx;
184
828
  struct pgp_priv_data *priv = DRVDATA(card);
185
828
  char    string[256];
186
828
  u8    c4data[10];
187
828
  u8    c5data[100];
188
828
  int   r, i;
189
828
  const pgp_pin_cfg_t *pin_cfg = (card->type == SC_CARD_TYPE_OPENPGP_V1)
190
828
                                 ? pin_cfg_v1 : pin_cfg_v2;
191
828
  sc_path_t path;
192
828
  sc_file_t *file = NULL;
193
194
828
  LOG_FUNC_CALLED(ctx);
195
196
828
  set_string(&p15card->tokeninfo->label, "OpenPGP card");
197
828
  set_string(&p15card->tokeninfo->manufacturer_id, "OpenPGP project");
198
199
  /* card->serialnr = 2 byte manufacturer_id + 4 byte serial_number */
200
828
  if (card->serialnr.len > 0) {
201
676
    unsigned short manuf_id = bebytes2ushort(card->serialnr.value);
202
676
    int j;
203
204
676
    sc_bin_to_hex(card->serialnr.value, card->serialnr.len, string, sizeof(string), 0);
205
676
    set_string(&p15card->tokeninfo->serial_number, string);
206
207
16.4k
    for (j = 0; manuf_map[j].name != NULL; j++) {
208
15.8k
      if (manuf_id == manuf_map[j].id) {
209
76
        set_string(&p15card->tokeninfo->manufacturer_id, manuf_map[j].name);
210
76
        break;
211
76
      }
212
15.8k
    }
213
676
  }
214
215
828
  p15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION | SC_PKCS15_TOKEN_EID_COMPLIANT;
216
217
  /* Extract preferred language */
218
828
  r = read_file(card, "0065:5f2d", string, sizeof(string)-1);
219
828
  if (r < 0)
220
578
    goto failed;
221
250
  string[r] = '\0';
222
250
  set_string(&p15card->tokeninfo->preferred_language, string);
223
224
  /* Get CHV status bytes from DO 006E/0073/00C4:
225
   *  00:   1 == user consent for signature PIN
226
   *    (i.e. PIN still valid for next PSO:CDS command)
227
   *  01-03:  max length of pins 1-3
228
   *  04-07:  tries left for pins 1-3
229
   */
230
250
  sc_log(ctx, "Reading PW status bytes");
231
250
  if ((r = read_file(card, "006E:0073:00C4", c4data, sizeof(c4data))) < 0)
232
23
    goto failed;
233
227
  if (r != 7) {
234
12
    sc_log(ctx, "CHV status bytes have unexpected length (expected 7, got %d)\n", r);
235
12
    r = SC_ERROR_OBJECT_NOT_VALID;
236
12
    goto failed;
237
12
  }
238
239
  /* Add PIN codes */
240
860
  for (i = 0; i < 3; i++) {
241
645
    sc_pkcs15_auth_info_t pin_info;
242
645
    sc_pkcs15_object_t   pin_obj;
243
244
645
    memset(&pin_info, 0, sizeof(pin_info));
245
645
    memset(&pin_obj,  0, sizeof(pin_obj));
246
247
645
    pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
248
645
    pin_info.auth_id.len      = 1;
249
645
    pin_info.auth_id.value[0] = pin_cfg[i].reference;
250
645
    pin_info.attrs.pin.reference     = pin_cfg[i].reference;
251
645
    pin_info.attrs.pin.flags         = pin_cfg[i].flags;
252
645
    pin_info.attrs.pin.type          = SC_PKCS15_PIN_TYPE_UTF8;
253
645
    pin_info.attrs.pin.min_length    = pin_cfg[i].min_length;
254
645
    pin_info.attrs.pin.stored_length = c4data[1 + pin_cfg[i].do_index];
255
645
    pin_info.attrs.pin.max_length    = c4data[1 + pin_cfg[i].do_index];
256
645
    pin_info.attrs.pin.pad_char      = '\0';
257
645
    pin_info.tries_left = c4data[4 + pin_cfg[i].do_index];
258
645
    pin_info.logged_in = SC_PIN_STATE_UNKNOWN;
259
260
645
    sc_format_path("3F00", &pin_info.path);
261
262
645
    strlcpy(pin_obj.label, pin_cfg[i].label, sizeof(pin_obj.label));
263
645
    pin_obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE;
264
645
    if (i < 2) {
265
430
      pin_obj.auth_id.len = 1;
266
430
      pin_obj.auth_id.value[0] = 3;
267
430
    }
268
269
645
    r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
270
645
    if (r < 0) {
271
0
      r = SC_ERROR_INTERNAL;
272
0
      goto failed;
273
0
    }
274
645
  }
275
276
  /* Get private key finger prints from DO 006E/0073/00C5:
277
   *  00-19:  finger print for SIG key
278
   *  20-39:  finger print for ENC key
279
   *  40-59:  finger print for AUT key
280
   */
281
215
  sc_log(ctx, "Reading Fingerprints");
282
215
  if ((r = read_file(card, "006E:0073:00C5", c5data, sizeof(c5data))) < 0)
283
1
    goto failed;
284
214
  if (r < 60) {
285
3
    sc_log(ctx,
286
3
      "finger print bytes have unexpected length (expected 60, got %d)\n", r);
287
3
    r = SC_ERROR_OBJECT_NOT_VALID;
288
3
    goto failed;
289
3
  }
290
291
211
  sc_log(ctx, "Adding private keys");
292
  /* XXX: check if "halfkeys" can be stored with gpg2. If not, add key pairs in one loop */
293
703
  for (i = 0; i < 3; i++) {
294
602
    sc_pkcs15_prkey_info_t prkey_info;
295
602
    sc_pkcs15_object_t     prkey_obj;
296
602
    u8 cxdata[12];
297
602
    int cxdata_len = sizeof(cxdata);
298
602
    char path_template[] = "006E:0073:00Cx";
299
602
    int j;
300
301
602
    memset(&prkey_info, 0, sizeof(prkey_info));
302
602
    memset(&prkey_obj,  0, sizeof(prkey_obj));
303
602
    memset(&cxdata, 0, sizeof(cxdata));
304
305
602
    path_template[13] = '1' + i; /* The needed tags are C1 C2 and C3 */
306
602
    if ((cxdata_len = read_file(card, path_template, cxdata, sizeof(cxdata))) < 1)
307
106
      goto failed;
308
309
    /* check validity using finger prints */
310
1.82k
    for (j = 19; j >= 0; j--) {
311
1.81k
      if (c5data[20 * i + j] != '\0')
312
482
        break;
313
1.81k
    }
314
315
    /* only add valid keys, i.e. those with a legal algorithm identifier & finger print */
316
496
    if (j >= 0 && cxdata[0] != 0) {
317
459
      struct sc_object_id oid = {0};
318
459
      struct sc_algorithm_info * algorithm_info; /* no need to free */
319
320
459
      algorithm_info = NULL;
321
459
      prkey_info.id.len         = 1;
322
459
      prkey_info.id.value[0]    = i + 1;
323
459
      prkey_info.usage          = key_cfg[i].prkey_usage;
324
459
      prkey_info.native         = 1;
325
459
      prkey_info.key_reference  = i;
326
327
459
      strlcpy(prkey_obj.label, key_cfg[i].label, sizeof(prkey_obj.label));
328
459
      prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE | SC_PKCS15_CO_FLAG_MODIFIABLE;
329
459
      prkey_obj.auth_id.len      = 1;
330
459
      prkey_obj.auth_id.value[0] = key_cfg[i].prkey_pin;
331
332
      /* need to get size from algorithms using oid */
333
459
      if (cxdata[0] == SC_OPENPGP_KEYALGO_ECDH ||
334
311
        cxdata[0] == SC_OPENPGP_KEYALGO_ECDSA ||
335
284
        cxdata[0] == SC_OPENPGP_KEYALGO_EDDSA) {
336
        /* Last byte could be Import-Format of private key, let's ignore it,
337
         * as it is not part of OID */
338
284
        if (cxdata[cxdata_len-1] == SC_OPENPGP_KEYFORMAT_EC_STD ||
339
101
            cxdata[cxdata_len-1] == SC_OPENPGP_KEYFORMAT_EC_STDPUB)
340
204
          cxdata_len--;
341
284
        r = sc_asn1_decode_object_id(&cxdata[1], cxdata_len-1, &oid);
342
284
        if (r != SC_SUCCESS) {
343
57
          sc_log(ctx, "Failed to parse OID for elliptic curve algorithm");
344
57
        }
345
284
      }
346
347
459
      switch (cxdata[0]) {
348
148
      case SC_OPENPGP_KEYALGO_ECDH:
349
148
        if (sc_compare_oid(&oid, &curve25519_oid)) {
350
0
          if ((algorithm_info = sc_card_find_xeddsa_alg(card, 0, &oid)))
351
0
            prkey_info.field_length = algorithm_info->key_length;
352
0
          else {
353
0
            sc_log(ctx, "algorithm not found");
354
0
            continue;
355
0
          }
356
0
          break;
357
0
        }
358
        /* Fall through */
359
248
      case SC_OPENPGP_KEYALGO_ECDSA:
360
248
        if((algorithm_info = sc_card_find_ec_alg(card, 0, &oid)))
361
120
          prkey_info.field_length = algorithm_info->key_length;
362
128
        else {
363
128
          sc_log(ctx, "algorithm not found");
364
128
          continue;
365
128
        }
366
120
        break;
367
120
      case SC_OPENPGP_KEYALGO_EDDSA:
368
36
        if ((algorithm_info = sc_card_find_eddsa_alg(card, 0, &oid)))
369
8
          prkey_info.field_length = algorithm_info->key_length;
370
28
        else {
371
28
          sc_log(ctx, "algorithm not found");
372
28
          continue;
373
28
        }
374
8
        break;
375
459
      }
376
377
303
      switch (cxdata[0]) {
378
8
      case SC_OPENPGP_KEYALGO_EDDSA:
379
        /* Filter out invalid usage: EdDSA does not support anything but sign */
380
8
        prkey_info.usage &= PGP_SIG_PRKEY_USAGE;
381
8
        r = sc_pkcs15emu_add_eddsa_prkey(p15card, &prkey_obj, &prkey_info);
382
8
        break;
383
384
60
      case SC_OPENPGP_KEYALGO_ECDH:
385
        /* This can result in either ECDSA key or EC_MONTGOMERY
386
         * so we need to check OID */
387
60
        if (sc_compare_oid(&oid, &curve25519_oid)) {
388
          /* This can do only DERIVE */
389
0
          prkey_info.usage = SC_PKCS15_PRKEY_USAGE_DERIVE;
390
0
          r = sc_pkcs15emu_add_xeddsa_prkey(p15card, &prkey_obj, &prkey_info);
391
0
          break;
392
0
        }
393
60
        prkey_info.usage |= SC_PKCS15_PRKEY_USAGE_DERIVE;
394
60
        prkey_info.usage &= ~PGP_ENC_PRKEY_USAGE;
395
60
        r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info);
396
60
        break;
397
398
60
      case SC_OPENPGP_KEYALGO_ECDSA:
399
60
        prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN;
400
60
        r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info);
401
60
        break;
402
403
52
      case SC_OPENPGP_KEYALGO_RSA:
404
52
        if (cxdata_len >= 3) {
405
          /* with Authentication key, can only decrypt if can change MSE */
406
41
          if (i == 2 && !(priv->ext_caps & EXT_CAP_MSE)) {
407
6
            prkey_info.usage &= ~PGP_ENC_PRKEY_USAGE;
408
6
          }
409
41
          prkey_info.modulus_length = bebytes2ushort(cxdata + 1);
410
41
          r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info);
411
41
          break;
412
41
        }
413
        /* Fallthrough */
414
134
      default:
415
134
        sc_log(ctx, "Invalid algorithm identifier %x (length = %d)",
416
303
          cxdata[0], r);
417
303
      }
418
419
303
      if (r < 0) {
420
4
        r = SC_ERROR_INTERNAL;
421
4
        goto failed;
422
4
      }
423
303
    }
424
496
  }
425
426
101
  sc_log(ctx, "Adding public keys");
427
  /* Add public keys */
428
398
  for (i = 0; i < 3; i++) {
429
299
    sc_pkcs15_pubkey_info_t pubkey_info;
430
299
    sc_pkcs15_object_t      pubkey_obj;
431
299
    u8 cxdata[12];
432
299
    int cxdata_len = sizeof(cxdata);
433
299
    char path_template[] = "006E:0073:00Cx";
434
299
    int j;
435
436
299
    memset(&pubkey_info, 0, sizeof(pubkey_info));
437
299
    memset(&pubkey_obj,  0, sizeof(pubkey_obj));
438
299
    memset(&cxdata, 0, sizeof(cxdata));
439
440
299
    path_template[13] = '1' + i; /* The needed tags are C1 C2 and C3 */
441
299
    if ((cxdata_len = read_file(card, path_template, cxdata, sizeof(cxdata))) < 1)
442
0
      goto failed;
443
444
    /* check validity using finger prints */
445
998
    for (j = 19; j >= 0; j--) {
446
986
      if (c5data[20 * i + j] != '\0')
447
287
        break;
448
986
    }
449
450
    /* only add valid keys, i.e. those with a legal algorithm identifier & finger print */
451
299
    if (j >= 0 && cxdata[0] != 0) {
452
268
      struct sc_object_id oid;
453
268
      struct sc_algorithm_info * algorithm_info; /* no need to free */
454
455
268
      algorithm_info = NULL;
456
268
      pubkey_info.id.len         = 1;
457
268
      pubkey_info.id.value[0]    = i + 1;
458
268
      pubkey_info.usage          = key_cfg[i].pubkey_usage;
459
268
      sc_format_path(key_cfg[i].pubkey_path, &pubkey_info.path);
460
461
268
      strlcpy(pubkey_obj.label, key_cfg[i].label, sizeof(pubkey_obj.label));
462
268
      pubkey_obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE;
463
464
268
      if (cxdata[0] == SC_OPENPGP_KEYALGO_ECDH ||
465
195
        cxdata[0] == SC_OPENPGP_KEYALGO_ECDSA ||
466
158
        cxdata[0] == SC_OPENPGP_KEYALGO_EDDSA) {
467
        /* Last byte could be Import-Format of private key, let's ignore it,
468
         * as it is not part of OID */
469
139
        if (cxdata[cxdata_len-1] == SC_OPENPGP_KEYFORMAT_EC_STD ||
470
70
            cxdata[cxdata_len-1] == SC_OPENPGP_KEYFORMAT_EC_STDPUB)
471
84
          cxdata_len--;
472
139
        r = sc_asn1_decode_object_id(&cxdata[1], cxdata_len-1, &oid);
473
139
        if (r != SC_SUCCESS) {
474
36
          sc_log(ctx, "Failed to parse OID for elliptic curve algorithm");
475
36
        }
476
139
      }
477
478
268
      switch (cxdata[0]) {
479
73
      case SC_OPENPGP_KEYALGO_ECDH:
480
73
        if (sc_compare_oid(&oid, &curve25519_oid)) {
481
0
          if ((algorithm_info = sc_card_find_xeddsa_alg(card, 0, &oid)))
482
0
            pubkey_info.field_length = algorithm_info->key_length;
483
0
          else {
484
0
            sc_log(ctx, "algorithm not found");
485
0
            continue;
486
0
          }
487
0
          break;
488
0
        }
489
        /* Fall through */
490
110
      case SC_OPENPGP_KEYALGO_ECDSA:
491
110
        if((algorithm_info = sc_card_find_ec_alg(card, 0, &oid)))
492
23
          pubkey_info.field_length = algorithm_info->key_length;
493
87
        else {
494
87
          sc_log(ctx, "algorithm not found");
495
87
          continue;
496
87
        }
497
23
        break;
498
29
      case SC_OPENPGP_KEYALGO_EDDSA:
499
29
        if ((algorithm_info = sc_card_find_eddsa_alg(card, 0, &oid)))
500
9
          pubkey_info.field_length = algorithm_info->key_length;
501
20
        else {
502
20
          sc_log(ctx, "algorithm not found");
503
20
          continue;
504
20
        }
505
9
        break;
506
268
      }
507
508
161
      switch (cxdata[0]) {
509
9
      case SC_OPENPGP_KEYALGO_EDDSA:
510
        /* assuming Ed25519 as it is the only supported now */
511
        /* Filter out invalid usage: ED does not support anything but sign */
512
9
        pubkey_info.usage &= PGP_SIG_PUBKEY_USAGE;
513
9
        r = sc_pkcs15emu_add_eddsa_pubkey(p15card, &pubkey_obj, &pubkey_info);
514
9
        break;
515
14
      case SC_OPENPGP_KEYALGO_ECDH:
516
        /* This can result in either ECDSA key or EC_MONTGOMERY
517
         * so we need to check OID */
518
14
        if (sc_compare_oid(&oid, &curve25519_oid)) {
519
          /* XXX What can this key do? */
520
0
          pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_DERIVE;
521
0
          r = sc_pkcs15emu_add_xeddsa_pubkey(p15card, &pubkey_obj, &pubkey_info);
522
0
          break;
523
0
        }
524
14
        pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_DERIVE;
525
14
        r = sc_pkcs15emu_add_ec_pubkey(p15card, &pubkey_obj, &pubkey_info);
526
14
        break;
527
9
      case SC_OPENPGP_KEYALGO_ECDSA:
528
9
        pubkey_info.usage = PGP_SIG_PUBKEY_USAGE;
529
9
        r = sc_pkcs15emu_add_ec_pubkey(p15card, &pubkey_obj, &pubkey_info);
530
9
        break;
531
22
      case SC_OPENPGP_KEYALGO_RSA:
532
22
        if (cxdata_len >= 3) {
533
          /* with Authentication pubkey, can only encrypt if can change MSE */
534
15
          if (i == 2 && !(priv->ext_caps & EXT_CAP_MSE)) {
535
6
            pubkey_info.usage &= ~PGP_ENC_PUBKEY_USAGE;
536
6
          }
537
15
          pubkey_info.modulus_length = bebytes2ushort(cxdata + 1);
538
15
          r = sc_pkcs15emu_add_rsa_pubkey(p15card, &pubkey_obj, &pubkey_info);
539
15
          break;
540
15
        }
541
        /* Fall through */
542
114
      default:
543
114
        sc_log(ctx, "Invalid algorithm identifier %x (length = %d)",
544
161
          cxdata[0], r);
545
161
      }
546
547
161
      if (r < 0) {
548
2
        r = SC_ERROR_INTERNAL;
549
2
        goto failed;
550
2
      }
551
161
    }
552
299
  }
553
554
  /* Check if certificate DO 7F21 holds data */
555
99
  sc_format_path("7F21", &path);
556
99
  r = sc_select_file(card, &path, &file);
557
99
  if (r < 0)
558
19
    goto failed;
559
560
128
  for(u8 i=0; i<PGP_MAX_NUM_CERTS; i++) {
561
116
    struct sc_pkcs15_cert_info cert_info;
562
116
    struct sc_pkcs15_object    cert_obj;
563
116
    u8* buffer = malloc(MAX_OPENPGP_DO_SIZE);
564
116
    int resp_len = 0;
565
566
116
    if (buffer == NULL)
567
0
      goto failed;
568
569
116
    memset(&cert_info, 0, sizeof(cert_info));
570
116
    memset(&cert_obj,  0, sizeof(cert_obj));
571
572
    /* try to SELECT DATA. Will only work for OpenPGP >= v3, errors are non-critical */
573
116
    sc_card_ctl(card, SC_CARDCTL_OPENPGP_SELECT_DATA, &i);
574
575
116
    sc_format_path(certs[i].path, &cert_info.path);
576
577
    /* Certificate ID. We use the same ID as the authentication key */
578
116
    sc_pkcs15_format_id(certs[i].id, &cert_info.id);
579
580
116
    resp_len = sc_get_data(card, 0x7F21, buffer, MAX_OPENPGP_DO_SIZE);
581
582
    /* Response length => free buffer and continue with next id */
583
116
    if (resp_len == 0) {
584
24
      free(buffer);
585
24
      continue;
586
24
    }
587
588
    /* Catch error during sc_get_data */
589
92
    if (resp_len < 0) {
590
57
      free(buffer);
591
57
      goto failed;
592
57
    }
593
594
    /* Assemble certificate info struct, based on `certs` array */
595
35
    cert_info.value.len = resp_len;
596
35
    cert_info.value.value = buffer;
597
35
    cert_info.authority = certs[i].authority;
598
35
    cert_obj.flags = certs[i].obj_flags;
599
600
    /* Object label */
601
35
    strlcpy(cert_obj.label, certs[i].label, sizeof(cert_obj.label));
602
603
35
    r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info);
604
35
    if (r < 0) {
605
0
      free(buffer);
606
0
      goto failed;
607
0
    }
608
609
    /* only iterate, for OpenPGP >= v3, thus break on < v3 */
610
35
    if (card->type < SC_CARD_TYPE_OPENPGP_V3)
611
11
      break;
612
35
  }
613
614
  /* Add PKCS#15 DATA objects from other OpenPGP card DOs. The return
615
   * value is ignored, so this will not cause initialization to fail.
616
   */
617
23
  sc_pkcs15emu_openpgp_add_data(p15card);
618
619
828
failed:
620
828
  if (r < 0) {
621
647
    sc_log(card->ctx,
622
647
        "Failed to initialize OpenPGP emulation: %s\n",
623
647
        sc_strerror(r));
624
647
    sc_pkcs15_card_clear(p15card);
625
647
  }
626
828
  sc_file_free(file);
627
828
  LOG_FUNC_RETURN(ctx, r);
628
828
}
629
630
// see https://stackoverflow.com/a/10536254 for explanation
631
#define LEN_MAX_INT_AS_STR (3 * sizeof(int) + 2)
632
633
static int
634
sc_pkcs15emu_openpgp_add_data(sc_pkcs15_card_t *p15card)
635
23
{
636
23
  sc_context_t *ctx = p15card->card->ctx;
637
23
  int i, r;
638
639
23
  LOG_FUNC_CALLED(ctx);
640
  /* Optional private use DOs 0101 to 0104 */
641
115
  for (i = 1; i <= PGP_NUM_PRIVDO; i++) {
642
92
    sc_pkcs15_data_info_t dat_info;
643
92
    sc_pkcs15_object_t dat_obj;
644
92
    char name[6 + LEN_MAX_INT_AS_STR];
645
92
    char path[7 + LEN_MAX_INT_AS_STR];
646
92
    u8 content[254];
647
92
    memset(&dat_info, 0, sizeof(dat_info));
648
92
    memset(&dat_obj, 0, sizeof(dat_obj));
649
650
92
    snprintf(name, 8, "PrivDO%d", i);
651
92
    snprintf(path, 9, "3F00010%d", i);
652
653
    /* Check if the DO can be read and is not empty. Otherwise we
654
     * won't expose a PKCS#15 DATA object.
655
     */
656
92
    r = read_file(p15card->card, path, content, sizeof(content));
657
92
    if (r <= 0 ) {
658
71
      sc_log(ctx, "Cannot read DO 010%d or there is no data in it", i);
659
      /* Skip */
660
71
      continue;
661
71
    }
662
21
    sc_format_path(path, &dat_info.path);
663
21
    strlcpy(dat_obj.label, name, sizeof(dat_obj.label));
664
21
    strlcpy(dat_info.app_label, name, sizeof(dat_info.app_label));
665
666
    /* Add DATA object to slot protected by PIN2 (PW1 with Ref 0x82) */
667
21
    dat_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE | SC_PKCS15_CO_FLAG_MODIFIABLE;
668
21
    dat_obj.auth_id.len = 1;
669
21
    if (i == 1 || i == 3)
670
11
      dat_obj.auth_id.value[0] = 2;
671
10
    else
672
10
      dat_obj.auth_id.value[0] = 3;
673
674
21
    sc_log(ctx, "Add %s data object", name);
675
21
    r = sc_pkcs15emu_add_data_object(p15card, &dat_obj, &dat_info);
676
21
    LOG_TEST_RET(ctx, r, "Could not add data object to framework");
677
21
  }
678
23
  LOG_FUNC_RETURN(ctx, SC_SUCCESS);
679
23
}
680
681
static int openpgp_detect_card(sc_pkcs15_card_t *p15card)
682
11.2k
{
683
11.2k
  if (p15card->card->type == SC_CARD_TYPE_OPENPGP_BASE
684
10.5k
      || p15card->card->type == SC_CARD_TYPE_OPENPGP_V1
685
10.4k
      || p15card->card->type == SC_CARD_TYPE_OPENPGP_V2
686
10.4k
      || p15card->card->type == SC_CARD_TYPE_OPENPGP_GNUK
687
10.4k
      || p15card->card->type == SC_CARD_TYPE_OPENPGP_V3)
688
828
    return SC_SUCCESS;
689
10.4k
  else
690
10.4k
    return SC_ERROR_WRONG_CARD;
691
11.2k
}
692
693
int sc_pkcs15emu_openpgp_init_ex(sc_pkcs15_card_t *p15card, struct sc_aid *aid)
694
11.2k
{
695
11.2k
  if (openpgp_detect_card(p15card))
696
10.4k
    return SC_ERROR_WRONG_CARD;
697
828
  return sc_pkcs15emu_openpgp_init(p15card);
698
11.2k
}