Coverage Report

Created: 2026-07-10 06:05

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/opensc/src/pkcs15init/pkcs15-lib.c
Line
Count
Source
1
/*
2
 * Initialize Cards according to PKCS#15.
3
 *
4
 * This is a fill in the blanks sort of exercise. You need a
5
 * profile that describes characteristics of your card, and the
6
 * application specific layout on the card. This program will
7
 * set up the card according to this specification (including
8
 * PIN initialization etc) and create the corresponding PKCS15
9
 * structure.
10
 *
11
 * There are a very few tasks that are too card specific to have
12
 * a generic implementation; that is how PINs and keys are stored
13
 * on the card. These should be implemented in pkcs15-<cardname>.c
14
 *
15
 * Copyright (C) 2002, Olaf Kirch <okir@suse.de>
16
 *
17
 * This library is free software; you can redistribute it and/or
18
 * modify it under the terms of the GNU Lesser General Public
19
 * License as published by the Free Software Foundation; either
20
 * version 2.1 of the License, or (at your option) any later version.
21
 *
22
 * This library is distributed in the hope that it will be useful,
23
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25
 * Lesser General Public License for more details.
26
 *
27
 * You should have received a copy of the GNU Lesser General Public
28
 * License along with this library; if not, write to the Free Software
29
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30
 */
31
32
#include "config.h"
33
34
#include <stdio.h>
35
#include <stdlib.h>
36
#include <ctype.h>
37
#include <stdarg.h>
38
#include <string.h>
39
#include <limits.h>
40
#include <time.h>
41
#ifdef HAVE_SYS_TIME_H
42
#include <sys/time.h>
43
#endif
44
#ifdef HAVE_STRINGS_H
45
#include <strings.h>
46
#endif
47
#include <assert.h>
48
#ifdef ENABLE_OPENSSL
49
#include <openssl/opensslv.h>
50
#include <openssl/bn.h>
51
#include <openssl/evp.h>
52
#include <openssl/pem.h>
53
#include <openssl/err.h>
54
#include <openssl/rand.h>
55
#include <openssl/rsa.h>
56
#include <openssl/pkcs12.h>
57
#endif
58
59
#include "libopensc/sc-ossl-compat.h"
60
#include "common/compat_strlcpy.h"
61
#include "common/libscdl.h"
62
#include "libopensc/pkcs15.h"
63
#include "libopensc/cardctl.h"
64
#include "libopensc/asn1.h"
65
#include "libopensc/log.h"
66
#include "libopensc/aux-data.h"
67
#include "profile.h"
68
#include "pkcs15-init.h"
69
#include "pkcs11/pkcs11.h"
70
71
13.8k
#define OPENSC_INFO_FILEPATH    "3F0050154946"
72
190
#define OPENSC_INFO_FILEID    0x4946
73
782
#define OPENSC_INFO_TAG_PROFILE   0x01
74
232
#define OPENSC_INFO_TAG_OPTION    0x02
75
76
/* Default ID for new key/pin */
77
22.6k
#define DEFAULT_ID      0x45
78
6.56k
#define DEFAULT_PIN_FLAGS   (SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE)
79
5.87k
#define DEFAULT_PRKEY_FLAGS   (SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE)
80
29
#define DEFAULT_PUBKEY_FLAGS    (SC_PKCS15_CO_FLAG_MODIFIABLE)
81
16.7k
#define DEFAULT_SKEY_FLAGS    (SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE)
82
0
#define DEFAULT_CERT_FLAGS    (SC_PKCS15_CO_FLAG_MODIFIABLE)
83
5.59k
#define DEFAULT_DATA_FLAGS    (SC_PKCS15_CO_FLAG_MODIFIABLE)
84
85
27.3k
#define TEMPLATE_INSTANTIATE_MIN_INDEX  0x0
86
33.8k
#define TEMPLATE_INSTANTIATE_MAX_INDEX  0xFE
87
88
/* Maximal number of access conditions that can be defined for one card operation. */
89
155k
#define SC_MAX_OP_ACS                   16
90
91
/* Handle encoding of PKCS15 on the card */
92
typedef int (*pkcs15_encoder)(struct sc_context *,
93
      struct sc_pkcs15_card *, u8 **, size_t *);
94
95
static int  sc_pkcs15init_store_data(struct sc_pkcs15_card *,
96
      struct sc_profile *, struct sc_pkcs15_object *,
97
      struct sc_pkcs15_der *, struct sc_path *);
98
static size_t sc_pkcs15init_keybits(struct sc_pkcs15_bignum *);
99
100
static int  sc_pkcs15init_update_dir(struct sc_pkcs15_card *,
101
      struct sc_profile *profile,
102
      struct sc_app_info *app);
103
static int  sc_pkcs15init_update_tokeninfo(struct sc_pkcs15_card *,
104
      struct sc_profile *profile);
105
static int  sc_pkcs15init_update_lastupdate(struct sc_pkcs15_card *,
106
      struct sc_profile *profile);
107
static int  sc_pkcs15init_update_odf(struct sc_pkcs15_card *,
108
      struct sc_profile *profile);
109
static unsigned int sc_pkcs15init_map_usage(unsigned long, int);
110
static int  do_select_parent(struct sc_profile *, struct sc_pkcs15_card *,
111
      struct sc_file *, struct sc_file **);
112
static int  sc_pkcs15init_create_pin(struct sc_pkcs15_card *, struct sc_profile *,
113
      struct sc_pkcs15_object *, struct sc_pkcs15init_pinargs *);
114
static int  check_keygen_params_consistency(struct sc_card *card,
115
      unsigned long alg, struct sc_pkcs15init_prkeyargs *prkey,
116
      unsigned int *keybits);
117
static int  check_key_compatibility(struct sc_pkcs15_card *, unsigned long,
118
      struct sc_pkcs15_prkey *, unsigned long,
119
      size_t, unsigned long);
120
static int  prkey_fixup(struct sc_pkcs15_card *, struct sc_pkcs15_prkey *);
121
static int  prkey_bits(struct sc_pkcs15_card *, struct sc_pkcs15_prkey *);
122
static int  key_pkcs15_algo(struct sc_pkcs15_card *, unsigned long);
123
static int  select_id(struct sc_pkcs15_card *, int, struct sc_pkcs15_id *);
124
static int  select_object_path(struct sc_pkcs15_card *, struct sc_profile *,
125
      struct sc_pkcs15_object *, struct sc_path *);
126
static int  sc_pkcs15init_get_pin_path(struct sc_pkcs15_card *,
127
      struct sc_pkcs15_id *, struct sc_path *);
128
static int  sc_pkcs15init_qualify_pin(struct sc_card *, const char *,
129
      size_t, struct sc_pkcs15_auth_info *);
130
static struct sc_pkcs15_df * find_df_by_type(struct sc_pkcs15_card *,
131
      unsigned int);
132
static int  sc_pkcs15init_read_info(struct sc_card *card, struct sc_profile *);
133
static int  sc_pkcs15init_parse_info(struct sc_card *, const unsigned char *, size_t,
134
      struct sc_profile *);
135
static int  sc_pkcs15init_write_info(struct sc_pkcs15_card *, struct sc_profile *,
136
      struct sc_pkcs15_object *);
137
138
static struct profile_operations {
139
  const char *name;
140
  void *func;
141
} profile_operations[] = {
142
  { "rutoken", (void *) sc_pkcs15init_get_rutoken_ops },
143
  { "flex", (void *) sc_pkcs15init_get_cryptoflex_ops },
144
  { "cyberflex", (void *) sc_pkcs15init_get_cyberflex_ops },
145
  { "cardos", (void *) sc_pkcs15init_get_cardos_ops },
146
  { "etoken", (void *) sc_pkcs15init_get_cardos_ops }, /* legacy */
147
  { "starcos", (void *) sc_pkcs15init_get_starcos_ops },
148
  { "oberthur", (void *) sc_pkcs15init_get_oberthur_ops },
149
  { "openpgp", (void *) sc_pkcs15init_get_openpgp_ops },
150
  { "setcos", (void *) sc_pkcs15init_get_setcos_ops },
151
  { "muscle", (void*) sc_pkcs15init_get_muscle_ops },
152
  { "asepcos", (void*) sc_pkcs15init_get_asepcos_ops },
153
  { "entersafe",(void*) sc_pkcs15init_get_entersafe_ops },
154
  { "epass2003",(void*) sc_pkcs15init_get_epass2003_ops },
155
  { "rutoken_ecp", (void *) sc_pkcs15init_get_rtecp_ops },
156
  { "rutoken_lite", (void *) sc_pkcs15init_get_rtecp_ops },
157
  { "myeid", (void *) sc_pkcs15init_get_myeid_ops },
158
  { "sc-hsm", (void *) sc_pkcs15init_get_sc_hsm_ops },
159
  { "isoApplet", (void *) sc_pkcs15init_get_isoApplet_ops },
160
  { "gids", (void *) sc_pkcs15init_get_gids_ops },
161
#ifdef ENABLE_OPENSSL
162
  { "authentic", (void *) sc_pkcs15init_get_authentic_ops },
163
  { "iasecc", (void *) sc_pkcs15init_get_iasecc_ops },
164
#endif
165
  { NULL, NULL },
166
};
167
168
169
static struct sc_pkcs15init_callbacks callbacks = {
170
  NULL,
171
  NULL,
172
};
173
174
175
static void sc_pkcs15init_free_ec_params(void *ptr)
176
1.20k
{
177
1.20k
  struct sc_ec_parameters *ecparams = (struct sc_ec_parameters *)ptr;
178
1.20k
  if (ecparams) {
179
1.20k
    sc_clear_ec_params(ecparams);
180
1.20k
    free(ecparams);
181
1.20k
  }
182
1.20k
}
183
184
/*
185
 * Set the application callbacks
186
 */
187
void
188
sc_pkcs15init_set_callbacks(struct sc_pkcs15init_callbacks *cb)
189
0
{
190
0
  callbacks.get_pin = cb? cb->get_pin : NULL;
191
0
  callbacks.get_key = cb? cb->get_key : NULL;
192
0
}
193
194
195
/*
196
 * Returns 1 if the a profile was found in the card's card_driver block
197
 * in the config file, or 0 otherwise.
198
 */
199
static int
200
get_profile_from_config(struct sc_card *card, char *buffer, size_t size)
201
0
{
202
0
  struct sc_context *ctx = card->ctx;
203
0
  const char *tmp;
204
0
  scconf_block **blocks, *blk;
205
0
  int i;
206
207
0
  for (i = 0; ctx->conf_blocks[i]; i++) {
208
0
    blocks = scconf_find_blocks(ctx->conf, ctx->conf_blocks[i],
209
0
          "card_driver",
210
0
          card->driver->short_name);
211
0
    if (!blocks)
212
0
      continue;
213
0
    blk = blocks[0];
214
0
    free(blocks);
215
0
    if (blk == NULL)
216
0
      continue;
217
218
0
    tmp = scconf_get_str(blk, "profile", NULL);
219
0
    if (tmp != NULL) {
220
0
      strlcpy(buffer, tmp, size);
221
0
      return 1;
222
0
    }
223
0
  }
224
225
0
  return 0;
226
0
}
227
228
229
static const char *
230
find_library(struct sc_context *ctx, const char *name)
231
0
{
232
0
  int          i;
233
0
  const char   *libname = NULL;
234
0
  scconf_block *blk, **blocks;
235
236
0
  for (i = 0; ctx->conf_blocks[i]; i++) {
237
0
    blocks = scconf_find_blocks(ctx->conf, ctx->conf_blocks[i], "framework", "pkcs15");
238
0
    if (!blocks)
239
0
      continue;
240
0
    blk = blocks[0];
241
0
    free(blocks);
242
0
    if (blk == NULL)
243
0
      continue;
244
0
    blocks = scconf_find_blocks(ctx->conf, blk, "pkcs15init", name);
245
0
    if (!blocks)
246
0
      continue;
247
0
    blk = blocks[0];
248
0
    free(blocks);
249
0
    if (blk == NULL)
250
0
      continue;
251
0
    libname = scconf_get_str(blk, "module", NULL);
252
0
    break;
253
0
  }
254
0
  if (!libname) {
255
0
    sc_log(ctx, "unable to locate pkcs15init driver for '%s'", name);
256
0
  }
257
0
  return libname;
258
0
}
259
260
261
static void *
262
load_dynamic_driver(struct sc_context *ctx, void **dll,
263
  const char *name)
264
0
{
265
0
  const char *version, *libname;
266
0
  void *handle;
267
0
  void *(*modinit)(const char *)  = NULL;
268
0
  const char *(*modversion)(void) = NULL;
269
270
0
  libname = find_library(ctx, name);
271
0
  if (!libname)
272
0
    return NULL;
273
0
  handle = sc_dlopen(libname);
274
0
  if (handle == NULL) {
275
0
    sc_log(ctx, "Module %s: cannot load '%s' library: %s", name, libname, sc_dlerror());
276
0
    return NULL;
277
0
  }
278
279
  /* verify correctness of module */
280
0
  modinit    = (void *(*)(const char *)) sc_dlsym(handle, "sc_module_init");
281
0
  modversion = (const char *(*)(void)) sc_dlsym(handle, "sc_driver_version");
282
0
  if (modinit == NULL || modversion == NULL) {
283
0
    sc_log(ctx, "dynamic library '%s' is not a OpenSC module",libname);
284
0
    sc_dlclose(handle);
285
0
    return NULL;
286
0
  }
287
  /* verify module version */
288
0
  version = modversion();
289
0
  if (version == NULL || strncmp(version, "0.9.", strlen("0.9.")) > 0) {
290
0
    sc_log(ctx,"dynamic library '%s': invalid module version",libname);
291
0
    sc_dlclose(handle);
292
0
    return NULL;
293
0
  }
294
0
  *dll = handle;
295
0
  sc_log(ctx, "successfully loaded pkcs15init driver '%s'", name);
296
297
0
  return modinit(name);
298
0
}
299
300
301
/*
302
 * Set up profile
303
 */
304
int
305
sc_pkcs15init_bind(struct sc_card *card, const char *name, const char *profile_option,
306
    struct sc_app_info *app_info, struct sc_profile **result)
307
0
{
308
0
  struct sc_context *ctx = card->ctx;
309
0
  struct sc_profile *profile;
310
0
  struct sc_pkcs15init_operations * (* func)(void) = NULL;
311
0
  const char  *driver = card->driver->short_name;
312
0
  char    card_profile[PATH_MAX];
313
0
  int   r, i;
314
315
0
  LOG_FUNC_CALLED(ctx);
316
  /* Put the card into administrative mode */
317
0
  r = sc_pkcs15init_set_lifecycle(card, SC_CARDCTRL_LIFECYCLE_ADMIN);
318
0
  if (r < 0 && r != SC_ERROR_NOT_SUPPORTED)
319
0
    LOG_TEST_RET(ctx, r, "Set lifecycle error");
320
321
0
  profile = sc_profile_new();
322
0
  profile->card = card;
323
324
0
  for (i = 0; profile_operations[i].name; i++) {
325
0
    if (!strcasecmp(driver, profile_operations[i].name)) {
326
0
      func = (struct sc_pkcs15init_operations *(*)(void)) profile_operations[i].func;
327
0
      break;
328
0
    }
329
0
  }
330
0
  if (!func) {
331
    /* no builtin support for this driver => look if there's a
332
     * dynamic module for this card */
333
0
    func = (struct sc_pkcs15init_operations *(*)(void)) load_dynamic_driver(card->ctx, &profile->dll, driver);
334
0
  }
335
0
  if (func) {
336
0
    profile->ops = func();
337
0
  }
338
0
  else {
339
0
    sc_log(ctx, "Unsupported card driver %s", driver);
340
0
    sc_profile_free(profile);
341
0
    LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Unsupported card driver");
342
0
  }
343
344
  /* Massage the main profile name to see if there are
345
   * any options in there
346
   */
347
0
  profile->name = strdup(name);
348
0
  if (strchr(profile->name, '+') != NULL) {
349
0
    char  *s;
350
351
0
    i = 0;
352
0
    (void) strtok(profile->name, "+");
353
0
    while ((s = strtok(NULL, "+")) != NULL) {
354
0
      if (i < SC_PKCS15INIT_MAX_OPTIONS-1)
355
0
        profile->options[i++] = strdup(s);
356
0
    }
357
0
  }
358
359
0
  r = sc_pkcs15init_read_info(card, profile);
360
0
  if (r < 0) {
361
0
    sc_profile_free(profile);
362
0
    LOG_TEST_RET(ctx, r, "Read info error");
363
0
  }
364
365
  /* Check the config file for a profile name.
366
   * If none is defined, use the default profile name.
367
   */
368
0
  if (!get_profile_from_config(card, card_profile, sizeof(card_profile)))
369
0
    strlcpy(card_profile, driver, sizeof card_profile);
370
0
  if (profile_option != NULL)
371
0
    strlcpy(card_profile, profile_option, sizeof(card_profile));
372
373
0
  do   {
374
0
    r = sc_profile_load(profile, profile->name);
375
0
    if (r < 0)   {
376
0
      sc_log(ctx, "Failed to load profile '%s': %s", profile->name, sc_strerror(r));
377
0
      break;
378
0
    }
379
380
0
    r = sc_profile_load(profile, card_profile);
381
0
    if (r < 0)   {
382
0
      sc_log(ctx, "Failed to load profile '%s': %s", card_profile, sc_strerror(r));
383
0
      break;
384
0
    }
385
386
0
    r = sc_profile_finish(profile, app_info);
387
0
    if (r < 0)
388
0
      sc_log(ctx, "Failed to finalize profile: %s", sc_strerror(r));
389
0
  }  while (0);
390
391
0
  if (r < 0) {
392
0
    sc_profile_free(profile);
393
0
    LOG_TEST_RET(ctx, r, "Load profile error");
394
0
  }
395
396
0
  if (app_info && app_info->aid.len)   {
397
0
    struct sc_path path;
398
399
0
    if (card->ef_atr && card->ef_atr->aid.len)   {
400
0
      sc_log(ctx, "sc_pkcs15init_bind() select MF using EF.ATR data");
401
0
      memset(&path, 0, sizeof(struct sc_path));
402
0
      path.type = SC_PATH_TYPE_DF_NAME;
403
0
      path.aid = card->ef_atr->aid;
404
0
      r = sc_select_file(card, &path, NULL);
405
0
      if (r)
406
0
        return r;
407
0
    }
408
409
0
    if (app_info->path.len)   {
410
0
      path = app_info->path;
411
0
    }
412
0
    else   {
413
0
      memset(&path, 0, sizeof(struct sc_path));
414
0
      path.type = SC_PATH_TYPE_DF_NAME;
415
0
      path.aid = app_info->aid;
416
0
    }
417
0
    sc_log(ctx, "sc_pkcs15init_bind() select application path(type:%X) '%s'", path.type, sc_print_path(&path));
418
0
    r = sc_select_file(card, &path, NULL);
419
0
  }
420
421
0
  *result = profile;
422
0
  LOG_FUNC_RETURN(ctx, r);
423
0
}
424
425
426
void
427
sc_pkcs15init_unbind(struct sc_profile *profile)
428
8.03k
{
429
8.03k
  int r;
430
8.03k
  struct sc_context *ctx = profile->card->ctx;
431
432
8.03k
  LOG_FUNC_CALLED(ctx);
433
8.03k
  sc_log(ctx, "Pksc15init Unbind: %i:%p:%i", profile->dirty, profile->p15_data, profile->pkcs15.do_last_update);
434
8.03k
  if (profile->dirty != 0 && profile->p15_data != NULL && profile->pkcs15.do_last_update) {
435
1.21k
    r = sc_pkcs15init_update_lastupdate(profile->p15_data, profile);
436
1.21k
    if (r < 0)
437
547
      sc_log(ctx, "Failed to update TokenInfo: %s", sc_strerror(r));
438
1.21k
  }
439
8.03k
  sc_profile_free(profile);
440
8.03k
}
441
442
443
void
444
sc_pkcs15init_set_p15card(struct sc_profile *profile, struct sc_pkcs15_card *p15card)
445
5.59k
{
446
5.59k
  struct sc_context *ctx = p15card->card->ctx;
447
5.59k
  struct sc_pkcs15_object *p15objects[10];
448
5.59k
  int i, r, nn_objs;
449
450
5.59k
  LOG_FUNC_CALLED(ctx);
451
452
  /* Prepare pin-domain instantiation:
453
   * for every present local User PIN, add to the profile EF list the named PIN path. */
454
5.59k
  nn_objs = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_AUTH_PIN, p15objects, 10);
455
6.69k
  for (i = 0; i < nn_objs; i++) {
456
1.10k
    struct sc_pkcs15_auth_info *auth_info = (struct sc_pkcs15_auth_info *) p15objects[i]->data;
457
1.10k
    struct sc_pkcs15_pin_attributes *pin_attrs = &auth_info->attrs.pin;
458
1.10k
    struct sc_file *file = NULL;
459
460
1.10k
    if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN)
461
72
      continue;
462
1.02k
    if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN)
463
507
      continue;
464
521
    if (!auth_info->path.len)
465
486
      continue;
466
467
35
    r = sc_profile_get_file_by_path(profile, &auth_info->path, &file);
468
35
                if (r == SC_ERROR_FILE_NOT_FOUND)   {
469
32
      if (!sc_select_file(p15card->card, &auth_info->path, &file))   {
470
8
        char pin_name[16];
471
472
8
        sprintf(pin_name, "pin-dir-%02X%02X", file->path.value[file->path.len - 2],
473
8
            file->path.value[file->path.len - 1]);
474
8
        sc_log(ctx, "add '%s' to profile file list", pin_name);
475
8
        sc_profile_add_file(profile, pin_name, file);
476
8
      }
477
32
    }
478
479
35
    sc_file_free(file);
480
35
  }
481
482
5.59k
  profile->p15_data = p15card;
483
5.59k
  sc_log(ctx, "sc_pkcs15init_set_p15card() returns");
484
5.59k
}
485
486
487
/*
488
 * Set the card's lifecycle
489
 */
490
int
491
sc_pkcs15init_set_lifecycle(struct sc_card *card, int lcycle)
492
17.9k
{
493
17.9k
  return sc_card_ctl(card, SC_CARDCTL_LIFECYCLE_SET, &lcycle);
494
17.9k
}
495
496
497
/*
498
 * Erase the card
499
 */
500
int
501
sc_pkcs15init_erase_card(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
502
    struct sc_aid *aid)
503
5.59k
{
504
5.59k
  struct sc_context *ctx = NULL;
505
5.59k
  int rv;
506
507
5.59k
  if (!p15card)
508
0
    return SC_ERROR_INVALID_ARGUMENTS;
509
510
5.59k
  ctx = p15card->card->ctx;
511
5.59k
  LOG_FUNC_CALLED(ctx);
512
  /* Needs the 'SOPIN' AUTH pkcs15 object.
513
   * So that, SOPIN can be found by it's reference. */
514
5.59k
  if (sc_pkcs15_bind(p15card->card, aid, &p15card) >= 0)
515
1.03k
    profile->p15_data = p15card;
516
517
5.59k
  if (profile->ops->erase_card == NULL)
518
5.59k
    LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
519
520
5.05k
  rv = profile->ops->erase_card(profile, p15card);
521
522
5.05k
  LOG_FUNC_RETURN(ctx, rv);
523
5.05k
}
524
525
526
int
527
sc_pkcs15init_erase_card_recursively(struct sc_pkcs15_card *p15card,
528
    struct sc_profile *profile)
529
223
{
530
223
  struct sc_file  *df = profile->df_info->file, *dir;
531
223
  int   r;
532
533
  /* Delete EF(DIR). This may not be very nice
534
   * against other applications that use this file, but
535
   * extremely useful for testing :)
536
   * Note we need to delete it before the DF because we create
537
   * it *after* the DF. Some cards (e.g. the cryptoflex) want
538
   * us to delete files in reverse order of creation.
539
   * */
540
223
  if (sc_profile_get_file(profile, "DIR", &dir) >= 0) {
541
16
    r = sc_pkcs15init_rmdir(p15card, profile, dir);
542
16
    sc_file_free(dir);
543
16
    if (r < 0 && r != SC_ERROR_FILE_NOT_FOUND)   {
544
13
      sc_free_apps(p15card->card);
545
13
      return r;
546
13
    }
547
16
  }
548
549
210
  r = sc_select_file(p15card->card, &df->path, &df);
550
210
  if (r >= 0) {
551
26
    r = sc_pkcs15init_rmdir(p15card, profile, df);
552
26
    sc_file_free(df);
553
26
  }
554
210
  if (r == SC_ERROR_FILE_NOT_FOUND)
555
2
    r = 0;
556
557
210
  sc_free_apps(p15card->card);
558
210
  return r;
559
223
}
560
561
562
int
563
sc_pkcs15init_delete_by_path(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
564
    const struct sc_path *file_path)
565
1.95k
{
566
1.95k
  struct sc_context *ctx = p15card->card->ctx;
567
1.95k
  struct sc_file *parent = NULL, *file = NULL;
568
1.95k
  struct sc_path path;
569
1.95k
  int rv;
570
  /*int file_type = SC_FILE_TYPE_DF;*/
571
572
1.95k
  LOG_FUNC_CALLED(ctx);
573
1.95k
  sc_log(ctx, "trying to delete '%s'", sc_print_path(file_path));
574
575
  /* For some cards, to delete file should be satisfied the 'DELETE' ACL of the file itself,
576
   * for the others the 'DELETE' ACL of parent.
577
   * Let's start from the file's 'DELETE' ACL.
578
   *
579
   * TODO: 'DELETE_SELF' exists. Proper solution would be to use this acl by every
580
   * card (driver and profile) that uses self delete ACL.
581
   */
582
  /* Select the file itself */
583
1.95k
  path = *file_path;
584
1.95k
  rv = sc_select_file(p15card->card, &path, &file);
585
1.95k
  LOG_TEST_RET(ctx, rv, "cannot select file to delete");
586
587
608
  if (sc_file_get_acl_entry(file, SC_AC_OP_DELETE_SELF))   {
588
2
    sc_log(ctx, "Found 'DELETE-SELF' acl");
589
2
    rv = sc_pkcs15init_authenticate(profile, p15card, file, SC_AC_OP_DELETE_SELF);
590
2
    sc_file_free(file);
591
2
  }
592
606
  else if (sc_file_get_acl_entry(file, SC_AC_OP_DELETE))   {
593
218
    sc_log(ctx, "Found 'DELETE' acl");
594
218
          rv = sc_pkcs15init_authenticate(profile, p15card, file, SC_AC_OP_DELETE);
595
218
    sc_file_free(file);
596
218
  }
597
388
  else    {
598
388
    sc_log(ctx, "Try to get the parent's 'DELETE' access");
599
    /*file_type = file->type;*/
600
388
    if (file_path->len >= 2) {
601
      /* Select the parent DF */
602
348
      path.len -= 2;
603
348
      rv = sc_select_file(p15card->card, &path, &parent);
604
348
      if (rv < 0)
605
73
        sc_file_free(file);
606
348
      LOG_TEST_RET(ctx, rv, "Cannot select parent");
607
608
275
      rv = sc_pkcs15init_authenticate(profile, p15card, parent, SC_AC_OP_DELETE);
609
275
      sc_file_free(parent);
610
275
      sc_file_free(file);
611
275
      LOG_TEST_RET(ctx, rv, "parent 'DELETE' authentication failed");
612
275
    }
613
40
    else {
614
      /* No 'DELETE' ACL of the file and not deleted for parent */
615
40
      rv = SC_ERROR_INVALID_ARGUMENTS;
616
40
      sc_file_free(file);
617
40
    }
618
388
  }
619
515
  LOG_TEST_RET(ctx, rv, "'DELETE' authentication failed");
620
621
  /* Reselect file to delete: current path could be changed by 'verify PIN' procedure */
622
395
  path = *file_path;
623
395
  rv = sc_select_file(p15card->card, &path, &file);
624
395
  LOG_TEST_RET(ctx, rv, "cannot select file to delete");
625
626
309
  memset(&path, 0, sizeof(path));
627
309
  path.type = SC_PATH_TYPE_FILE_ID;
628
309
  if (file_path->len < 2) {
629
5
    sc_file_free(file);
630
5
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
631
5
  }
632
304
  path.value[0] = file_path->value[file_path->len - 2];
633
304
  path.value[1] = file_path->value[file_path->len - 1];
634
304
  path.len = 2;
635
636
  /* Reselect file to delete if the parent DF was selected and it's not DF. */
637
/*
638
  if (file_type != SC_FILE_TYPE_DF)   {
639
    rv = sc_select_file(p15card->card, &path, &file);
640
    LOG_TEST_RET(ctx, rv, "cannot select file to delete");
641
  }
642
*/
643
644
304
  sc_log(ctx, "Now really delete file");
645
304
  rv = sc_delete_file(p15card->card, &path);
646
304
  sc_file_free(file);
647
304
  LOG_FUNC_RETURN(ctx, rv);
648
304
}
649
650
651
/*
652
 * Try to delete a file (and, in the DF case, its contents).
653
 * Note that this will not work if a pkcs#15 file's ERASE AC
654
 * references a pin other than the SO pin.
655
 */
656
int
657
sc_pkcs15init_rmdir(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
658
    struct sc_file *df)
659
44
{
660
44
  struct sc_context *ctx = p15card->card->ctx;
661
44
  unsigned char buffer[1024];
662
44
  struct sc_path  path;
663
44
  struct sc_file  *file, *parent;
664
44
  int   r = 0, nfids;
665
666
44
  if (df == NULL)
667
0
    return SC_ERROR_INTERNAL;
668
44
  sc_log(ctx, "sc_pkcs15init_rmdir(%s)", sc_print_path(&df->path));
669
670
44
  if (df->type == SC_FILE_TYPE_DF) {
671
31
    r = sc_pkcs15init_authenticate(profile, p15card, df, SC_AC_OP_LIST_FILES);
672
31
    if (r < 0)
673
2
      return r;
674
29
    r = sc_list_files(p15card->card, buffer, sizeof(buffer));
675
29
    if (r < 0)
676
18
      return r;
677
678
11
    path = df->path;
679
11
    path.len += 2;
680
11
    if (path.len > SC_MAX_PATH_SIZE)
681
1
      return SC_ERROR_INTERNAL;
682
683
10
    nfids = r / 2;
684
13
    while (r >= 0 && nfids--) {
685
7
      path.value[path.len-2] = buffer[2*nfids];
686
7
      path.value[path.len-1] = buffer[2*nfids+1];
687
7
      r = sc_select_file(p15card->card, &path, &file);
688
7
      if (r < 0) {
689
5
        if (r == SC_ERROR_FILE_NOT_FOUND)
690
1
          continue;
691
4
        break;
692
5
      }
693
2
      r = sc_pkcs15init_rmdir(p15card, profile, file);
694
2
      sc_file_free(file);
695
2
    }
696
697
10
    if (r < 0)
698
7
      return r;
699
10
  }
700
701
  /* Select the parent DF */
702
16
  path = df->path;
703
16
  if (path.len <= 2)
704
7
    return SC_ERROR_INVALID_ARGUMENTS;
705
9
  path.len -= 2;
706
9
  r = sc_select_file(p15card->card, &path, &parent);
707
9
  if (r < 0)
708
3
    return r;
709
710
6
  r = sc_pkcs15init_authenticate(profile, p15card, df, SC_AC_OP_DELETE);
711
6
  if (r < 0) {
712
1
    sc_file_free(parent);
713
1
    return r;
714
1
  }
715
5
  r = sc_pkcs15init_authenticate(profile, p15card, parent, SC_AC_OP_DELETE);
716
5
  sc_file_free(parent);
717
5
  if (r < 0)
718
1
    return r;
719
720
4
  memset(&path, 0, sizeof(path));
721
4
  path.type = SC_PATH_TYPE_FILE_ID;
722
4
  path.value[0] = df->id >> 8;
723
4
  path.value[1] = df->id & 0xFF;
724
4
  path.len = 2;
725
726
  /* ensure that the card is in the correct lifecycle */
727
4
  r = sc_pkcs15init_set_lifecycle(p15card->card, SC_CARDCTRL_LIFECYCLE_ADMIN);
728
4
  if (r < 0 && r != SC_ERROR_NOT_SUPPORTED)
729
1
    return r;
730
731
3
  r = sc_delete_file(p15card->card, &path);
732
3
  return r;
733
4
}
734
735
736
int
737
sc_pkcs15init_finalize_card(struct sc_card *card, struct sc_profile *profile)
738
5.59k
{
739
5.59k
  if (profile->ops->finalize_card == NULL)
740
3.94k
    return SC_ERROR_NOT_SUPPORTED;
741
1.65k
  return profile->ops->finalize_card(card);
742
5.59k
}
743
744
745
int
746
sc_pkcs15init_finalize_profile(struct sc_card *card, struct sc_profile *profile,
747
    struct sc_aid *aid)
748
0
{
749
0
  struct sc_context *ctx = card->ctx;
750
0
  const struct sc_app_info *app = NULL;
751
0
  int rv;
752
753
0
  LOG_FUNC_CALLED(ctx);
754
0
  if (card->app_count < 0 && SC_SUCCESS != sc_enum_apps(card))
755
0
    sc_log(ctx, "Could not enumerate apps");
756
757
0
  if (aid)   {
758
0
    sc_log(ctx, "finalize profile for AID %s", sc_dump_hex(aid->value, aid->len));
759
0
    app = sc_find_app(card, aid);
760
0
  }
761
0
  else if (card->app_count == 1) {
762
0
    app = card->app[0];
763
0
  }
764
0
  else if (card->app_count > 1) {
765
0
    LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Need AID defined in this context");
766
0
  }
767
768
0
  sc_log(ctx, "Finalize profile with application '%s'", app ? app->label : "default");
769
0
  rv = sc_profile_finish(profile, app);
770
771
0
  sc_log(ctx, "sc_pkcs15init_finalize_profile() returns %i", rv);
772
0
  LOG_FUNC_RETURN(ctx, rv);
773
0
}
774
775
/*
776
 * Initialize the PKCS#15 application
777
 */
778
int
779
sc_pkcs15init_add_app(struct sc_card *card, struct sc_profile *profile,
780
    struct sc_pkcs15init_initargs *args)
781
8.03k
{
782
8.03k
  struct sc_context *ctx = card->ctx;
783
8.03k
  struct sc_pkcs15_card *p15card = profile->p15_spec;
784
8.03k
  struct sc_pkcs15_auth_info pin_ainfo, puk_ainfo;
785
8.03k
  struct sc_pkcs15_pin_attributes *pin_attrs = &pin_ainfo.attrs.pin;
786
8.03k
  struct sc_pkcs15_object *pin_obj = NULL;
787
8.03k
  struct sc_app_info  *app;
788
8.03k
  struct sc_file    *df = profile->df_info->file;
789
8.03k
  int     r = SC_SUCCESS;
790
8.03k
  int     has_so_pin = args->so_pin_len != 0;
791
792
8.03k
  LOG_FUNC_CALLED(ctx);
793
8.03k
  p15card->card = card;
794
795
  /* FIXME:
796
   * Some cards need pincache
797
   *  for ex. to create temporary CHV key with the value of default AUTH key.
798
   */
799
8.03k
  p15card->opts.use_pin_cache = 1;
800
801
8.03k
  if (card->app_count >= SC_MAX_CARD_APPS)
802
8.03k
    LOG_TEST_RET(ctx, SC_ERROR_TOO_MANY_OBJECTS, "Too many applications on this card.");
803
804
  /* In case of pinpad readers check if SO PIN is defined in a profile */
805
8.03k
  if (!has_so_pin && (card->reader->capabilities & SC_READER_CAP_PIN_PAD)) {
806
0
    sc_profile_get_pin_info(profile, SC_PKCS15INIT_SO_PIN, &pin_ainfo);
807
    /* If found, assume we want SO PIN */
808
0
    has_so_pin = pin_ainfo.attrs.pin.reference != -1;
809
0
  }
810
811
  /* If the profile requires an SO PIN, check min/max length */
812
8.03k
  if (has_so_pin) {
813
8.03k
    const char  *pin_label;
814
815
8.03k
    if (args->so_pin_len) {
816
8.03k
      sc_profile_get_pin_info(profile, SC_PKCS15INIT_SO_PIN, &pin_ainfo);
817
8.03k
      r = sc_pkcs15init_qualify_pin(card, "SO PIN", args->so_pin_len, &pin_ainfo);
818
8.03k
      LOG_TEST_RET(ctx, r, "Failed to qualify SO PIN");
819
8.03k
    }
820
821
    /* Path encoded only for local SO PIN */
822
2.15k
    if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_LOCAL)
823
1.84k
      pin_ainfo.path = df->path;
824
825
    /* Select the PIN reference */
826
2.15k
    if (profile->ops->select_pin_reference) {
827
2.01k
      r = profile->ops->select_pin_reference(profile, p15card, &pin_ainfo);
828
2.01k
      LOG_TEST_RET(ctx, r, "Failed to select card specific PIN reference");
829
2.01k
    }
830
831
1.77k
    sc_profile_get_pin_info(profile, SC_PKCS15INIT_SO_PUK, &puk_ainfo);
832
1.77k
    r = sc_pkcs15init_qualify_pin(card, "SO PUK", args->so_puk_len, &puk_ainfo);
833
1.77k
    LOG_TEST_RET(ctx, r, "Failed to qualify SO PUK");
834
835
1.44k
    if (!(pin_label = args->so_pin_label)) {
836
1.44k
      if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN)
837
324
        pin_label = "Security Officer PIN";
838
1.11k
      else
839
1.11k
        pin_label = "User PIN";
840
1.44k
    }
841
842
1.44k
    if (args->so_puk_len == 0)
843
223
      pin_attrs->flags |= SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED;
844
845
1.44k
    pin_obj = sc_pkcs15init_new_object(SC_PKCS15_TYPE_AUTH_PIN, pin_label, NULL, &pin_ainfo);
846
1.44k
    if (pin_obj)   {
847
      /* When composing ACLs to create 'DIR' DF,
848
       *  the references of the not-yet-existing PINs can be requested.
849
       * For this, create a 'virtual' AUTH object 'SO PIN', accessible by the card specific part,
850
       * but not yet written into the on-card PKCS#15.
851
       */
852
1.44k
      sc_log(ctx, "Add virtual SO_PIN('%.*s',flags:%X,reference:%i,path:'%s')", (int) sizeof pin_obj->label, pin_obj->label,
853
1.44k
          pin_attrs->flags, pin_attrs->reference, sc_print_path(&pin_ainfo.path));
854
855
1.44k
      r = sc_pkcs15_add_object(p15card, pin_obj);
856
1.44k
      LOG_TEST_GOTO_ERR(ctx, r, "Failed to add 'SOPIN' AUTH object");
857
1.44k
    }
858
1.44k
  }
859
860
  /* Perform card-specific initialization */
861
1.44k
  if (profile->ops->init_card)   {
862
1.16k
    r = profile->ops->init_card(profile, p15card);
863
1.16k
    if (r < 0 && pin_obj)   {
864
574
      sc_pkcs15_remove_object(p15card, pin_obj);
865
574
    }
866
1.16k
    LOG_TEST_GOTO_ERR(ctx, r, "Card specific init failed");
867
1.16k
  }
868
869
  /* Create the application directory */
870
867
  if (profile->ops->create_dir) {
871
797
    r = profile->ops->create_dir(profile, p15card, df);
872
797
    if (r < 0 && pin_obj)   {
873
553
      sc_pkcs15_remove_object(p15card, pin_obj);
874
553
    }
875
797
    LOG_TEST_GOTO_ERR(ctx, r, "Create 'DIR' error");
876
797
  }
877
878
  /* Store SO PIN */
879
314
  if (pin_obj && profile->ops->create_pin)
880
244
    r = profile->ops->create_pin(profile, p15card, df, pin_obj,
881
244
        args->so_pin, args->so_pin_len,
882
244
        args->so_puk, args->so_puk_len);
883
884
314
  if (pin_obj)
885
    /* Remove 'virtual' AUTH object . */
886
314
    sc_pkcs15_remove_object(p15card, pin_obj);
887
888
314
  LOG_TEST_GOTO_ERR(ctx, r, "Card specific create application DF failed");
889
890
  /* Store the PKCS15 information on the card */
891
219
  app = (struct sc_app_info *)calloc(1, sizeof(*app));
892
219
  if (app == NULL) {
893
0
    r = SC_ERROR_OUT_OF_MEMORY;
894
0
    LOG_TEST_GOTO_ERR(ctx, r, "Failed to allocate application info");
895
0
  }
896
897
219
  app->path = p15card->file_app->path;
898
219
  if (p15card->file_app->namelen <= SC_MAX_AID_SIZE) {
899
219
    app->aid.len = p15card->file_app->namelen;
900
219
    memcpy(app->aid.value, p15card->file_app->name, app->aid.len);
901
219
  }
902
903
  /* set serial number if explicitly specified */
904
219
  if (args->serial)   {
905
0
    sc_pkcs15init_set_serial(profile, args->serial);
906
0
  }
907
219
  else {
908
    /* otherwise try to get the serial number from the card */
909
219
    struct sc_serial_number serialnr;
910
911
219
    r = sc_card_ctl(card, SC_CARDCTL_GET_SERIALNR, &serialnr);
912
219
    if (r == SC_SUCCESS) {
913
109
      char hex_serial[SC_MAX_SERIALNR * 2 + 1];
914
915
109
      sc_bin_to_hex(serialnr.value, serialnr.len, hex_serial, sizeof(hex_serial), 0);
916
109
      sc_pkcs15init_set_serial(profile, hex_serial);
917
109
    }
918
219
  }
919
920
219
  if (args->label) {
921
0
    free(p15card->tokeninfo->label);
922
0
    p15card->tokeninfo->label = strdup(args->label);
923
0
  }
924
219
  if (p15card->tokeninfo->label)
925
219
    app->label = strdup(p15card->tokeninfo->label);
926
0
  else
927
0
    app->label = strdup("Token");
928
929
  /* See if we've set an SO PIN */
930
219
  r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_AODF, pin_obj);
931
219
  if (r >= 0) {
932
95
    r = sc_pkcs15init_update_dir(p15card, profile, app);
933
95
    if (r >= 0) {
934
34
      r = sc_pkcs15init_update_tokeninfo(p15card, profile);
935
61
    } else {
936
      /* FIXED: what to do if sc_pkcs15init_update_dir failed? */
937
      /* sc_pkcs15init_update_dir may add app to card->app[] */
938
61
      int found = 0;
939
61
      int i;
940
61
      for (i = 0; i < card->app_count; i++) {
941
29
        if (card->app[i] == app) {
942
29
          found = 1;
943
29
          break;
944
29
        }
945
29
      }
946
61
      if (found == 0) { /* not in card->app[] free it */
947
32
        free(app->label);
948
32
        free(app); /* unused */
949
32
      }
950
61
    }
951
95
  }
952
124
  else {
953
124
    free(app->label);
954
124
    free(app); /* unused */
955
124
    LOG_TEST_GOTO_ERR(ctx, r, "Failed to add pin object.");
956
124
  }
957
958
95
  sc_pkcs15init_write_info(p15card, profile, pin_obj);
959
95
  pin_obj = NULL;
960
961
1.44k
err:
962
1.44k
  sc_pkcs15_free_object(pin_obj);
963
1.44k
  LOG_FUNC_RETURN(ctx, r);
964
1.44k
}
965
966
967
/*
968
 * Store a PIN/PUK pair
969
 */
970
static int
971
sc_pkcs15init_store_puk(struct sc_pkcs15_card *p15card,
972
      struct sc_profile *profile,
973
      struct sc_pkcs15init_pinargs *args)
974
0
{
975
0
  struct sc_context *ctx = p15card->card->ctx;
976
0
  struct sc_pkcs15_object *pin_obj;
977
0
  struct sc_pkcs15_auth_info *auth_info;
978
0
  int     r;
979
0
  char puk_label[0x30];
980
981
0
  LOG_FUNC_CALLED(ctx);
982
0
  if (!args->puk_id.len)
983
0
    LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "PUK auth ID not supplied");
984
985
  /* Make sure we don't get duplicate PIN IDs */
986
0
  r = sc_pkcs15_find_pin_by_auth_id(p15card, &args->puk_id, NULL);
987
0
  if (r != SC_ERROR_OBJECT_NOT_FOUND)
988
0
    LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "There already is a PIN with this ID.");
989
990
0
  if (!args->puk_label)   {
991
0
    if (args->label)
992
0
      snprintf(puk_label, sizeof(puk_label), "%s (PUK)", args->label);
993
0
    else
994
0
      snprintf(puk_label, sizeof(puk_label), "User PUK");
995
996
0
    args->puk_label = puk_label;
997
0
  }
998
999
0
  args->pin = args->puk;
1000
0
  args->pin_len = args->puk_len;
1001
0
  args->puk = NULL;
1002
0
  args->puk_len = 0;
1003
1004
0
  pin_obj = sc_pkcs15init_new_object(SC_PKCS15_TYPE_AUTH_PIN, args->puk_label, NULL, NULL);
1005
0
  if (pin_obj == NULL)
1006
0
    LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate PIN object");
1007
1008
0
  auth_info = (struct sc_pkcs15_auth_info *) pin_obj->data;
1009
1010
0
  sc_profile_get_pin_info(profile, SC_PKCS15INIT_USER_PUK, auth_info);
1011
0
  if (auth_info == NULL)
1012
0
    LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "Failed to retrieve auth_info");
1013
1014
0
  auth_info->auth_id = args->puk_id;
1015
1016
  /* Now store the PINs */
1017
0
  if (profile->ops->create_pin) {
1018
0
    r = sc_pkcs15init_create_pin(p15card, profile, pin_obj, args);
1019
0
    LOG_TEST_GOTO_ERR(ctx, r, "Failed to create PIN");
1020
0
  }
1021
0
  else {
1022
0
    r = SC_ERROR_NOT_SUPPORTED;
1023
0
    LOG_TEST_GOTO_ERR(ctx, r, "In Old API store PUK object is not supported");
1024
0
  }
1025
1026
0
  r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_AODF, pin_obj);
1027
0
  LOG_TEST_GOTO_ERR(ctx, r, "Add pin object error");
1028
1029
0
  profile->dirty = 1;
1030
1031
0
  pin_obj = NULL;
1032
1033
0
err:
1034
0
  sc_pkcs15_free_object(pin_obj);
1035
0
  LOG_FUNC_RETURN(ctx, r);
1036
0
}
1037
1038
1039
int
1040
sc_pkcs15init_store_pin(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
1041
      struct sc_pkcs15init_pinargs *args)
1042
5.59k
{
1043
5.59k
  struct sc_context *ctx = p15card->card->ctx;
1044
5.59k
  struct sc_pkcs15_object *pin_obj;
1045
5.59k
  struct sc_pkcs15_auth_info *auth_info;
1046
5.59k
  int     r;
1047
1048
5.59k
  LOG_FUNC_CALLED(ctx);
1049
  /* No auth_id given: select one */
1050
5.59k
  if (args->auth_id.len == 0) {
1051
0
    unsigned int  n;
1052
1053
0
    args->auth_id.len = 1;
1054
0
    for (n = 1, r = 0; n < 256; n++) {
1055
0
      args->auth_id.value[0] = n;
1056
0
      r = sc_pkcs15_find_pin_by_auth_id(p15card, &args->auth_id, NULL);
1057
0
      if (r == SC_ERROR_OBJECT_NOT_FOUND)
1058
0
        break;
1059
0
    }
1060
1061
0
    if (r != SC_ERROR_OBJECT_NOT_FOUND)
1062
0
      LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "No auth_id specified for new PIN");
1063
0
  }
1064
5.59k
  else   {
1065
    /* Make sure we don't get duplicate PIN IDs */
1066
5.59k
    r = sc_pkcs15_find_pin_by_auth_id(p15card, &args->auth_id, NULL);
1067
5.59k
    if (r != SC_ERROR_OBJECT_NOT_FOUND)
1068
5.59k
      LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "There already is a PIN with this ID.");
1069
5.59k
  }
1070
1071
5.11k
  pin_obj = sc_pkcs15init_new_object(SC_PKCS15_TYPE_AUTH_PIN, args->label, NULL, NULL);
1072
5.11k
  if (pin_obj == NULL)
1073
5.11k
    LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate PIN object");
1074
1075
5.11k
  auth_info = (struct sc_pkcs15_auth_info *) pin_obj->data;
1076
1077
5.11k
  sc_profile_get_pin_info(profile, SC_PKCS15INIT_USER_PIN, auth_info);
1078
5.11k
  if (auth_info == NULL)
1079
5.11k
    LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "Failed to retrieve auth_info");
1080
1081
5.11k
  auth_info->auth_id = args->auth_id;
1082
1083
  /* Now store the PINs */
1084
5.11k
  sc_log(ctx, "Store PIN(%.*s,authID:%s)", (int) sizeof pin_obj->label, pin_obj->label, sc_pkcs15_print_id(&auth_info->auth_id));
1085
5.11k
  if (profile->ops->create_pin) {
1086
4.44k
    r = sc_pkcs15init_create_pin(p15card, profile, pin_obj, args);
1087
4.44k
    LOG_TEST_GOTO_ERR(ctx, r, "Card specific create PIN failed.");
1088
4.44k
  } else {
1089
663
    r = SC_ERROR_NOT_SUPPORTED;
1090
663
    LOG_TEST_GOTO_ERR(ctx, r, "Store PIN operation is not supported");
1091
663
  }
1092
1093
391
  r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_AODF, pin_obj);
1094
391
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to add PIN object");
1095
1096
31
  if (args->puk_id.len)
1097
0
    r = sc_pkcs15init_store_puk(p15card, profile, args);
1098
1099
31
  profile->dirty = 1;
1100
1101
31
  pin_obj = NULL;
1102
1103
5.11k
err:
1104
5.11k
  sc_pkcs15_free_object(pin_obj);
1105
5.11k
  LOG_FUNC_RETURN(ctx, r);
1106
5.11k
}
1107
1108
1109
static int
1110
sc_pkcs15init_create_pin(struct sc_pkcs15_card *p15card,
1111
    struct sc_profile *profile,
1112
    struct sc_pkcs15_object *pin_obj,
1113
    struct sc_pkcs15init_pinargs *args)
1114
4.44k
{
1115
4.44k
  struct sc_context *ctx = p15card->card->ctx;
1116
4.44k
  struct sc_pkcs15_auth_info *auth_info = (struct sc_pkcs15_auth_info *) pin_obj->data;
1117
4.44k
  struct sc_pkcs15_pin_attributes *pin_attrs = &auth_info->attrs.pin;
1118
4.44k
  struct sc_file  *df = profile->df_info->file;
1119
4.44k
  int   r, retry = 0;
1120
1121
4.44k
  LOG_FUNC_CALLED(ctx);
1122
  /* Some cards need to keep all their PINs in separate directories.
1123
   * Create a subdirectory now, and put the pin into
1124
   * this subdirectory
1125
   */
1126
4.44k
  if (profile->pin_domains) {
1127
9
    if (!profile->ops->create_domain)
1128
9
      LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "PIN domains not supported.");
1129
1130
1
    r = profile->ops->create_domain(profile, p15card, &auth_info->auth_id, &df);
1131
1
    LOG_TEST_RET(ctx, r, "Card specific create domain failed");
1132
1
  }
1133
1134
  /* Path encoded only for local PINs */
1135
4.43k
  if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_LOCAL)
1136
4.39k
    auth_info->path = df->path;
1137
1138
  /* pin_info->reference = 0; */
1139
1140
  /* Loop until we come up with an acceptable pin reference */
1141
4.44k
  while (1) {
1142
4.44k
    if (profile->ops->select_pin_reference) {
1143
4.10k
      r = profile->ops->select_pin_reference(profile, p15card, auth_info);
1144
4.10k
      LOG_TEST_RET(ctx, r, "Card specific select PIN reference failed");
1145
1146
2.70k
      retry = 1;
1147
2.70k
    }
1148
1149
3.03k
    r = sc_pkcs15_find_pin_by_reference(p15card, &auth_info->path, pin_attrs->reference, NULL);
1150
3.03k
    if (r == SC_ERROR_OBJECT_NOT_FOUND)
1151
3.03k
      break;
1152
1153
3
    if (r != 0 || !retry)
1154
      /* Other error trying to retrieve pin obj */
1155
3
      LOG_TEST_RET(ctx, SC_ERROR_TOO_MANY_OBJECTS, "Failed to allocate PIN reference.");
1156
1157
3
    pin_attrs->reference++;
1158
3
  }
1159
1160
3.03k
  if (args->puk_len == 0)
1161
0
    pin_attrs->flags |= SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED;
1162
1163
3.03k
  sc_log(ctx, "create PIN with reference:%X, flags:%X, path:%s",
1164
3.03k
      pin_attrs->reference, pin_attrs->flags, sc_print_path(&auth_info->path));
1165
3.03k
  r = profile->ops->create_pin(profile, p15card,
1166
3.03k
      df, pin_obj,
1167
3.03k
      args->pin, args->pin_len,
1168
3.03k
      args->puk, args->puk_len);
1169
1170
3.03k
  if (df != profile->df_info->file)
1171
0
    sc_file_free(df);
1172
1173
3.03k
  LOG_FUNC_RETURN(ctx, r);
1174
3.03k
}
1175
1176
1177
/*
1178
 * Default function for creating a pin subdirectory
1179
 */
1180
int
1181
sc_pkcs15_create_pin_domain(struct sc_profile *profile,
1182
    struct sc_pkcs15_card *p15card, const struct sc_pkcs15_id *id,
1183
    struct sc_file **ret)
1184
1
{
1185
1
  struct sc_context *ctx = p15card->card->ctx;
1186
1
  struct sc_file *df = profile->df_info->file;
1187
1
  int r;
1188
1189
1
  sc_log(ctx, "create PIN domain (path:%s,ID:%s)", sc_print_path(&df->path), sc_pkcs15_print_id(id));
1190
  /* Instantiate PIN directory just below the application DF */
1191
1
  r = sc_profile_instantiate_template(profile, "pin-domain", &df->path, "pin-dir", id, ret);
1192
1
  if (r >= 0)   {
1193
0
    sc_log(ctx, "create PIN DF(path:%s)", sc_print_path(&(*ret)->path));
1194
0
    r = profile->ops->create_dir(profile, p15card, *ret);
1195
0
  }
1196
1197
1
  return r;
1198
1
}
1199
1200
static int
1201
sc_pkcs15init_encode_prvkey_content(struct sc_pkcs15_card *p15card, struct sc_pkcs15_prkey *prvkey,
1202
    struct sc_pkcs15_object *object)
1203
0
{
1204
0
  struct sc_context *ctx = p15card->card->ctx;
1205
1206
0
  LOG_FUNC_CALLED(ctx);
1207
0
  if (prvkey->algorithm == SC_ALGORITHM_RSA)   {
1208
0
    struct sc_pkcs15_pubkey pubkey;
1209
0
    int rv;
1210
1211
0
    pubkey.algorithm = prvkey->algorithm;
1212
0
    pubkey.u.rsa.modulus = prvkey->u.rsa.modulus;
1213
0
    pubkey.u.rsa.exponent = prvkey->u.rsa.exponent;
1214
1215
0
    rv = sc_pkcs15_encode_pubkey(ctx, &pubkey, &object->content.value, &object->content.len);
1216
0
    LOG_TEST_RET(ctx, rv, "Failed to encode public key");
1217
0
  }
1218
0
  LOG_FUNC_RETURN(ctx, SC_SUCCESS);
1219
0
}
1220
1221
/*
1222
 * Prepare private key download, and initialize a prkdf entry
1223
 */
1224
static int
1225
sc_pkcs15init_init_prkdf(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
1226
    struct sc_pkcs15init_prkeyargs *keyargs, struct sc_pkcs15_prkey *key, int keybits,
1227
    struct sc_pkcs15_object **res_obj)
1228
5.87k
{
1229
5.87k
  struct sc_context *ctx = p15card->card->ctx;
1230
5.87k
  struct sc_pkcs15_prkey_info *key_info = NULL;
1231
5.87k
  struct sc_pkcs15_keyinfo_gostparams *keyinfo_gostparams;
1232
5.87k
  struct sc_pkcs15_object *object = NULL;
1233
5.87k
  const char  *label;
1234
5.87k
  unsigned int  usage;
1235
5.87k
  int   r = 0, key_type;
1236
5.87k
  struct sc_ec_parameters *new_ecparams = NULL;
1237
1238
5.87k
  LOG_FUNC_CALLED(ctx);
1239
5.87k
  if (!res_obj || !keybits) {
1240
0
    r = SC_ERROR_INVALID_ARGUMENTS;
1241
0
    LOG_TEST_GOTO_ERR(ctx, r, "Initialize PrKDF entry failed");
1242
0
  }
1243
1244
5.87k
  *res_obj = NULL;
1245
1246
5.87k
  if ((usage = keyargs->usage) == 0) {
1247
5.87k
    usage = SC_PKCS15_PRKEY_USAGE_SIGN;
1248
5.87k
    if (keyargs->x509_usage)
1249
0
      usage = sc_pkcs15init_map_usage(keyargs->x509_usage, 1);
1250
5.87k
  }
1251
1252
5.87k
  if ((label = keyargs->label) == NULL)
1253
5.87k
    label = DEFAULT_PRIVATE_KEY_LABEL;
1254
1255
  /* Create the prkey object now.
1256
   * If we find out below that we're better off reusing an
1257
   * existing object, we'll ditch this one */
1258
5.87k
  key_type = key_pkcs15_algo(p15card, key->algorithm);
1259
5.87k
  r = key_type;
1260
5.87k
  LOG_TEST_GOTO_ERR(ctx, r, "Unsupported key type");
1261
1262
5.87k
  object = sc_pkcs15init_new_object(key_type, label, &keyargs->auth_id, NULL);
1263
5.87k
  if (object == NULL) {
1264
0
    r = SC_ERROR_OUT_OF_MEMORY;
1265
0
    LOG_TEST_GOTO_ERR(ctx, r, "Cannot allocate new PrKey object");
1266
0
  }
1267
1268
5.87k
  key_info = (struct sc_pkcs15_prkey_info *) object->data;
1269
5.87k
  key_info->usage = usage;
1270
5.87k
  key_info->native = 1;
1271
5.87k
  key_info->key_reference = 0;
1272
5.87k
  key_info->modulus_length = keybits;
1273
5.87k
  key_info->access_flags = keyargs->access_flags;
1274
5.87k
  object->user_consent = keyargs->user_consent;
1275
  /* Path is selected below */
1276
1277
5.87k
  if (keyargs->access_flags & SC_PKCS15_PRKEY_ACCESS_EXTRACTABLE) {
1278
0
    key_info->access_flags &= ~SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE;
1279
0
  }
1280
1281
  /* Select a Key ID if the user didn't specify one,
1282
   * otherwise make sure it's compatible with our intended use */
1283
5.87k
  r = select_id(p15card, SC_PKCS15_TYPE_PRKEY, &keyargs->id);
1284
5.87k
  LOG_TEST_GOTO_ERR(ctx, r, "Cannot select ID for PrKey object");
1285
1286
5.87k
  key_info->id = keyargs->id;
1287
1288
5.87k
  if (key->algorithm == SC_ALGORITHM_GOSTR3410) {
1289
0
    key_info->params.len = sizeof(*keyinfo_gostparams);
1290
    /* FIXME: malloc() call in pkcs15init, but free() call
1291
     * in libopensc (sc_pkcs15_free_prkey_info) */
1292
0
    key_info->params.data = malloc(key_info->params.len);
1293
0
    if (!key_info->params.data) {
1294
0
      r = SC_ERROR_OUT_OF_MEMORY;
1295
0
      LOG_TEST_GOTO_ERR(ctx, r, "Cannot allocate memory for GOST parameters");
1296
0
    }
1297
0
    keyinfo_gostparams = key_info->params.data;
1298
0
    keyinfo_gostparams->gostr3410 = keyargs->params.gost.gostr3410;
1299
0
    keyinfo_gostparams->gostr3411 = keyargs->params.gost.gostr3411;
1300
0
    keyinfo_gostparams->gost28147 = keyargs->params.gost.gost28147;
1301
5.87k
  } else if (key->algorithm == SC_ALGORITHM_EC ||
1302
4.54k
      key->algorithm == SC_ALGORITHM_EDDSA ||
1303
4.54k
      key->algorithm == SC_ALGORITHM_XEDDSA) {
1304
    /* keyargs->key.u.ec.params.der.value is allocated in keyargs, which is on stack */
1305
1.33k
    struct sc_ec_parameters *ecparams = &keyargs->key.u.ec.params;
1306
1307
1.33k
    new_ecparams = calloc(1, sizeof(struct sc_ec_parameters));
1308
1.33k
    if (!new_ecparams) {
1309
0
      r = SC_ERROR_OUT_OF_MEMORY;
1310
0
      LOG_TEST_GOTO_ERR(ctx, r, "Cannot allocate memory for EC parameters");
1311
0
    }
1312
1.33k
    r = sc_copy_ec_params(new_ecparams, &keyargs->key.u.ec.params);
1313
1.33k
    LOG_TEST_GOTO_ERR(ctx, r, "Cannot copy EC parameters");
1314
1315
1.33k
    key_info->params.data = new_ecparams;
1316
1.33k
    key_info->params.free_params = sc_pkcs15init_free_ec_params;
1317
1.33k
    key_info->field_length = ecparams->field_length;
1318
1.33k
    key_info->modulus_length = 0;
1319
1.33k
  }
1320
1321
5.87k
  r = select_object_path(p15card, profile, object, &key_info->path);
1322
5.87k
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to select private key object path");
1323
1324
  /* See if we need to select a key reference for this object */
1325
5.68k
  if (profile->ops->select_key_reference) {
1326
2.83k
    while (1) {
1327
2.83k
      sc_log(ctx, "Look for usable key reference starting from %i", key_info->key_reference);
1328
2.83k
      r = profile->ops->select_key_reference(profile, p15card, key_info);
1329
2.83k
      LOG_TEST_GOTO_ERR(ctx, r, "Failed to select card specific key reference");
1330
1331
2.33k
      r = sc_pkcs15_find_prkey_by_reference(p15card, &key_info->path, key_info->key_reference, NULL);
1332
2.33k
      if (r == SC_ERROR_OBJECT_NOT_FOUND)   {
1333
2.32k
        sc_log(ctx, "Will use key reference %i", key_info->key_reference);
1334
2.32k
        break;
1335
2.32k
      }
1336
1337
4
      if (r != 0) {
1338
        /* Other error trying to retrieve pin obj */
1339
0
        r = SC_ERROR_TOO_MANY_OBJECTS;
1340
0
        LOG_TEST_GOTO_ERR(ctx, r, "Failed to select key reference");
1341
0
      }
1342
1343
4
      key_info->key_reference++;
1344
4
    }
1345
2.83k
  }
1346
1347
5.17k
  *res_obj = object;
1348
5.17k
  object = NULL;
1349
5.17k
  new_ecparams = NULL;
1350
5.17k
  r = SC_SUCCESS;
1351
1352
5.87k
err:
1353
5.87k
  if (new_ecparams) {
1354
127
    sc_clear_ec_params(new_ecparams);
1355
127
    free(new_ecparams);
1356
127
    key_info->params.data = NULL;
1357
127
  }
1358
5.87k
  sc_pkcs15init_free_object(object);
1359
5.87k
  LOG_FUNC_RETURN(ctx, r);
1360
5.87k
}
1361
1362
/*
1363
 * Prepare secret key download, and initialize a skdf entry
1364
 */
1365
static int
1366
sc_pkcs15init_init_skdf(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
1367
    struct sc_pkcs15init_skeyargs *keyargs, struct sc_pkcs15_object **res_obj)
1368
16.7k
{
1369
16.7k
  struct sc_context *ctx = p15card->card->ctx;
1370
16.7k
  struct sc_pkcs15_skey_info *key_info;
1371
16.7k
  struct sc_pkcs15_object *object = NULL;
1372
16.7k
  const char  *label;
1373
16.7k
  unsigned int  usage;
1374
16.7k
  unsigned long keybits = keyargs->value_len;
1375
16.7k
  int   r = 0, key_type;
1376
1377
16.7k
  LOG_FUNC_CALLED(ctx);
1378
16.7k
  if (!res_obj || !keybits) {
1379
0
    r = SC_ERROR_INVALID_ARGUMENTS;
1380
0
    LOG_TEST_GOTO_ERR(ctx, r, "Initialize SKDF entry failed");
1381
0
  }
1382
1383
16.7k
  *res_obj = NULL;
1384
1385
16.7k
  if ((usage = keyargs->usage) == 0) {
1386
0
    usage = SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_DECRYPT;
1387
0
  }
1388
1389
16.7k
  if ((label = keyargs->label) == NULL)
1390
16.7k
    label = DEFAULT_SECRET_KEY_LABEL;
1391
1392
  /* Create the skey object now.
1393
   * If we find out below that we're better off reusing an
1394
   * existing object, we'll ditch this one */
1395
16.7k
  key_type = key_pkcs15_algo(p15card, keyargs->algorithm);
1396
16.7k
  r = key_type;
1397
16.7k
  LOG_TEST_GOTO_ERR(ctx, r, "Unsupported key type");
1398
1399
16.7k
  object = sc_pkcs15init_new_object(key_type, label, &keyargs->auth_id, NULL);
1400
16.7k
  if (object == NULL) {
1401
0
    r = SC_ERROR_OUT_OF_MEMORY;
1402
0
    LOG_TEST_GOTO_ERR(ctx, r, "Cannot allocate new SKey object");
1403
0
  }
1404
1405
16.7k
  key_info = (struct sc_pkcs15_skey_info *) object->data;
1406
16.7k
  key_info->usage = usage;
1407
16.7k
  key_info->native = 1;
1408
16.7k
  key_info->key_reference = 0;
1409
16.7k
  switch (keyargs->algorithm) {
1410
5.59k
  case SC_ALGORITHM_DES:
1411
5.59k
    key_info->key_type = CKK_DES;
1412
5.59k
    break;
1413
5.59k
  case SC_ALGORITHM_3DES:
1414
5.59k
    key_info->key_type = CKK_DES3;
1415
5.59k
    break;
1416
5.59k
  case SC_ALGORITHM_AES:
1417
5.59k
    key_info->key_type = CKK_AES;
1418
5.59k
    break;
1419
0
  default:
1420
0
    key_info->key_type = CKK_GENERIC_SECRET;
1421
0
    break;
1422
16.7k
  }
1423
16.7k
  key_info->value_len = keybits;
1424
16.7k
  key_info->access_flags = keyargs->access_flags;
1425
  /* Path is selected below */
1426
1427
16.7k
  if (keyargs->access_flags & SC_PKCS15_PRKEY_ACCESS_EXTRACTABLE) {
1428
16.7k
    key_info->access_flags &= ~SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE;
1429
16.7k
  }
1430
1431
16.7k
  if (keyargs->session_object > 0)
1432
0
      object->session_object = 1;
1433
1434
16.7k
  object->user_consent = keyargs->user_consent;
1435
1436
  /* Select a Key ID if the user didn't specify one,
1437
   * otherwise make sure it's compatible with our intended use */
1438
16.7k
  r = select_id(p15card, SC_PKCS15_TYPE_SKEY, &keyargs->id);
1439
16.7k
  LOG_TEST_GOTO_ERR(ctx, r, "Cannot select ID for SKey object");
1440
1441
16.7k
  key_info->id = keyargs->id;
1442
1443
16.7k
  r = select_object_path(p15card, profile, object, &key_info->path);
1444
16.7k
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to select secret key object path");
1445
1446
  /* See if we need to select a key reference for this object */
1447
16.3k
  if (profile->ops->select_key_reference) {
1448
8.22k
    r = SC_ERROR_NOT_SUPPORTED;
1449
8.22k
    LOG_TEST_GOTO_ERR(ctx, r, "SKey keyreference selection not supported");
1450
8.22k
  }
1451
1452
8.11k
  *res_obj = object;
1453
8.11k
  object = NULL;
1454
8.11k
  r = SC_SUCCESS;
1455
1456
16.7k
err:
1457
16.7k
  sc_pkcs15init_free_object(object);
1458
16.7k
  LOG_FUNC_RETURN(ctx, r);
1459
16.7k
}
1460
1461
static int
1462
_pkcd15init_set_aux_md_data(struct sc_pkcs15_card *p15card, struct sc_auxiliary_data **aux_data,
1463
    unsigned char *guid, size_t guid_len)
1464
5.17k
{
1465
5.17k
  struct sc_context *ctx = p15card->card->ctx;
1466
5.17k
  unsigned char flags = SC_MD_CONTAINER_MAP_VALID_CONTAINER;
1467
5.17k
  char gd[SC_MD_MAX_CONTAINER_NAME_LEN + 1];
1468
5.17k
  int rv;
1469
1470
5.17k
  LOG_FUNC_CALLED(ctx);
1471
1472
5.17k
  if(!guid || !guid_len)
1473
5.17k
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
1474
1475
0
  if (!aux_data)
1476
0
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
1477
1478
0
  if (guid_len > SC_MD_MAX_CONTAINER_NAME_LEN)
1479
0
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_DATA);
1480
1481
0
  memset(gd, 0, sizeof(gd));
1482
0
  memcpy(gd, guid, guid_len);
1483
1484
0
  if (*aux_data == NULL)   {
1485
0
    rv = sc_aux_data_allocate(ctx, aux_data, NULL);
1486
0
    LOG_TEST_RET(ctx, rv, "Failed to allocate aux data");
1487
0
  }
1488
1489
0
  rv = sc_aux_data_set_md_guid(ctx, *aux_data, gd);
1490
0
  LOG_TEST_RET(ctx, rv, "Failed to set private key CMAP record GUID");
1491
1492
0
  if (sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_PRKEY, NULL, 0) == 0)
1493
0
    flags |= SC_MD_CONTAINER_MAP_DEFAULT_CONTAINER;
1494
1495
0
  rv = sc_aux_data_set_md_flags(ctx, *aux_data, flags);
1496
0
  LOG_TEST_RET(ctx, rv, "Failed to set private key CMAP record flags");
1497
1498
0
  LOG_FUNC_RETURN(ctx, SC_SUCCESS);
1499
0
}
1500
1501
/*
1502
 * Copy gost3410 parameters (e.g. from prkey to pubkey)
1503
 */
1504
static int
1505
sc_copy_gost_params(struct sc_pkcs15_gost_parameters *dst, struct sc_pkcs15_gost_parameters *src)
1506
0
{
1507
0
  if (!dst || !src)
1508
0
    return SC_ERROR_INVALID_ARGUMENTS;
1509
1510
0
  memcpy((dst->key).value, (src->key).value, sizeof((src->key).value));
1511
0
  memcpy((dst->hash).value, (src->hash).value, sizeof((src->hash).value));
1512
0
  memcpy((dst->cipher).value, (src->cipher).value, sizeof((src->cipher).value));
1513
1514
0
  return SC_SUCCESS;
1515
0
}
1516
1517
/*
1518
 * Generate a new private key
1519
 */
1520
int
1521
sc_pkcs15init_generate_key(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
1522
    struct sc_pkcs15init_keygen_args *keygen_args, unsigned int keybits,
1523
    struct sc_pkcs15_object **res_obj)
1524
11.1k
{
1525
11.1k
  struct sc_context *ctx = p15card->card->ctx;
1526
11.1k
  struct sc_pkcs15init_pubkeyargs pubkey_args;
1527
11.1k
  struct sc_pkcs15_object *object = NULL;
1528
11.1k
  struct sc_pkcs15_prkey_info *key_info = NULL;
1529
11.1k
  struct sc_pkcs15_pubkey *pubkey = NULL;
1530
11.1k
  int r, caller_supplied_id = 0;
1531
11.1k
  unsigned long algorithm = keygen_args->prkey_args.key.algorithm;
1532
1533
11.1k
  LOG_FUNC_CALLED(ctx);
1534
1535
11.1k
  memset(&pubkey_args, 0, sizeof(pubkey_args));
1536
1537
  /* check supported key size */
1538
11.1k
  r = check_keygen_params_consistency(p15card->card,
1539
11.1k
    algorithm, &keygen_args->prkey_args,
1540
11.1k
    &keybits);
1541
11.1k
  LOG_TEST_GOTO_ERR(ctx, r, "Invalid key size");
1542
1543
5.95k
  if (check_key_compatibility(p15card, algorithm,
1544
5.95k
      &keygen_args->prkey_args.key, keygen_args->prkey_args.x509_usage,
1545
5.95k
      keybits, SC_ALGORITHM_ONBOARD_KEY_GEN) != SC_SUCCESS) {
1546
78
    r = SC_ERROR_NOT_SUPPORTED;
1547
78
    LOG_TEST_GOTO_ERR(ctx, r, "Cannot generate key with the given parameters");
1548
78
  }
1549
1550
5.88k
  if (profile->ops->generate_key == NULL) {
1551
0
    r = SC_ERROR_NOT_SUPPORTED;
1552
0
    LOG_TEST_GOTO_ERR(ctx, r, "Key generation not supported");
1553
0
  }
1554
1555
5.88k
  if (keygen_args->prkey_args.id.len)   {
1556
1.17k
    caller_supplied_id = 1;
1557
1558
    /* Make sure that private key's ID is the unique inside the PKCS#15 application */
1559
1.17k
    r = sc_pkcs15_find_prkey_by_id(p15card, &keygen_args->prkey_args.id, NULL);
1560
1.17k
    if (!r) {
1561
3
      r = SC_ERROR_NON_UNIQUE_ID;
1562
3
      LOG_TEST_GOTO_ERR(ctx, r, "Non unique ID of the private key object");
1563
3
    }
1564
1.17k
    else if (r != SC_ERROR_OBJECT_NOT_FOUND) {
1565
0
      LOG_TEST_GOTO_ERR(ctx, r, "Find private key error");
1566
0
    }
1567
1.17k
  }
1568
1569
  /* Set up the PrKDF object */
1570
5.87k
  r = sc_pkcs15init_init_prkdf(p15card, profile, &keygen_args->prkey_args,
1571
5.87k
    &keygen_args->prkey_args.key, keybits, &object);
1572
5.87k
  LOG_TEST_GOTO_ERR(ctx, r, "Set up private key object error");
1573
1574
5.17k
  key_info = (struct sc_pkcs15_prkey_info *) object->data;
1575
1576
5.17k
  r = _pkcd15init_set_aux_md_data(p15card, &key_info->aux_data,
1577
5.17k
      keygen_args->prkey_args.guid, keygen_args->prkey_args.guid_len);
1578
5.17k
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to set aux MD data");
1579
1580
  /* Set up the PuKDF info. The public key will be filled in
1581
   * by the card driver's generate_key function called below.
1582
   * Auth.ID of the public key object is left empty. */
1583
5.17k
  pubkey_args.id = keygen_args->prkey_args.id;
1584
5.17k
  pubkey_args.label = keygen_args->pubkey_label ? keygen_args->pubkey_label : object->label;
1585
5.17k
  pubkey_args.usage = keygen_args->prkey_args.usage;
1586
5.17k
  pubkey_args.x509_usage = keygen_args->prkey_args.x509_usage;
1587
5.17k
  pubkey_args.key.algorithm = algorithm;
1588
1589
5.17k
  if (algorithm == SC_ALGORITHM_GOSTR3410)   {
1590
0
    pubkey_args.params.gost = keygen_args->prkey_args.params.gost;
1591
0
    r = sc_copy_gost_params(&(pubkey_args.key.u.gostr3410.params), &(keygen_args->prkey_args.key.u.gostr3410.params));
1592
0
    LOG_TEST_GOTO_ERR(ctx, r, "Cannot allocate GOST parameters");
1593
5.17k
  } else if (algorithm == SC_ALGORITHM_EC ||
1594
3.97k
      algorithm == SC_ALGORITHM_EDDSA ||
1595
3.97k
      algorithm == SC_ALGORITHM_XEDDSA) {
1596
1.20k
    r = sc_copy_ec_params(&pubkey_args.key.u.ec.params, &keygen_args->prkey_args.key.u.ec.params);
1597
1.20k
    LOG_TEST_GOTO_ERR(ctx, r, "Cannot allocate EC parameters");
1598
1.20k
  }
1599
1600
  /* Generate the private key on card */
1601
5.17k
  r = profile->ops->create_key(profile, p15card, object);
1602
5.17k
  LOG_TEST_GOTO_ERR(ctx, r, "Cannot generate key: create key failed");
1603
1604
2.69k
  r = profile->ops->generate_key(profile, p15card, object, &pubkey_args.key);
1605
2.69k
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to generate key");
1606
1607
  /* update PrKDF entry */
1608
63
  if (!caller_supplied_id)   {
1609
35
    struct sc_pkcs15_id iid;
1610
1611
    /* Caller not supplied ID, so,
1612
     * if intrinsic ID can be calculated -- overwrite the native one */
1613
35
    memset(&iid, 0, sizeof(iid));
1614
35
    r = sc_pkcs15init_select_intrinsic_id(p15card, profile, SC_PKCS15_TYPE_PUBKEY, &iid, &pubkey_args.key);
1615
35
    LOG_TEST_GOTO_ERR(ctx, r, "Select intrinsic ID error");
1616
1617
34
    if (iid.len)
1618
8
      key_info->id = iid;
1619
34
  }
1620
62
  pubkey = &pubkey_args.key;
1621
62
  if (!pubkey->alg_id)   {
1622
62
    pubkey->alg_id = calloc(1, sizeof(struct sc_algorithm_id));
1623
62
    if (!pubkey->alg_id) {
1624
0
      r = SC_ERROR_OUT_OF_MEMORY;
1625
0
      LOG_TEST_GOTO_ERR(ctx, r, "Can not allocate memory for algorithm id");
1626
0
    }
1627
1628
62
    sc_init_oid(&pubkey->alg_id->oid);
1629
62
    pubkey->alg_id->algorithm = pubkey->algorithm;
1630
62
  }
1631
1632
62
  pubkey_args.id = key_info->id;
1633
62
  r = sc_pkcs15_encode_pubkey(ctx, pubkey, &object->content.value, &object->content.len);
1634
62
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to encode public key");
1635
1636
62
  r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_PRKDF, object);
1637
62
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to add generated private key object");
1638
1639
29
  if (!r && profile->ops->emu_store_data)   {
1640
2
    r = profile->ops->emu_store_data(p15card, profile, object, NULL, NULL);
1641
2
    if (r == SC_ERROR_NOT_IMPLEMENTED)
1642
0
      r = SC_SUCCESS;
1643
2
    if (r < 0)
1644
0
      sc_pkcs15_remove_object(p15card, object);
1645
2
    LOG_TEST_GOTO_ERR(ctx, r, "Card specific 'store data' failed");
1646
2
  }
1647
1648
29
  r = sc_pkcs15init_store_public_key(p15card, profile, &pubkey_args, NULL);
1649
29
  if (r < 0)
1650
19
    sc_pkcs15_remove_object(p15card, object);
1651
29
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to store public key");
1652
1653
10
  if (res_obj)
1654
0
    *res_obj = object;
1655
10
  object = NULL;
1656
1657
10
  profile->dirty = 1;
1658
1659
11.1k
err:
1660
11.1k
  sc_pkcs15_free_object(object);
1661
11.1k
  sc_pkcs15_erase_pubkey(&pubkey_args.key);
1662
11.1k
  LOG_FUNC_RETURN(ctx, r);
1663
11.1k
}
1664
1665
/*
1666
 * Generate a new secret key
1667
 */
1668
int
1669
sc_pkcs15init_generate_secret_key(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
1670
    struct sc_pkcs15init_skeyargs *skey_args, struct sc_pkcs15_object **res_obj)
1671
16.7k
{
1672
16.7k
  struct sc_context *ctx = p15card->card->ctx;
1673
16.7k
  struct sc_pkcs15_object *object = NULL;
1674
16.7k
  unsigned int keybits = (unsigned int)skey_args->value_len;
1675
16.7k
  int r;
1676
1677
16.7k
  LOG_FUNC_CALLED(ctx);
1678
  /* check supported key size */
1679
16.7k
  r = check_keygen_params_consistency(p15card->card, skey_args->algorithm, NULL, &keybits);
1680
16.7k
  LOG_TEST_RET(ctx, r, "Invalid key size");
1681
1682
699
  if (check_key_compatibility(p15card, skey_args->algorithm, NULL, 0,
1683
699
      keybits, SC_ALGORITHM_ONBOARD_KEY_GEN) != SC_SUCCESS)
1684
699
    LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Cannot generate key with the given parameters");
1685
1686
0
  if (profile->ops->generate_key == NULL)
1687
0
    LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Key generation not supported");
1688
1689
0
  if (skey_args->id.len)   {
1690
    /* Make sure that secret key's ID is the unique inside the PKCS#15 application */
1691
0
    r = sc_pkcs15_find_skey_by_id(p15card, &skey_args->id, NULL);
1692
0
    if (!r)
1693
0
      LOG_TEST_RET(ctx, SC_ERROR_NON_UNIQUE_ID, "Non unique ID of the private key object");
1694
0
    else if (r != SC_ERROR_OBJECT_NOT_FOUND)
1695
0
      LOG_TEST_RET(ctx, r, "Find private key error");
1696
0
  }
1697
1698
  /* Set up the SKDF object */
1699
0
  r = sc_pkcs15init_init_skdf(p15card, profile, skey_args, &object);
1700
0
  LOG_TEST_GOTO_ERR(ctx, r, "Set up secret key object error");
1701
1702
  /* Generate the secret key on card */
1703
0
  r = profile->ops->create_key(profile, p15card, object);
1704
0
  LOG_TEST_GOTO_ERR(ctx, r, "Cannot generate key: create key failed");
1705
1706
0
  r = profile->ops->generate_key(profile, p15card, object, NULL);
1707
0
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to generate key");
1708
1709
0
  r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_SKDF, object);
1710
0
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to add generated secret key object");
1711
1712
0
  if (!r && profile->ops->emu_store_data)   {
1713
0
    r = profile->ops->emu_store_data(p15card, profile, object, NULL, NULL);
1714
0
    if (r == SC_ERROR_NOT_IMPLEMENTED)
1715
0
      r = SC_SUCCESS;
1716
0
    LOG_TEST_GOTO_ERR(ctx, r, "Card specific 'store data' failed");
1717
0
  }
1718
1719
0
  if (res_obj)
1720
0
    *res_obj = object;
1721
0
  object = NULL;
1722
1723
0
  profile->dirty = 1;
1724
1725
0
err:
1726
0
  sc_pkcs15_free_object(object);
1727
0
  LOG_FUNC_RETURN(ctx, r);
1728
0
}
1729
1730
1731
/*
1732
 * Store private key
1733
 */
1734
int
1735
sc_pkcs15init_store_private_key(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
1736
    struct sc_pkcs15init_prkeyargs *keyargs, struct sc_pkcs15_object **res_obj)
1737
0
{
1738
0
  struct sc_context *ctx = p15card->card->ctx;
1739
0
  struct sc_pkcs15_object *object = NULL;
1740
0
  struct sc_pkcs15_prkey key;
1741
0
  struct sc_pkcs15_prkey_info *key_info = NULL;
1742
0
  int keybits, r = 0;
1743
1744
0
  LOG_FUNC_CALLED(ctx);
1745
1746
0
  if (keyargs->key.algorithm == SC_ALGORITHM_EC) {
1747
    /* Do this before copying the key below, otherwise we would leak the memory
1748
     * if some fixing would happen in check_key_compatibility() or elsewhere.
1749
     * This should have been done in the sc_pkcs15_convert_prkey()
1750
     * or earlier, but the context is not available at that point */
1751
0
    r = sc_pkcs15_fix_ec_parameters(ctx, &keyargs->key.u.ec.params);
1752
0
    LOG_TEST_RET(ctx, r, "failed to fix EC parameters");
1753
0
  }
1754
  /* Create a copy of the key first */
1755
0
  key = keyargs->key;
1756
1757
0
  r = prkey_fixup(p15card, &key);
1758
0
  LOG_TEST_RET(ctx, r, "Private key data sanity check failed");
1759
1760
0
  keybits = prkey_bits(p15card, &key);
1761
0
  LOG_TEST_RET(ctx, keybits, "Invalid private key size");
1762
1763
  /* Now check whether the card is able to handle this key
1764
   * this already modifies the local shallow copy of the key structure! */
1765
0
  if (check_key_compatibility(p15card, key.algorithm, &key, keyargs->x509_usage, keybits, 0) != SC_SUCCESS) {
1766
    /* Make sure the caller explicitly tells us to store
1767
     * the key as extractable. */
1768
0
    if (!(keyargs->access_flags & SC_PKCS15_PRKEY_ACCESS_EXTRACTABLE))
1769
0
      LOG_TEST_RET(ctx, SC_ERROR_INCOMPATIBLE_KEY, "Card does not support this key for crypto. Cannot store it as non extractable.");
1770
0
  }
1771
1772
  /* Select a intrinsic Key ID if user didn't specify one */
1773
0
  r = sc_pkcs15init_select_intrinsic_id(p15card, profile, SC_PKCS15_TYPE_PRKEY,
1774
0
      &keyargs->id, &keyargs->key);
1775
0
  LOG_TEST_RET(ctx, r, "Get intrinsic ID error");
1776
1777
  /* Make sure that private key's ID is the unique inside the PKCS#15 application */
1778
0
  r = sc_pkcs15_find_prkey_by_id(p15card, &keyargs->id, NULL);
1779
0
  if (!r)
1780
0
    LOG_TEST_RET(ctx, SC_ERROR_NON_UNIQUE_ID, "Non unique ID of the private key object");
1781
0
  else if (r != SC_ERROR_OBJECT_NOT_FOUND)
1782
0
    LOG_TEST_RET(ctx, r, "Find private key error");
1783
1784
  /* Set up the PrKDF object */
1785
0
  r = sc_pkcs15init_init_prkdf(p15card, profile, keyargs, &key, keybits, &object);
1786
0
  LOG_TEST_RET(ctx, r, "Failed to initialize private key object");
1787
1788
0
  r = sc_pkcs15init_encode_prvkey_content(p15card, &key, object);
1789
0
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to encode public key");
1790
1791
0
  key_info = (struct sc_pkcs15_prkey_info *) object->data;
1792
0
  r = _pkcd15init_set_aux_md_data(p15card, &key_info->aux_data, keyargs->guid, keyargs->guid_len);
1793
0
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to set aux MD data");
1794
1795
0
  if (profile->ops->create_key)
1796
0
    r = profile->ops->create_key(profile, p15card, object);
1797
0
  LOG_TEST_GOTO_ERR(ctx, r, "Card specific 'create key' failed");
1798
1799
0
  if (profile->ops->store_key)
1800
0
    r = profile->ops->store_key(profile, p15card, object, &key);
1801
0
  LOG_TEST_GOTO_ERR(ctx, r, "Card specific 'store key' failed");
1802
1803
0
  sc_pkcs15_free_object_content(object);
1804
0
  r = sc_pkcs15init_encode_prvkey_content(p15card, &key, object);
1805
0
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to encode public key");
1806
1807
  /* Now update the PrKDF */
1808
0
  r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_PRKDF, object);
1809
0
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to add new private key PKCS#15 object");
1810
1811
0
  if (!r && profile->ops->emu_store_data)   {
1812
0
    r = profile->ops->emu_store_data(p15card, profile, object, NULL, NULL);
1813
0
    if (r == SC_ERROR_NOT_IMPLEMENTED)
1814
0
      r = SC_SUCCESS;
1815
0
    LOG_TEST_GOTO_ERR(ctx, r, "Card specific 'store data' failed");
1816
0
  }
1817
1818
0
  if (r >= 0 && res_obj)
1819
0
    *res_obj = object;
1820
0
  object = NULL;
1821
1822
0
  profile->dirty = 1;
1823
1824
0
err:
1825
0
  sc_pkcs15_free_object(object);
1826
0
  LOG_FUNC_RETURN(ctx, r);
1827
0
}
1828
1829
1830
/*
1831
 * Store a public key
1832
 */
1833
int
1834
sc_pkcs15init_store_public_key(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
1835
    struct sc_pkcs15init_pubkeyargs *keyargs, struct sc_pkcs15_object **res_obj)
1836
29
{
1837
29
  struct sc_context *ctx = p15card->card->ctx;
1838
29
  struct sc_pkcs15_object *object = NULL;
1839
29
  struct sc_pkcs15_pubkey_info *key_info;
1840
29
  struct sc_pkcs15_keyinfo_gostparams *keyinfo_gostparams;
1841
29
  struct sc_pkcs15_pubkey key;
1842
29
  struct sc_path  *path;
1843
29
  const char  *label;
1844
29
  unsigned int  type = 0;
1845
29
  unsigned int usage;
1846
29
  size_t keybits;
1847
29
  int   r;
1848
1849
29
  LOG_FUNC_CALLED(ctx);
1850
29
  if (!keyargs)
1851
29
    LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Store public key aborted");
1852
1853
  /* Create shallow a copy of the key first */
1854
29
  key = keyargs->key;
1855
1856
  /* Copy algorithm id structure */
1857
29
  if (keyargs->key.alg_id) {
1858
29
    key.alg_id = calloc(1, sizeof(struct sc_algorithm_id));
1859
29
    if (!key.alg_id)
1860
29
      LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Can not allocate memory for algorithm id");
1861
1862
29
    key.alg_id->algorithm = keyargs->key.alg_id->algorithm;
1863
29
    memcpy(&key.alg_id->oid, &keyargs->key.alg_id->oid, sizeof(struct sc_object_id));
1864
29
  }
1865
1866
  /* Copy algorithm related parameters */
1867
29
  switch (key.algorithm) {
1868
15
  case SC_ALGORITHM_RSA:
1869
15
    key.u.rsa.modulus.data = NULL;
1870
15
    key.u.rsa.exponent.data = NULL;
1871
    // copy RSA params
1872
15
    if (!(key.u.rsa.modulus.data = malloc(keyargs->key.u.rsa.modulus.len))) {
1873
0
      r = SC_ERROR_OUT_OF_MEMORY;
1874
0
      LOG_TEST_GOTO_ERR(ctx, r, "Failed to copy RSA public key parameters");
1875
0
    }
1876
15
    memcpy(key.u.rsa.modulus.data, keyargs->key.u.rsa.modulus.data, keyargs->key.u.rsa.modulus.len);
1877
15
    if (!(key.u.rsa.exponent.data = malloc(keyargs->key.u.rsa.exponent.len))) {
1878
0
      r = SC_ERROR_OUT_OF_MEMORY;
1879
0
      LOG_TEST_GOTO_ERR(ctx, r, "Failed to copy RSA public key parameters");
1880
0
    }
1881
15
    memcpy(key.u.rsa.exponent.data, keyargs->key.u.rsa.exponent.data, keyargs->key.u.rsa.exponent.len);
1882
15
    keybits = sc_pkcs15init_keybits(&key.u.rsa.modulus);
1883
15
    type = SC_PKCS15_TYPE_PUBKEY_RSA;
1884
15
    break;
1885
0
  case SC_ALGORITHM_GOSTR3410:
1886
0
    key.u.gostr3410.xy.data = NULL;
1887
    // copy GOSTR params
1888
0
    if (!(key.u.gostr3410.xy.data = malloc(keyargs->key.u.gostr3410.xy.len))) {
1889
0
      r = SC_ERROR_OUT_OF_MEMORY;
1890
0
      LOG_TEST_GOTO_ERR(ctx, r, "Failed to copy GOSTR public key parameters");
1891
0
    }
1892
0
    memcpy(key.u.gostr3410.xy.data, keyargs->key.u.gostr3410.xy.data, keyargs->key.u.gostr3410.xy.len);
1893
0
    keybits = SC_PKCS15_GOSTR3410_KEYSIZE;
1894
0
    type = SC_PKCS15_TYPE_PUBKEY_GOSTR3410;
1895
0
    break;
1896
14
  case SC_ALGORITHM_EC:
1897
14
  case SC_ALGORITHM_EDDSA:
1898
14
  case SC_ALGORITHM_XEDDSA:
1899
1900
14
    r = sc_copy_ec_params(&key.u.ec.params, &keyargs->key.u.ec.params);
1901
14
    LOG_TEST_GOTO_ERR(ctx, r, "Failed to copy EC public key parameters");
1902
14
    r = sc_pkcs15_fix_ec_parameters(ctx, &key.u.ec.params);
1903
14
    LOG_TEST_GOTO_ERR(ctx, r, "Failed to fix EC public key parameters");
1904
1905
14
    if (key.algorithm == SC_ALGORITHM_EC)
1906
14
      type = SC_PKCS15_TYPE_PUBKEY_EC;
1907
0
    else if (key.algorithm == SC_ALGORITHM_EDDSA)
1908
0
      type = SC_PKCS15_TYPE_PUBKEY_EDDSA;
1909
0
    else if (key.algorithm == SC_ALGORITHM_XEDDSA)
1910
0
      type = SC_PKCS15_TYPE_PUBKEY_XEDDSA;
1911
1912
14
    keybits = key.u.ec.params.field_length;
1913
14
    break;
1914
0
  default:
1915
0
    r = SC_ERROR_NOT_SUPPORTED;
1916
0
    LOG_TEST_GOTO_ERR(ctx, r, "Unsupported key algorithm.");
1917
29
  }
1918
1919
29
  if ((usage = keyargs->usage) == 0) {
1920
29
    if (type == SC_PKCS15_TYPE_PUBKEY_XEDDSA) {
1921
0
      sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Setting default usage to derive");
1922
0
      usage = SC_PKCS15_PRKEY_USAGE_DERIVE;
1923
29
    } else {
1924
29
      sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Setting default usage to verify");
1925
29
      usage = SC_PKCS15_PRKEY_USAGE_VERIFY;
1926
29
    }
1927
29
    if (keyargs->x509_usage) {
1928
0
      sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Setting usage from keyargs->x509_usage");
1929
0
      usage = sc_pkcs15init_map_usage(keyargs->x509_usage, 0);
1930
0
    }
1931
29
  }
1932
29
  sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Usage: 0x%X", usage);
1933
1934
29
  label = keyargs->label;
1935
29
  if (!label)
1936
0
    label = "Public Key";
1937
1938
  /* Set up the pkcs15 object. */
1939
29
  object = sc_pkcs15init_new_object(type, label, &keyargs->auth_id, NULL);
1940
29
  if (object == NULL) {
1941
0
    r = SC_ERROR_OUT_OF_MEMORY;
1942
0
    LOG_TEST_GOTO_ERR(ctx, r, "Cannot allocate new public key object");
1943
0
  }
1944
1945
29
  key_info = (struct sc_pkcs15_pubkey_info *) object->data;
1946
29
  key_info->usage = usage;
1947
29
  key_info->id = keyargs->id;
1948
1949
29
  if (key.algorithm == SC_ALGORITHM_RSA) {
1950
15
    key_info->modulus_length = keybits;
1951
15
  } else if (key.algorithm == SC_ALGORITHM_GOSTR3410) {
1952
0
    key_info->params.len = sizeof(*keyinfo_gostparams);
1953
    /* FIXME: malloc() call in pkcs15init, but free() call
1954
     * in libopensc (sc_pkcs15_free_prkey_info) */
1955
0
    key_info->params.data = malloc(key_info->params.len);
1956
0
    if (!key_info->params.data) {
1957
0
      r = SC_ERROR_OUT_OF_MEMORY;
1958
0
      LOG_TEST_GOTO_ERR(ctx, r, "Cannot allocate GOST params");
1959
0
    }
1960
0
    keyinfo_gostparams = key_info->params.data;
1961
0
    keyinfo_gostparams->gostr3410 = keyargs->params.gost.gostr3410;
1962
0
    keyinfo_gostparams->gostr3411 = keyargs->params.gost.gostr3411;
1963
0
    keyinfo_gostparams->gost28147 = keyargs->params.gost.gost28147;
1964
14
  } else if (key.algorithm == SC_ALGORITHM_EC ||
1965
0
      key.algorithm == SC_ALGORITHM_EDDSA ||
1966
14
      key.algorithm == SC_ALGORITHM_XEDDSA) {
1967
14
    key_info->field_length = keybits;
1968
    /* only SC_ALGORITHM_EC has ec_params with the EC curveName OID
1969
     * that becomes part of the SPKI algo params.
1970
     * EDDSA and XEDDSA ec_params have the OID of the EDDSA or XEDDSA
1971
     * which is used as the alg OID. But we still copy here
1972
     * as the asn1 routines will do the right thing based on key.algorithm.
1973
     */
1974
14
    if (key.u.ec.params.der.value) {
1975
14
      key_info->params.data = malloc(key.u.ec.params.der.len);
1976
14
      if (!key_info->params.data) {
1977
0
        r = SC_ERROR_OUT_OF_MEMORY;
1978
0
        LOG_TEST_GOTO_ERR(ctx, r, "Cannot allocate EC params");
1979
0
      }
1980
14
      key_info->params.len = key.u.ec.params.der.len;
1981
14
      memcpy(key_info->params.data, key.u.ec.params.der.value, key.u.ec.params.der.len);
1982
14
    }
1983
14
    if (keyargs->key.u.ec.ecpointQ.value) {
1984
14
      key.u.ec.ecpointQ.value = malloc(keyargs->key.u.ec.ecpointQ.len);
1985
14
      if (!key.u.ec.ecpointQ.value) {
1986
0
        r = SC_ERROR_OUT_OF_MEMORY;
1987
0
        LOG_TEST_GOTO_ERR(ctx, r, "Cannot allocate EC public key");
1988
0
      }
1989
14
      key.u.ec.ecpointQ.len = keyargs->key.u.ec.ecpointQ.len;
1990
14
      memcpy(key.u.ec.ecpointQ.value, keyargs->key.u.ec.ecpointQ.value, key.u.ec.ecpointQ.len);
1991
14
    }
1992
14
  }
1993
1994
  /* Select a intrinsic Key ID if the user didn't specify one */
1995
29
  r = sc_pkcs15init_select_intrinsic_id(p15card, profile, SC_PKCS15_TYPE_PUBKEY, &keyargs->id, &key);
1996
29
  LOG_TEST_GOTO_ERR(ctx, r, "Get intrinsic ID error");
1997
1998
  /* Select a Key ID if the user didn't specify one and there is no intrinsic ID,
1999
   * otherwise make sure it's unique */
2000
29
  r = select_id(p15card, SC_PKCS15_TYPE_PUBKEY, &keyargs->id);
2001
29
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to select public key object ID");
2002
2003
  /* Make sure that private key's ID is the unique inside the PKCS#15 application */
2004
29
  r = sc_pkcs15_find_pubkey_by_id(p15card, &keyargs->id, NULL);
2005
29
  if (!r) {
2006
0
    r = SC_ERROR_NON_UNIQUE_ID;
2007
0
    LOG_TEST_GOTO_ERR(ctx, r, "Non unique ID of the public key object");
2008
29
  } else if (r != SC_ERROR_OBJECT_NOT_FOUND)  {
2009
0
    LOG_TEST_GOTO_ERR(ctx, r, "Find public key error");
2010
0
  }
2011
2012
29
  key_info->id = keyargs->id;
2013
2014
  /* DER encode public key components */
2015
29
  r = sc_pkcs15_encode_pubkey(p15card->card->ctx, &key, &object->content.value, &object->content.len);
2016
29
  LOG_TEST_GOTO_ERR(ctx, r, "Encode public key error");
2017
2018
29
  r = sc_pkcs15_encode_pubkey(p15card->card->ctx, &key, &key_info->direct.raw.value, &key_info->direct.raw.len);
2019
29
  LOG_TEST_GOTO_ERR(ctx, r, "RAW encode public key error");
2020
2021
  /* EC key are encoded as SPKI to preserve domain parameter */
2022
29
  r = sc_pkcs15_encode_pubkey_as_spki(p15card->card->ctx, &key, &key_info->direct.spki.value, &key_info->direct.spki.len);
2023
29
  LOG_TEST_GOTO_ERR(ctx, r, "SPKI encode public key error");
2024
2025
  /* Now create key file and store key */
2026
29
  if (type == SC_PKCS15_TYPE_PUBKEY_EC ||
2027
15
      type == SC_PKCS15_TYPE_PUBKEY_EDDSA ||
2028
15
      type == SC_PKCS15_TYPE_PUBKEY_XEDDSA)
2029
14
    r = sc_pkcs15init_store_data(p15card, profile, object, &key_info->direct.spki, &key_info->path);
2030
15
  else
2031
15
    r = sc_pkcs15init_store_data(p15card, profile, object, &object->content, &key_info->path);
2032
2033
29
  path = &key_info->path;
2034
29
  if (path->count == 0) {
2035
6
    path->index = 0;
2036
6
    path->count = -1;
2037
6
  }
2038
2039
  /* Update the PuKDF */
2040
29
  if (r >= 0)
2041
16
    r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_PUKDF, object);
2042
29
  LOG_TEST_GOTO_ERR(ctx, r, "Add object error");
2043
2044
10
  if (r >= 0 && res_obj)
2045
0
    *res_obj = object;
2046
10
  object = NULL;
2047
2048
10
  profile->dirty = 1;
2049
2050
29
err:
2051
29
  sc_pkcs15_erase_pubkey(&key);
2052
29
  sc_pkcs15_free_object(object);
2053
29
  LOG_FUNC_RETURN(ctx, r);
2054
29
}
2055
2056
2057
/*
2058
 * Store secret key
2059
 */
2060
int
2061
sc_pkcs15init_store_secret_key(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
2062
    struct sc_pkcs15init_skeyargs *keyargs, struct sc_pkcs15_object **res_obj)
2063
16.7k
{
2064
16.7k
  struct sc_context *ctx = p15card->card->ctx;
2065
16.7k
  struct sc_pkcs15_object *object = NULL;
2066
16.7k
  int r = 0;
2067
2068
16.7k
  LOG_FUNC_CALLED(ctx);
2069
2070
  /* Now check whether the card is able to handle this key */
2071
16.7k
  if (check_key_compatibility(p15card, keyargs->algorithm, NULL, 0, keyargs->value_len, 0) != SC_SUCCESS) {
2072
    /* Make sure the caller explicitly tells us to store
2073
     * the key as extractable. */
2074
16.0k
    if (!(keyargs->access_flags & SC_PKCS15_PRKEY_ACCESS_EXTRACTABLE))
2075
16.0k
      LOG_TEST_RET(ctx, SC_ERROR_INCOMPATIBLE_KEY, "Card does not support this key for crypto. Cannot store it as non extractable.");
2076
16.0k
  }
2077
2078
16.7k
#ifdef ENABLE_OPENSSL
2079
16.7k
  if (!keyargs->id.len) {
2080
    /* Calculating intrinsic Key ID for secret key does not make
2081
     * sense - just generate random one */
2082
5.59k
    if (RAND_bytes(keyargs->id.value, 20) == 1)
2083
5.59k
      keyargs->id.len = 20;
2084
5.59k
  }
2085
16.7k
#endif
2086
2087
  /* Make sure that secret key's ID is the unique inside the PKCS#15 application */
2088
16.7k
  r = sc_pkcs15_find_skey_by_id(p15card, &keyargs->id, NULL);
2089
16.7k
  if (!r)
2090
16.7k
    LOG_TEST_RET(ctx, SC_ERROR_NON_UNIQUE_ID, "Non unique ID of the secret key object");
2091
16.7k
  else if (r != SC_ERROR_OBJECT_NOT_FOUND)
2092
0
    LOG_TEST_RET(ctx, r, "Find secret key error");
2093
2094
  /* Set up the SKDF object */
2095
16.7k
  r = sc_pkcs15init_init_skdf(p15card, profile, keyargs, &object);
2096
16.7k
  LOG_TEST_RET(ctx, r, "Failed to initialize secret key object");
2097
2098
8.11k
  if (profile->ops->create_key)
2099
8.11k
    r = profile->ops->create_key(profile, p15card, object);
2100
8.11k
  LOG_TEST_GOTO_ERR(ctx, r, "Card specific 'create key' failed");
2101
2102
  /* If no key data, only an empty EF is created.
2103
   * It can be used to receive an unwrapped key later. */
2104
2.00k
  if (keyargs->key.data_len > 0) {
2105
2.00k
    if (profile->ops->store_key) {
2106
2.00k
      struct sc_pkcs15_prkey key;
2107
2.00k
      memset(&key, 0, sizeof(key));
2108
2.00k
      key.algorithm = keyargs->algorithm;
2109
2.00k
      key.u.secret = keyargs->key;
2110
2.00k
      r = profile->ops->store_key(profile, p15card, object, &key);
2111
2.00k
    }
2112
2.00k
  }
2113
2.00k
  LOG_TEST_GOTO_ERR(ctx, r, "Card specific 'store key' failed");
2114
2115
80
  sc_pkcs15_free_object_content(object);
2116
2117
  /* Now update the SKDF, unless it is a session object.
2118
     If we have an on card session object, we have created the actual key object on card.
2119
     The card handles removing it when the session is finished or during the next reset.
2120
     We will maintain the object in the P15 structure in memory for duration of the session,
2121
     but we don't want it to be written into SKDF. */
2122
80
  if (!object->session_object) {
2123
80
    r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_SKDF, object);
2124
80
    LOG_TEST_GOTO_ERR(ctx, r, "Failed to add new secret key PKCS#15 object");
2125
80
  }
2126
2127
5
  if (!r && profile->ops->emu_store_data && !object->session_object)   {
2128
0
    r = profile->ops->emu_store_data(p15card, profile, object, NULL, NULL);
2129
0
    if (r == SC_ERROR_NOT_IMPLEMENTED)
2130
0
      r = SC_SUCCESS;
2131
0
    LOG_TEST_GOTO_ERR(ctx, r, "Card specific 'store data' failed");
2132
0
  }
2133
2134
5
  if (r >= 0 && res_obj)
2135
0
    *res_obj = object;
2136
5
  object = NULL;
2137
2138
5
  profile->dirty = 1;
2139
2140
8.11k
err:
2141
8.11k
  sc_pkcs15_free_object(object);
2142
8.11k
  LOG_FUNC_RETURN(ctx, r);
2143
8.11k
}
2144
2145
/*
2146
 * Store a certificate
2147
 */
2148
int
2149
sc_pkcs15init_store_certificate(struct sc_pkcs15_card *p15card,
2150
    struct sc_profile *profile,
2151
    struct sc_pkcs15init_certargs *args,
2152
    struct sc_pkcs15_object **res_obj)
2153
0
{
2154
0
  struct sc_context *ctx = p15card->card->ctx;
2155
0
  struct sc_pkcs15_cert_info *cert_info = NULL;
2156
0
  struct sc_pkcs15_object *object = NULL;
2157
0
  struct sc_pkcs15_object *key_object = NULL;
2158
0
  struct sc_path existing_path;
2159
0
  const char *label = NULL;
2160
0
  int   r;
2161
2162
0
  LOG_FUNC_CALLED(ctx);
2163
2164
0
  memset(&existing_path, 0, sizeof(struct sc_path));
2165
2166
0
  label = args->label;
2167
0
  if (!label)
2168
0
    label = "Certificate";
2169
2170
0
  r = sc_pkcs15init_select_intrinsic_id(p15card, profile, SC_PKCS15_TYPE_CERT_X509,
2171
0
      &args->id, &args->der_encoded);
2172
0
  LOG_TEST_RET(ctx, r, "Get certificate 'intrinsic ID' error");
2173
0
  sc_log(ctx, "Cert(ID:%s) rv %i", sc_pkcs15_print_id(&args->id), r);
2174
2175
  /* Select an ID if the user didn't specify one, otherwise make sure it's unique */
2176
0
  r = select_id(p15card, SC_PKCS15_TYPE_CERT, &args->id);
2177
0
  if (r == SC_ERROR_NON_UNIQUE_ID && args->update)   {
2178
0
    struct sc_pkcs15_object *existing_obj = NULL;
2179
2180
0
    r = sc_pkcs15_find_object_by_id(p15card, SC_PKCS15_TYPE_CERT, &args->id, &existing_obj);
2181
0
    if (!r)   {
2182
0
      sc_log(ctx, "Found cert(ID:%s)", sc_pkcs15_print_id(&args->id));
2183
0
      existing_path = ((struct sc_pkcs15_cert_info *)existing_obj->data)->path;
2184
2185
0
      sc_pkcs15_remove_object(p15card, existing_obj);
2186
0
      sc_pkcs15_free_object(existing_obj);
2187
0
    }
2188
2189
0
    r = select_id(p15card, SC_PKCS15_TYPE_CERT, &args->id);
2190
0
  }
2191
0
  sc_log(ctx, "Select ID Cert(ID:%s) rv %i", sc_pkcs15_print_id(&args->id), r);
2192
0
  LOG_TEST_RET(ctx, r, "Select certificate ID error");
2193
2194
0
  object = sc_pkcs15init_new_object(SC_PKCS15_TYPE_CERT_X509, label, NULL, NULL);
2195
0
  if (object == NULL)
2196
0
    LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Failed to allocate certificate object");
2197
0
  cert_info = (struct sc_pkcs15_cert_info *) object->data;
2198
0
  cert_info->id = args->id;
2199
0
  cert_info->authority = args->authority;
2200
0
  sc_der_copy(&object->content, &args->der_encoded);
2201
0
  sc_der_copy(&cert_info->value, &args->der_encoded);
2202
2203
0
  if (existing_path.len)   {
2204
0
    sc_log(ctx, "Using existing path %s", sc_print_path(&existing_path));
2205
0
    cert_info->path = existing_path;
2206
0
  }
2207
2208
0
  sc_log(ctx, "Store cert(%.*s,ID:%s,der(%p,%"SC_FORMAT_LEN_SIZE_T"u))",
2209
0
         (int) sizeof object->label, object->label,
2210
0
         sc_pkcs15_print_id(&cert_info->id), args->der_encoded.value,
2211
0
         args->der_encoded.len);
2212
2213
0
  if (!profile->pkcs15.direct_certificates)
2214
0
    r = sc_pkcs15init_store_data(p15card, profile, object, &args->der_encoded, &cert_info->path);
2215
2216
  /* Now update the CDF */
2217
0
  if (r >= 0)   {
2218
0
    r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_CDF, object);
2219
    /* TODO: update private key PKCS#15 object with the certificate's attributes */
2220
0
  }
2221
2222
0
  if (r >= 0)   {
2223
0
    r = sc_pkcs15_prkey_attrs_from_cert(p15card, object, &key_object);
2224
0
    if (r)   {
2225
0
      r = 0;
2226
0
    }
2227
0
    else if (key_object) {
2228
0
      if (profile->ops->emu_update_any_df) {
2229
0
        r = profile->ops->emu_update_any_df(profile, p15card, SC_AC_OP_UPDATE, key_object);
2230
0
        if (r == SC_ERROR_NOT_SUPPORTED)
2231
0
          r = SC_SUCCESS;
2232
0
      }
2233
0
      else {
2234
0
        r = sc_pkcs15init_update_any_df(p15card, profile, key_object->df, 0);
2235
0
        sc_log(ctx, "update_any_df returned %i", r);
2236
0
      }
2237
0
    }
2238
0
  }
2239
2240
0
  if (r < 0)   {
2241
0
    sc_pkcs15_remove_object(p15card, object);
2242
0
    sc_pkcs15_free_object(object);
2243
0
  }
2244
0
  else if (res_obj)   {
2245
0
    *res_obj = object;
2246
0
  }
2247
2248
0
  profile->dirty = 1;
2249
2250
0
  LOG_FUNC_RETURN(ctx, r);
2251
0
}
2252
2253
2254
/*
2255
 * Store a data object
2256
 */
2257
int
2258
sc_pkcs15init_store_data_object(struct sc_pkcs15_card *p15card,
2259
    struct sc_profile *profile,
2260
    struct sc_pkcs15init_dataargs *args,
2261
    struct sc_pkcs15_object **res_obj)
2262
5.59k
{
2263
5.59k
  struct sc_context *ctx = p15card->card->ctx;
2264
5.59k
  struct sc_pkcs15_data_info *data_object_info;
2265
5.59k
  struct sc_pkcs15_object *object;
2266
5.59k
  struct sc_pkcs15_object *objs[32];
2267
5.59k
  const char  *label;
2268
5.59k
  int   r, i;
2269
5.59k
  unsigned int    tid = 0x01;
2270
2271
5.59k
  LOG_FUNC_CALLED(ctx);
2272
5.59k
  if (!profile)
2273
5.59k
    LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Missing profile");
2274
5.59k
  label = args->label;
2275
2276
5.59k
  if (!args->id.len) {
2277
    /* Select an ID if the user didn't specify one, otherwise
2278
     * make sure it's unique (even though data objects doesn't
2279
     * have a pkcs15 id we need one here to create a unique
2280
     * file id from the data file template */
2281
5.59k
    r = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_DATA_OBJECT, objs, 32);
2282
5.59k
    LOG_TEST_RET(ctx, r, "Get 'DATA' objects error");
2283
2284
5.61k
    for (i = 0; i < r; i++) {
2285
21
      unsigned char cid;
2286
21
      struct sc_pkcs15_data_info *cinfo = (struct sc_pkcs15_data_info *) objs[i]->data;
2287
21
      if (!cinfo->path.len)
2288
0
        continue;
2289
21
      cid = cinfo->path.value[cinfo->path.len - 1];
2290
21
      if (cid >= tid)
2291
15
        tid = cid + 1;
2292
21
    }
2293
5.59k
    if (tid > 0xff)
2294
      /* too many data objects ... */
2295
1
      return SC_ERROR_TOO_MANY_OBJECTS;
2296
5.59k
    args->id.len = 1;
2297
5.59k
    args->id.value[0] = tid;
2298
5.59k
  }
2299
0
  else   {
2300
    /* in case the user specifies an id it should be at most
2301
     * one byte long */
2302
0
    if (args->id.len > 1)
2303
0
      return SC_ERROR_INVALID_ARGUMENTS;
2304
0
  }
2305
2306
5.59k
  object = sc_pkcs15init_new_object(SC_PKCS15_TYPE_DATA_OBJECT, label, &args->auth_id, NULL);
2307
5.59k
  if (object == NULL)
2308
0
    return SC_ERROR_OUT_OF_MEMORY;
2309
2310
5.59k
  data_object_info = (struct sc_pkcs15_data_info *) object->data;
2311
5.59k
  if (args->app_label != NULL)
2312
5.59k
    strlcpy(data_object_info->app_label, args->app_label, sizeof(data_object_info->app_label));
2313
0
  else if (label != NULL)
2314
0
    strlcpy(data_object_info->app_label, label, sizeof(data_object_info->app_label));
2315
2316
5.59k
  data_object_info->app_oid = args->app_oid;
2317
5.59k
  sc_der_copy(&data_object_info->data, &args->der_encoded);
2318
2319
5.59k
  r = sc_pkcs15init_store_data(p15card, profile, object, &args->der_encoded, &data_object_info->path);
2320
5.59k
  LOG_TEST_GOTO_ERR(ctx, r, "Store 'DATA' object error");
2321
2322
  /* Now update the DDF */
2323
331
  r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_DODF, object);
2324
331
  LOG_TEST_GOTO_ERR(ctx, r, "'DODF' update error");
2325
2326
70
  if (r >= 0 && res_obj)
2327
0
    *res_obj = object;
2328
70
  object = NULL;
2329
2330
70
  profile->dirty = 1;
2331
2332
5.59k
err:
2333
5.59k
  sc_pkcs15_free_object(object);
2334
5.59k
  LOG_FUNC_RETURN(ctx, r);
2335
5.59k
}
2336
2337
2338
int
2339
sc_pkcs15init_get_pin_reference(struct sc_pkcs15_card *p15card,
2340
    struct sc_profile *profile, unsigned auth_method, int reference)
2341
4.13k
{
2342
4.13k
  struct sc_context *ctx = p15card->card->ctx;
2343
4.13k
  struct sc_pkcs15_auth_info auth_info;
2344
4.13k
  struct sc_pkcs15_object *auth_objs[0x10];
2345
4.13k
  int r, ii, nn_objs;
2346
2347
4.13k
  LOG_FUNC_CALLED(ctx);
2348
2349
  /* 1. Look for the corresponding pkcs15 PIN object. */
2350
2351
  /* Get all existing pkcs15 AUTH objects */
2352
4.13k
  r = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_AUTH_PIN, auth_objs, 0x10);
2353
4.13k
  LOG_TEST_RET(ctx, r, "Get PKCS#15 AUTH objects error");
2354
4.13k
  nn_objs = r;
2355
2356
4.13k
  sc_log(ctx, "found %i auth objects; looking for AUTH object(auth_method:%i,reference:%i)",
2357
4.13k
      nn_objs, auth_method, reference);
2358
5.77k
  for (ii=0; ii<nn_objs; ii++)   {
2359
2.96k
    struct sc_pkcs15_auth_info *auth_info = (struct sc_pkcs15_auth_info *)auth_objs[ii]->data;
2360
2.96k
    struct sc_pkcs15_pin_attributes *pin_attrs = &auth_info->attrs.pin;
2361
2362
2.96k
    sc_log(ctx, "check PIN(%.*s,auth_method:%i,type:%i,reference:%i,flags:%X)",
2363
2.96k
        (int) sizeof auth_objs[ii]->label, auth_objs[ii]->label, auth_info->auth_method, pin_attrs->type,
2364
2.96k
        pin_attrs->reference, pin_attrs->flags);
2365
    /* Find out if there is AUTH pkcs15 object with given 'type' and 'reference' */
2366
2.96k
    if (auth_info->auth_method == auth_method && pin_attrs->reference == reference)
2367
2.96k
      LOG_FUNC_RETURN(ctx, pin_attrs->reference);
2368
2369
2.70k
    if (auth_method != SC_AC_SYMBOLIC)
2370
309
      continue;
2371
2372
    /* Translate 'SYMBOLIC' PIN reference into the pkcs#15 pinAttributes.flags
2373
     *  and check for the existing pkcs15 PIN object with these flags. */
2374
2.39k
    switch (reference)   {
2375
1.06k
    case SC_PKCS15INIT_USER_PIN:
2376
1.06k
      if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN)
2377
413
        continue;
2378
651
      if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN)
2379
11
        continue;
2380
640
      break;
2381
1.30k
    case SC_PKCS15INIT_SO_PIN:
2382
1.30k
      if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN)
2383
266
        continue;
2384
1.03k
      if (!(pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN))
2385
628
        continue;
2386
410
      break;
2387
410
    case SC_PKCS15INIT_USER_PUK:
2388
14
      if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN)
2389
0
        continue;
2390
14
      if (!(pin_attrs->flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN))
2391
7
        continue;
2392
7
      break;
2393
8
    case SC_PKCS15INIT_SO_PUK:
2394
8
      if (!(pin_attrs->flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN))
2395
4
        continue;
2396
4
      if (!(pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN))
2397
4
        continue;
2398
0
      break;
2399
1
    default:
2400
1
      LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid Symbolic PIN reference");
2401
2.39k
    }
2402
2403
1.05k
    LOG_FUNC_RETURN(ctx, pin_attrs->reference);
2404
2405
1.05k
  }
2406
2407
  /* 2. No existing pkcs15 PIN object
2408
   *  -- check if profile defines some PIN with 'reference' as PIN reference. */
2409
2.81k
  r = sc_profile_get_pin_id_by_reference(profile, auth_method, reference, &auth_info);
2410
2.81k
  if (r < 0)
2411
2.81k
    LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "PIN template not found");
2412
2413
1.47k
  LOG_FUNC_RETURN(ctx, auth_info.attrs.pin.reference);
2414
1.47k
}
2415
2416
2417
static int
2418
sc_pkcs15init_store_data(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
2419
    struct sc_pkcs15_object *object, struct sc_pkcs15_der *data,
2420
    struct sc_path *path)
2421
5.62k
{
2422
5.62k
  struct sc_context *ctx = p15card->card->ctx;
2423
5.62k
  struct sc_file  *file = NULL;
2424
5.62k
  int   r;
2425
2426
5.62k
  LOG_FUNC_CALLED(ctx);
2427
2428
5.62k
  if (profile->ops->emu_store_data)   {
2429
1.33k
    r = profile->ops->emu_store_data(p15card, profile, object, data, path);
2430
1.33k
    if (r == SC_SUCCESS || r != SC_ERROR_NOT_IMPLEMENTED)
2431
1.33k
      LOG_FUNC_RETURN(ctx, r);
2432
1.33k
  }
2433
2434
4.72k
  r = select_object_path(p15card, profile, object, path);
2435
4.72k
  LOG_TEST_RET(ctx, r, "Failed to select object path");
2436
2437
4.59k
  r = sc_profile_get_file_by_path(profile, path, &file);
2438
4.59k
  LOG_TEST_RET(ctx, r, "Failed to get file by path");
2439
2440
1.87k
  if (file->path.count == 0) {
2441
172
    file->path.index = 0;
2442
172
    file->path.count = -1;
2443
172
  }
2444
2445
1.87k
  r = sc_pkcs15init_delete_by_path(profile, p15card, &file->path);
2446
1.87k
  if (r && r != SC_ERROR_FILE_NOT_FOUND) {
2447
1.06k
    sc_file_free(file);
2448
1.06k
    LOG_TEST_RET(ctx, r, "Cannot delete file");
2449
1.06k
  }
2450
2451
807
  r = sc_pkcs15init_update_file(profile, p15card, file, data->value, data->len);
2452
2453
807
  *path = file->path;
2454
2455
807
  sc_file_free(file);
2456
807
  LOG_FUNC_RETURN(ctx, r);
2457
807
}
2458
2459
/*
2460
 * Map X509 keyUsage extension bits to PKCS#15 keyUsage bits
2461
 */
2462
typedef struct {
2463
  unsigned long x509_usage;
2464
  unsigned int p15_usage;
2465
} sc_usage_map;
2466
2467
static sc_usage_map x509_to_pkcs15_private_key_usage[16] = {
2468
  { SC_PKCS15INIT_X509_DIGITAL_SIGNATURE,
2469
    SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_SIGNRECOVER },
2470
  { SC_PKCS15INIT_X509_NON_REPUDIATION, SC_PKCS15_PRKEY_USAGE_NONREPUDIATION },
2471
  { SC_PKCS15INIT_X509_KEY_ENCIPHERMENT, SC_PKCS15_PRKEY_USAGE_UNWRAP },
2472
  { SC_PKCS15INIT_X509_DATA_ENCIPHERMENT, SC_PKCS15_PRKEY_USAGE_DECRYPT },
2473
  { SC_PKCS15INIT_X509_KEY_AGREEMENT, SC_PKCS15_PRKEY_USAGE_DERIVE },
2474
  { SC_PKCS15INIT_X509_KEY_CERT_SIGN,
2475
    SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_SIGNRECOVER },
2476
  { SC_PKCS15INIT_X509_CRL_SIGN,
2477
    SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_SIGNRECOVER }
2478
};
2479
2480
static sc_usage_map x509_to_pkcs15_public_key_usage[16] = {
2481
  { SC_PKCS15INIT_X509_DIGITAL_SIGNATURE,
2482
    SC_PKCS15_PRKEY_USAGE_VERIFY | SC_PKCS15_PRKEY_USAGE_VERIFYRECOVER },
2483
  { SC_PKCS15INIT_X509_NON_REPUDIATION, SC_PKCS15_PRKEY_USAGE_NONREPUDIATION },
2484
  { SC_PKCS15INIT_X509_KEY_ENCIPHERMENT, SC_PKCS15_PRKEY_USAGE_WRAP },
2485
  { SC_PKCS15INIT_X509_DATA_ENCIPHERMENT, SC_PKCS15_PRKEY_USAGE_ENCRYPT },
2486
  { SC_PKCS15INIT_X509_KEY_AGREEMENT, SC_PKCS15_PRKEY_USAGE_DERIVE },
2487
  { SC_PKCS15INIT_X509_KEY_CERT_SIGN,
2488
    SC_PKCS15_PRKEY_USAGE_VERIFY | SC_PKCS15_PRKEY_USAGE_VERIFYRECOVER },
2489
  { SC_PKCS15INIT_X509_CRL_SIGN,
2490
    SC_PKCS15_PRKEY_USAGE_VERIFY | SC_PKCS15_PRKEY_USAGE_VERIFYRECOVER }
2491
};
2492
2493
2494
static unsigned int
2495
sc_pkcs15init_map_usage(unsigned long x509_usage, int _private)
2496
0
{
2497
0
  unsigned int  p15_usage = 0, n;
2498
0
  sc_usage_map   *map;
2499
2500
0
  map = _private ? x509_to_pkcs15_private_key_usage
2501
0
          : x509_to_pkcs15_public_key_usage;
2502
0
  for (n = 0; n < 16; n++) {
2503
0
    if (x509_usage & map[n].x509_usage)
2504
0
      p15_usage |= map[n].p15_usage;
2505
0
  }
2506
0
  return p15_usage;
2507
0
}
2508
2509
2510
/*
2511
 * Compute modulus length
2512
 */
2513
static size_t
2514
sc_pkcs15init_keybits(struct sc_pkcs15_bignum *bn)
2515
15
{
2516
15
  unsigned int  mask;
2517
15
  size_t bits;
2518
2519
15
  if (!bn || !bn->len)
2520
0
    return 0;
2521
15
  bits = bn->len << 3;
2522
49
  for (mask = 0x80; mask && !(bn->data[0] & mask); mask >>= 1)
2523
34
    bits--;
2524
15
  return bits;
2525
15
}
2526
2527
2528
/*
2529
 * Check consistency of the key parameters.
2530
 */
2531
static int
2532
check_keygen_params_consistency(struct sc_card *card,
2533
    unsigned long alg, struct sc_pkcs15init_prkeyargs *prkey,
2534
    unsigned int *keybits)
2535
27.9k
{
2536
27.9k
  struct sc_context *ctx = card->ctx;
2537
27.9k
  int i, rv;
2538
2539
27.9k
  if (prkey && (alg == SC_ALGORITHM_EC ||
2540
5.59k
             alg == SC_ALGORITHM_EDDSA ||
2541
5.59k
             alg == SC_ALGORITHM_XEDDSA)) {
2542
5.59k
    struct sc_ec_parameters *ecparams = &prkey->key.u.ec.params;
2543
2544
5.59k
    rv = sc_pkcs15_fix_ec_parameters(ctx, ecparams);
2545
5.59k
    LOG_TEST_RET(ctx, rv, "Cannot fix EC parameters");
2546
2547
5.59k
    sc_log(ctx, "EC parameters: %s", sc_dump_hex(ecparams->der.value, ecparams->der.len));
2548
5.59k
    if (!*keybits)
2549
5.59k
      *keybits = (unsigned int)ecparams->field_length;
2550
5.59k
  }
2551
2552
126k
  for (i = 0; i < card->algorithm_count; i++) {
2553
105k
    struct sc_algorithm_info *info = &card->algorithms[i];
2554
2555
105k
    if (info->algorithm != alg)
2556
91.9k
      continue;
2557
2558
13.4k
    if (info->key_length != *keybits)
2559
6.80k
      continue;
2560
2561
6.65k
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
2562
6.65k
  }
2563
2564
21.3k
  if (prkey && (alg == SC_ALGORITHM_EC ||
2565
973
             alg == SC_ALGORITHM_EDDSA ||
2566
4.26k
             alg == SC_ALGORITHM_XEDDSA)) {
2567
    /* allocated in sc_pkcs15_fix_ec_parameters */
2568
4.26k
    free(prkey->key.u.ec.params.der.value);
2569
4.26k
    prkey->key.u.ec.params.der.value = NULL;
2570
4.26k
  }
2571
2572
21.3k
  LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
2573
21.3k
}
2574
2575
/*
2576
 * Check whether the card has native crypto support for this key.
2577
 */
2578
static int
2579
check_key_compatibility(struct sc_pkcs15_card *p15card, unsigned long alg,
2580
    struct sc_pkcs15_prkey *prkey, unsigned long x509_usage,
2581
    size_t key_length, unsigned long flags)
2582
23.4k
{
2583
23.4k
  struct sc_context *ctx = p15card->card->ctx;
2584
23.4k
  struct sc_algorithm_info *info;
2585
23.4k
  unsigned int count;
2586
23.4k
  unsigned long talg = alg;
2587
2588
23.4k
  LOG_FUNC_CALLED(ctx);
2589
2590
23.4k
  if (alg == SC_ALGORITHM_EDDSA || alg == SC_ALGORITHM_XEDDSA)
2591
0
    talg = SC_ALGORITHM_EC; /* really testing ecparams */
2592
2593
23.4k
  count = p15card->card->algorithm_count;
2594
119k
  for (info = p15card->card->algorithms; count--; info++) {
2595
    /* don't check flags if none was specified */
2596
2597
102k
    if (alg != SC_ALGORITHM_EDDSA && alg != SC_ALGORITHM_XEDDSA) {
2598
102k
      if (info->algorithm != alg || info->key_length != key_length)
2599
95.0k
        continue;
2600
102k
    }
2601
7.35k
    if (flags != 0 && ((info->flags & flags) != flags))
2602
777
      continue;
2603
2604
6.58k
    if (alg == SC_ALGORITHM_RSA && prkey)   {
2605
4.54k
      if (info->u._rsa.exponent != 0 && prkey->u.rsa.exponent.len != 0) {
2606
0
        struct sc_pkcs15_bignum *e = &prkey->u.rsa.exponent;
2607
0
        unsigned long exponent = 0;
2608
0
        unsigned int  n;
2609
2610
0
        if (e->len > 4)
2611
0
          continue;
2612
0
        for (n = 0; n < e->len; n++) {
2613
0
          exponent <<= 8;
2614
0
          exponent |= e->data[n];
2615
0
        }
2616
0
        if (info->u._rsa.exponent != exponent)
2617
0
          continue;
2618
0
      }
2619
4.54k
    } else if (talg == SC_ALGORITHM_EC) { /* includes EDDSA and XEDDSA */
2620
1.33k
      if (!sc_valid_oid(&prkey->u.ec.params.id))
2621
0
        if (sc_pkcs15_fix_ec_parameters(ctx, &prkey->u.ec.params))
2622
0
          LOG_FUNC_RETURN(ctx, SC_ERROR_OBJECT_NOT_VALID);
2623
1.33k
      if (sc_valid_oid(&info->u._ec.params.id))
2624
709
        if (!sc_compare_oid(&info->u._ec.params.id, &prkey->u.ec.params.id))
2625
0
          continue;
2626
1.33k
    }
2627
2628
6.58k
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
2629
6.58k
  }
2630
2631
16.8k
  LOG_FUNC_RETURN(ctx, SC_ERROR_OBJECT_NOT_VALID);
2632
16.8k
}
2633
2634
2635
/*
2636
 * Check RSA key for consistency, and compute missing
2637
 * CRT elements
2638
 */
2639
static int
2640
prkey_fixup_rsa(struct sc_pkcs15_card *p15card, struct sc_pkcs15_prkey_rsa *key)
2641
0
{
2642
0
  struct sc_context *ctx = p15card->card->ctx;
2643
0
  int r = SC_SUCCESS;
2644
2645
0
  if (!key->modulus.len || !key->exponent.len || !key->d.len || !key->p.len || !key->q.len) {
2646
0
    sc_log(ctx, "Missing private RSA coefficient");
2647
0
    return SC_ERROR_INVALID_ARGUMENTS;
2648
0
  }
2649
2650
0
#ifdef ENABLE_OPENSSL
2651
2652
  /* Generate additional parameters.
2653
   * At least the GPK seems to need the full set of CRT
2654
   * parameters; storing just the private exponent produces
2655
   * invalid signatures.
2656
   * The cryptoflex does not seem to be able to do any sort
2657
   * of RSA without the full set of CRT coefficients either
2658
   */
2659
   /* We don't really need an RSA structure, only the BIGNUMs */
2660
2661
0
  if (!key->dmp1.len || !key->dmq1.len || !key->iqmp.len) {
2662
0
    BIGNUM *aux = NULL;
2663
0
    BN_CTX *bn_ctx = NULL;
2664
0
    BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL, *rsa_p = NULL,
2665
0
           *rsa_q = NULL, *rsa_dmp1 = NULL, *rsa_dmq1 = NULL, *rsa_iqmp = NULL;
2666
2667
0
    rsa_n = BN_bin2bn(key->modulus.data, (int)key->modulus.len, NULL);
2668
0
    rsa_e = BN_bin2bn(key->exponent.data, (int)key->exponent.len, NULL);
2669
0
    rsa_d = BN_bin2bn(key->d.data, (int)key->d.len, NULL);
2670
0
    rsa_p = BN_bin2bn(key->p.data, (int)key->p.len, NULL);
2671
0
    rsa_q = BN_bin2bn(key->q.data, (int)key->q.len, NULL);
2672
0
    rsa_dmp1 = BN_new();
2673
0
    rsa_dmq1 = BN_new();
2674
0
    rsa_iqmp = BN_new();
2675
2676
0
    if (!rsa_n || !rsa_e || !rsa_d || !rsa_p || !rsa_q ||
2677
0
        !rsa_dmp1 || !rsa_dmq1 || !rsa_iqmp) {
2678
0
      sc_log_openssl(ctx);
2679
0
      r = SC_ERROR_INTERNAL;
2680
0
      goto end;
2681
0
    }
2682
2683
0
    aux = BN_new();
2684
0
    bn_ctx = BN_CTX_new();
2685
2686
0
    if (!aux || !bn_ctx) {
2687
0
      sc_log_openssl(ctx);
2688
0
      r = SC_ERROR_INTERNAL;
2689
0
      goto end;
2690
0
    }
2691
2692
0
    if (BN_sub(aux, rsa_q, BN_value_one()) != 1 ||
2693
0
        BN_mod(rsa_dmq1, rsa_d, aux, bn_ctx) != 1 ||
2694
0
        BN_sub(aux, rsa_p, BN_value_one()) != 1 ||
2695
0
        BN_mod(rsa_dmp1, rsa_d, aux, bn_ctx) != 1 ||
2696
0
        !BN_mod_inverse(rsa_iqmp, rsa_q, rsa_p, bn_ctx)) {
2697
0
      sc_log_openssl(ctx);
2698
0
      r = SC_ERROR_INTERNAL;
2699
0
      goto end;
2700
0
    }
2701
2702
    /* Do not replace, only fill in missing */
2703
0
    if (key->dmp1.data == NULL) {
2704
0
      key->dmp1.len = BN_num_bytes(rsa_dmp1);
2705
0
      key->dmp1.data = malloc(key->dmp1.len);
2706
0
      if (key->dmp1.data) {
2707
0
        BN_bn2bin(rsa_dmp1, key->dmp1.data);
2708
0
      } else {
2709
0
        key->dmp1.len = 0;
2710
0
      }
2711
0
    }
2712
2713
0
    if (key->dmq1.data == NULL) {
2714
0
      key->dmq1.len = BN_num_bytes(rsa_dmq1);
2715
0
      key->dmq1.data = malloc(key->dmq1.len);
2716
0
      if (key->dmq1.data) {
2717
0
        BN_bn2bin(rsa_dmq1, key->dmq1.data);
2718
0
      } else {
2719
0
        key->dmq1.len = 0;
2720
0
      }
2721
0
    }
2722
0
    if (key->iqmp.data == NULL) {
2723
0
      key->iqmp.len = BN_num_bytes(rsa_iqmp);
2724
0
      key->iqmp.data = malloc(key->iqmp.len);
2725
0
      if (key->iqmp.data) {
2726
0
        BN_bn2bin(rsa_iqmp, key->iqmp.data);
2727
0
      } else {
2728
0
        key->iqmp.len = 0;
2729
0
      }
2730
0
    }
2731
0
end:
2732
0
    BN_clear_free(rsa_n);
2733
0
    BN_clear_free(rsa_e);
2734
0
    BN_clear_free(rsa_d);
2735
0
    BN_clear_free(rsa_p);
2736
0
    BN_clear_free(rsa_q);
2737
0
    BN_clear_free(rsa_dmp1);
2738
0
    BN_clear_free(rsa_dmq1);
2739
0
    BN_clear_free(rsa_iqmp);
2740
0
    BN_clear_free(aux);
2741
0
    BN_CTX_free(bn_ctx);
2742
0
  }
2743
0
#endif
2744
0
  return r;
2745
0
}
2746
2747
2748
static int
2749
prkey_fixup(struct sc_pkcs15_card *p15card, struct sc_pkcs15_prkey *key)
2750
0
{
2751
0
  switch (key->algorithm) {
2752
0
  case SC_ALGORITHM_RSA:
2753
0
    return prkey_fixup_rsa(p15card, &key->u.rsa);
2754
0
  case SC_ALGORITHM_GOSTR3410:
2755
    /* for now */
2756
0
    return 0;
2757
0
  }
2758
0
  return 0;
2759
0
}
2760
2761
2762
static int
2763
prkey_bits(struct sc_pkcs15_card *p15card, struct sc_pkcs15_prkey *key)
2764
0
{
2765
0
  struct sc_context *ctx = p15card->card->ctx;
2766
2767
0
  switch (key->algorithm) {
2768
0
  case SC_ALGORITHM_RSA:
2769
0
    return (int)sc_pkcs15init_keybits(&key->u.rsa.modulus);
2770
0
  case SC_ALGORITHM_GOSTR3410:
2771
0
    if (sc_pkcs15init_keybits(&key->u.gostr3410.d) > SC_PKCS15_GOSTR3410_KEYSIZE) {
2772
0
      sc_log(ctx,
2773
0
             "Unsupported key (keybits %"SC_FORMAT_LEN_SIZE_T"u)",
2774
0
             sc_pkcs15init_keybits(&key->u.gostr3410.d));
2775
0
      return SC_ERROR_OBJECT_NOT_VALID;
2776
0
    }
2777
0
    return SC_PKCS15_GOSTR3410_KEYSIZE;
2778
0
  case SC_ALGORITHM_EC:
2779
0
  case SC_ALGORITHM_EDDSA:
2780
0
  case SC_ALGORITHM_XEDDSA:
2781
0
    sc_log(ctx, "Private EC type key length %" SC_FORMAT_LEN_SIZE_T "u",
2782
0
        key->u.ec.params.field_length);
2783
0
    if (key->u.ec.params.field_length == 0)   {
2784
0
      sc_log(ctx, "Invalid EC key length");
2785
0
      return SC_ERROR_OBJECT_NOT_VALID;
2786
0
    }
2787
0
    return (int)key->u.ec.params.field_length;
2788
0
  }
2789
0
  sc_log(ctx, "Unsupported key algorithm.");
2790
0
  return SC_ERROR_NOT_SUPPORTED;
2791
0
}
2792
2793
2794
static int
2795
key_pkcs15_algo(struct sc_pkcs15_card *p15card, unsigned long algorithm)
2796
22.6k
{
2797
22.6k
  struct sc_context *ctx = p15card->card->ctx;
2798
2799
22.6k
  switch (algorithm) {
2800
4.54k
  case SC_ALGORITHM_RSA:
2801
4.54k
    return SC_PKCS15_TYPE_PRKEY_RSA;
2802
0
  case SC_ALGORITHM_GOSTR3410:
2803
0
    return SC_PKCS15_TYPE_PRKEY_GOSTR3410;
2804
1.33k
  case SC_ALGORITHM_EC:
2805
1.33k
    return SC_PKCS15_TYPE_PRKEY_EC;
2806
0
  case SC_ALGORITHM_EDDSA:
2807
0
    return SC_PKCS15_TYPE_PRKEY_EDDSA;
2808
0
  case SC_ALGORITHM_XEDDSA:
2809
0
    return SC_PKCS15_TYPE_PRKEY_XEDDSA;
2810
5.59k
  case SC_ALGORITHM_DES:
2811
5.59k
    return SC_PKCS15_TYPE_SKEY_DES;
2812
5.59k
  case SC_ALGORITHM_3DES:
2813
5.59k
    return SC_PKCS15_TYPE_SKEY_3DES;
2814
5.59k
  case SC_ALGORITHM_AES:
2815
5.59k
  case SC_ALGORITHM_UNDEFINED:
2816
5.59k
    return SC_PKCS15_TYPE_SKEY_GENERIC;
2817
22.6k
  }
2818
0
  sc_log(ctx, "Unsupported key algorithm.");
2819
0
  return SC_ERROR_NOT_SUPPORTED;
2820
22.6k
}
2821
2822
2823
static struct sc_pkcs15_df *
2824
find_df_by_type(struct sc_pkcs15_card *p15card, unsigned int type)
2825
3.25k
{
2826
3.25k
  struct sc_pkcs15_df *df = p15card->df_list;
2827
2828
9.97k
  while (df != NULL && df->type != type)
2829
6.72k
    df = df->next;
2830
3.25k
  return df;
2831
3.25k
}
2832
2833
2834
int
2835
sc_pkcs15init_select_intrinsic_id(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
2836
    int type, struct sc_pkcs15_id *id_out, void *data)
2837
64
{
2838
#ifndef ENABLE_OPENSSL
2839
  LOG_FUNC_RETURN(p15card->card->ctx, SC_SUCCESS);
2840
#else
2841
64
  struct sc_context *ctx = p15card->card->ctx;
2842
64
  struct sc_pkcs15_pubkey *pubkey = NULL;
2843
64
  unsigned id_style;
2844
64
  struct sc_pkcs15_id id;
2845
64
  unsigned char *id_data = NULL;
2846
64
  size_t id_data_len = 0;
2847
64
  int rv, allocated = 0;
2848
2849
64
  LOG_FUNC_CALLED(ctx);
2850
2851
64
  if (!id_out || !profile)
2852
64
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
2853
2854
64
  id_style = profile->id_style;
2855
2856
  /* ID already exists */
2857
64
  if (id_out->len)
2858
64
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
2859
2860
  /* Native ID style is not intrinsic one */
2861
35
  if (id_style == SC_PKCS15INIT_ID_STYLE_NATIVE)
2862
35
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
2863
2864
10
  memset(&id, 0, sizeof(id));
2865
  /* Get PKCS15 public key */
2866
10
  switch(type)   {
2867
0
  case SC_PKCS15_TYPE_CERT_X509:
2868
0
    rv = sc_pkcs15_pubkey_from_cert(ctx, (struct sc_pkcs15_der *)data, &pubkey);
2869
0
    LOG_TEST_RET(ctx, rv, "X509 parse error");
2870
0
    allocated = 1;
2871
0
    break;
2872
0
  case SC_PKCS15_TYPE_PRKEY:
2873
0
    rv = sc_pkcs15_pubkey_from_prvkey(ctx, (struct sc_pkcs15_prkey *)data, &pubkey);
2874
0
    LOG_TEST_RET(ctx, rv, "Cannot get public key");
2875
0
    allocated = 1;
2876
0
    break;
2877
10
  case SC_PKCS15_TYPE_PUBKEY:
2878
10
    pubkey = (struct sc_pkcs15_pubkey *)data;
2879
10
    allocated = 0;
2880
10
    break;
2881
0
  default:
2882
0
    sc_log(ctx, "Intrinsic ID is not implemented for the object type 0x%X", type);
2883
0
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
2884
10
  }
2885
2886
  /* Skip silently if key is not initialized. */
2887
10
  if (pubkey->algorithm == SC_ALGORITHM_RSA && !pubkey->u.rsa.modulus.len)
2888
1
    goto done;
2889
9
  else if (pubkey->algorithm == SC_ALGORITHM_GOSTR3410 &&
2890
0
      !pubkey->u.gostr3410.xy.data)
2891
0
    goto done;
2892
9
  else if (pubkey->algorithm == SC_ALGORITHM_EC && !pubkey->u.ec.ecpointQ.value)
2893
0
    goto done;
2894
2895
  /* In Mozilla 'GOST R 34.10' is not yet supported.
2896
   * So, switch to the ID recommended by RFC2459 */
2897
9
  if (pubkey->algorithm == SC_ALGORITHM_GOSTR3410 && id_style == SC_PKCS15INIT_ID_STYLE_MOZILLA)
2898
0
    id_style = SC_PKCS15INIT_ID_STYLE_RFC2459;
2899
2900
9
  switch (id_style)  {
2901
7
  case SC_PKCS15INIT_ID_STYLE_MOZILLA:
2902
7
    if (pubkey->algorithm == SC_ALGORITHM_RSA)
2903
7
      SHA1(pubkey->u.rsa.modulus.data, pubkey->u.rsa.modulus.len, id.value);
2904
0
    else if (pubkey->algorithm == SC_ALGORITHM_EC)
2905
      /* ID should be SHA1 of the X coordinate according to PKCS#15 v1.1 */
2906
      /* skip the 04 tag and get the X component */
2907
0
      SHA1(pubkey->u.ec.ecpointQ.value+1, (pubkey->u.ec.ecpointQ.len - 1) / 2, id.value);
2908
0
    else
2909
0
      goto done;
2910
2911
7
    id.len = SHA_DIGEST_LENGTH;
2912
7
    break;
2913
1
  case SC_PKCS15INIT_ID_STYLE_RFC2459:
2914
1
    rv = sc_pkcs15_encode_pubkey(ctx, pubkey, &id_data, &id_data_len);
2915
1
    LOG_TEST_GOTO_ERR(ctx, rv, "Encoding public key error");
2916
2917
1
    if (!id_data || !id_data_len) {
2918
0
      rv = SC_ERROR_INTERNAL;
2919
0
      LOG_TEST_GOTO_ERR(ctx, rv, "Encoding public key error");
2920
0
    }
2921
2922
1
    SHA1(id_data, id_data_len, id.value);
2923
1
    id.len = SHA_DIGEST_LENGTH;
2924
2925
1
    break;
2926
1
  default:
2927
1
    sc_log(ctx, "Unsupported ID style: %i", id_style);
2928
1
    rv = SC_ERROR_NOT_SUPPORTED;
2929
1
    LOG_TEST_GOTO_ERR(ctx, rv, "Non supported ID style");
2930
9
  }
2931
2932
9
done:
2933
9
  memcpy(id_out, &id, sizeof(*id_out));
2934
9
  rv = (int)id_out->len;
2935
2936
10
err:
2937
10
  if (id_data)
2938
1
    free(id_data);
2939
10
  if (allocated)
2940
0
    sc_pkcs15_free_pubkey(pubkey);
2941
2942
10
  LOG_FUNC_RETURN(ctx, rv);
2943
10
#endif
2944
10
}
2945
2946
2947
static int
2948
select_id(struct sc_pkcs15_card *p15card, int type, struct sc_pkcs15_id *id)
2949
22.6k
{
2950
22.6k
  struct sc_context *ctx = p15card->card->ctx;
2951
22.6k
  struct sc_pkcs15_id unused_id;
2952
22.6k
  struct sc_pkcs15_object *obj;
2953
22.6k
  unsigned int nid = DEFAULT_ID;
2954
22.6k
  int r;
2955
2956
22.6k
  LOG_FUNC_CALLED(ctx);
2957
  /* If the user provided an ID, make sure we can use it */
2958
22.6k
  if (id->len != 0) {
2959
17.9k
    r = sc_pkcs15_find_object_by_id(p15card, type, id, &obj);
2960
2961
17.9k
    if (r == SC_ERROR_OBJECT_NOT_FOUND)
2962
17.9k
      r = 0;
2963
0
    else if (!r)
2964
0
      r = SC_ERROR_NON_UNIQUE_ID;
2965
2966
17.9k
    LOG_FUNC_RETURN(ctx, r);
2967
17.9k
  }
2968
2969
4.70k
  memset(&unused_id, 0, sizeof(unused_id));
2970
879k
  while (nid < 255) {
2971
874k
    id->value[0] = nid++;
2972
874k
    id->len = 1;
2973
2974
874k
    r = sc_pkcs15_find_object_by_id(p15card, type, id, &obj);
2975
874k
    if (r == SC_ERROR_OBJECT_NOT_FOUND) {
2976
      /* We don't have an object of that type yet.
2977
       * If we're allocating a PRKEY object, make
2978
       * sure there's no conflicting pubkey or cert
2979
       * object either. */
2980
874k
      if (type == SC_PKCS15_TYPE_PRKEY) {
2981
874k
        struct sc_pkcs15_search_key search_key;
2982
2983
874k
        memset(&search_key, 0, sizeof(search_key));
2984
874k
        search_key.class_mask = SC_PKCS15_SEARCH_CLASS_PUBKEY | SC_PKCS15_SEARCH_CLASS_CERT;
2985
874k
        search_key.id = id;
2986
2987
874k
        r = sc_pkcs15_search_objects(p15card, &search_key, NULL, 0);
2988
        /* If there is a pubkey or cert with
2989
         * this ID, skip it. */
2990
874k
        if (r > 0)
2991
18
          continue;
2992
874k
      }
2993
874k
      if (!unused_id.len)
2994
4.70k
        unused_id = *id;
2995
874k
      continue;
2996
874k
    }
2997
874k
  }
2998
2999
4.70k
  if (unused_id.len) {
3000
4.70k
    *id = unused_id;
3001
4.70k
    LOG_FUNC_RETURN(ctx, 0);
3002
4.70k
  }
3003
3004
0
  LOG_FUNC_RETURN(ctx, SC_ERROR_TOO_MANY_OBJECTS);
3005
0
}
3006
3007
3008
/*
3009
 * Select a path for a new object
3010
 *  1.  If the object is to be protected by a PIN, use the path
3011
 *  given in the PIN auth object
3012
 *  2.  Otherwise, use the path of the application DF
3013
 *  3.  If the profile defines a key-dir template, the new object
3014
 *  should go into a subdirectory of the selected DF:
3015
 *  Instantiate the template, using the ID of the new object
3016
 *  to uniquify the path. Inside the instantiated template,
3017
 *  look for a file corresponding to the type of object we
3018
 *  wish to create ("private-key", "public-key" etc).
3019
 */
3020
static const char *
3021
get_template_name_from_object (struct sc_pkcs15_object *obj)
3022
27.3k
{
3023
27.3k
  switch (obj->type & SC_PKCS15_TYPE_CLASS_MASK) {
3024
5.87k
  case SC_PKCS15_TYPE_PRKEY:
3025
5.87k
    return "private-key";
3026
27
  case SC_PKCS15_TYPE_PUBKEY:
3027
27
    return "public-key";
3028
16.7k
  case SC_PKCS15_TYPE_SKEY:
3029
16.7k
    return "secret-key";
3030
0
  case SC_PKCS15_TYPE_CERT:
3031
0
    return "certificate";
3032
4.70k
  case SC_PKCS15_TYPE_DATA_OBJECT:
3033
4.70k
    if (obj->flags & SC_PKCS15_CO_FLAG_PRIVATE)
3034
0
      return "privdata";
3035
4.70k
    else
3036
4.70k
      return "data";
3037
27.3k
  }
3038
3039
0
  return NULL;
3040
27.3k
}
3041
3042
3043
static int
3044
get_object_path_from_object (struct sc_pkcs15_object *obj,
3045
    struct sc_path *ret_path)
3046
5.07k
{
3047
5.07k
  if (!ret_path)
3048
0
    return SC_ERROR_INVALID_ARGUMENTS;
3049
3050
5.07k
  memset(ret_path, 0, sizeof(struct sc_path));
3051
3052
5.07k
  switch(obj->type & SC_PKCS15_TYPE_CLASS_MASK)   {
3053
3.51k
  case SC_PKCS15_TYPE_PRKEY:
3054
3.51k
    *ret_path = ((struct sc_pkcs15_prkey_info *)obj->data)->path;
3055
3.51k
    return SC_SUCCESS;
3056
0
  case SC_PKCS15_TYPE_PUBKEY:
3057
0
    *ret_path = ((struct sc_pkcs15_pubkey_info *)obj->data)->path;
3058
0
    return SC_SUCCESS;
3059
1.55k
  case SC_PKCS15_TYPE_SKEY:
3060
1.55k
    *ret_path = ((struct sc_pkcs15_skey_info *)obj->data)->path;
3061
1.55k
    return SC_SUCCESS;
3062
0
  case SC_PKCS15_TYPE_CERT:
3063
0
    *ret_path = ((struct sc_pkcs15_cert_info *)obj->data)->path;
3064
0
    return SC_SUCCESS;
3065
0
  case SC_PKCS15_TYPE_DATA_OBJECT:
3066
0
    *ret_path = ((struct sc_pkcs15_data_info *)obj->data)->path;
3067
0
    return SC_SUCCESS;
3068
0
  case SC_PKCS15_TYPE_AUTH:
3069
0
    *ret_path = ((struct sc_pkcs15_auth_info *)obj->data)->path;
3070
0
    return SC_SUCCESS;
3071
5.07k
  }
3072
0
  return SC_ERROR_NOT_SUPPORTED;
3073
5.07k
}
3074
3075
3076
static int
3077
select_object_path(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
3078
    struct sc_pkcs15_object *obj, struct sc_path *path)
3079
27.3k
{
3080
27.3k
  struct sc_context *ctx = p15card->card->ctx;
3081
27.3k
  struct sc_file  *file;
3082
27.3k
  struct sc_pkcs15_object *objs[32];
3083
27.3k
  struct sc_pkcs15_id index_id;
3084
27.3k
  struct sc_path obj_path;
3085
27.3k
  int ii, r, nn_objs, index;
3086
27.3k
  const char *name;
3087
3088
27.3k
  LOG_FUNC_CALLED(ctx);
3089
27.3k
  r = sc_pkcs15_get_objects(p15card, obj->type & SC_PKCS15_TYPE_CLASS_MASK, objs, sizeof(objs)/sizeof(objs[0]));
3090
27.3k
  LOG_TEST_RET(ctx, r, "Get PKCS#15 objects error");
3091
27.3k
  nn_objs = r;
3092
3093
  /* For cards with a pin-domain profile, we need
3094
   * to put the key below the DF of the specified PIN
3095
   */
3096
27.3k
  memset(path, 0, sizeof(*path));
3097
27.3k
  if (obj->auth_id.len && profile->pin_domains != 0) {
3098
56
    r = sc_pkcs15init_get_pin_path(p15card, &obj->auth_id, path);
3099
56
    LOG_TEST_RET(ctx, r, "Cannot get PIN path");
3100
56
  }
3101
27.3k
  else {
3102
27.3k
    *path = profile->df_info->file->path;
3103
27.3k
  }
3104
3105
  /* If the profile specifies a key directory template,
3106
   * instantiate it now and create the DF
3107
   */
3108
27.3k
  name = get_template_name_from_object (obj);
3109
27.3k
  if (!name)
3110
27.3k
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
3111
3112
27.3k
  sc_log(ctx, "key-domain.%s @%s (auth_id.len=%"SC_FORMAT_LEN_SIZE_T"u)",
3113
27.3k
         name, sc_print_path(path), obj->auth_id.len);
3114
3115
27.3k
  index_id.len = 1;
3116
32.2k
  for (index = TEMPLATE_INSTANTIATE_MIN_INDEX; index <= TEMPLATE_INSTANTIATE_MAX_INDEX; index++)   {
3117
32.1k
    index_id.value[0] = index;
3118
32.1k
    r = sc_profile_instantiate_template(profile, "key-domain", path, name, &index_id, &file);
3119
32.1k
    if (r == SC_ERROR_TEMPLATE_NOT_FOUND)   {
3120
      /* No template in 'key-domain' -- try to instantiate the template-'object name'
3121
       * outside of the 'key-domain' scope. */
3122
31.1k
      char t_name[0x40];
3123
3124
31.1k
      snprintf(t_name, sizeof(t_name), "template-%s", name);
3125
31.1k
      sc_log(ctx, "get instance %i of '%s'", index, t_name);
3126
31.1k
      r = sc_profile_get_file_instance(profile, t_name, index, &file);
3127
31.1k
      if (r == SC_ERROR_FILE_NOT_FOUND)
3128
31.1k
        LOG_FUNC_RETURN(ctx, SC_SUCCESS);
3129
31.1k
    }
3130
7.13k
    LOG_TEST_RET(ctx, r, "Template instantiation error");
3131
3132
6.42k
    if (file->type == SC_FILE_TYPE_BSO)
3133
25
      break;
3134
3135
6.39k
    sc_log(ctx, "instantiated template path %s", sc_print_path(&file->path));
3136
6.41k
    for (ii=0; ii<nn_objs; ii++)   {
3137
5.07k
      r = get_object_path_from_object(objs[ii], &obj_path);
3138
5.07k
      LOG_TEST_RET(ctx, r, "Failed to get object path from pkcs15 object");
3139
3140
5.07k
      if (obj_path.len != file->path.len)
3141
194
        break;
3142
3143
4.87k
      if (!memcmp(obj_path.value, file->path.value, obj_path.len))
3144
4.85k
        break;
3145
4.87k
    }
3146
3147
6.39k
    if (ii==nn_objs)
3148
1.34k
      break;
3149
3150
5.04k
    if (obj_path.len != file->path.len)
3151
194
      break;
3152
3153
4.85k
    sc_file_free(file);
3154
3155
4.85k
    index_id.value[0] += 1;
3156
4.85k
  }
3157
3158
1.58k
  if (index > TEMPLATE_INSTANTIATE_MAX_INDEX)
3159
1.58k
    LOG_TEST_RET(ctx, SC_ERROR_TOO_MANY_OBJECTS, "Template instantiation error");
3160
3161
1.56k
  *path = file->path;
3162
1.56k
  sc_file_free(file);
3163
3164
1.56k
  sc_log(ctx, "returns object path '%s'", sc_print_path(path));
3165
1.56k
  LOG_FUNC_RETURN(ctx, SC_SUCCESS);
3166
1.56k
}
3167
3168
/*
3169
 * Update EF(DIR)
3170
 */
3171
static int
3172
sc_pkcs15init_update_dir(struct sc_pkcs15_card *p15card,
3173
    struct sc_profile *profile,
3174
    struct sc_app_info *app)
3175
95
{
3176
95
  struct sc_context *ctx = p15card->card->ctx;
3177
95
  struct sc_card  *card = p15card->card;
3178
95
  int r, retry = 1;
3179
3180
95
  LOG_FUNC_CALLED(ctx);
3181
95
  if (profile->ops->emu_update_dir)   {
3182
0
    r = profile->ops->emu_update_dir(profile, p15card, app);
3183
0
    LOG_FUNC_RETURN(ctx, r);
3184
0
  }
3185
3186
166
  do {
3187
166
    struct sc_file  *dir_file;
3188
166
    struct sc_path  path;
3189
3190
166
    r = sc_enum_apps(card);
3191
166
    if (r != SC_ERROR_FILE_NOT_FOUND)
3192
86
      break;
3193
    /* DIR file is not yet created. */
3194
3195
80
    sc_format_path("3F002F00", &path);
3196
80
    r = sc_profile_get_file_by_path(profile, &path, &dir_file);
3197
80
    LOG_TEST_RET(ctx, r, "DIR file not defined in profile");
3198
3199
    /* Create DIR file */
3200
77
    r = sc_pkcs15init_update_file(profile, p15card, dir_file, NULL, 0);
3201
77
    sc_file_free(dir_file);
3202
77
  } while (retry--);
3203
3204
92
  if (r >= 0) {
3205
63
    card->app[card->app_count++] = app;
3206
63
    r = sc_update_dir(card, NULL);
3207
63
  }
3208
92
  LOG_FUNC_RETURN(ctx, r);
3209
92
}
3210
3211
3212
static int
3213
sc_pkcs15init_update_tokeninfo(struct sc_pkcs15_card *p15card, struct sc_profile *profile)
3214
1.14k
{
3215
1.14k
  struct sc_context *ctx = p15card->card->ctx;
3216
1.14k
  unsigned char *buf = NULL;
3217
1.14k
  size_t    size;
3218
1.14k
  int   rv;
3219
3220
1.14k
  LOG_FUNC_CALLED(ctx);
3221
3222
  /* set lastUpdate field */
3223
1.14k
  if (p15card->tokeninfo->last_update.gtime != NULL)   {
3224
27
    free(p15card->tokeninfo->last_update.gtime);
3225
27
    p15card->tokeninfo->last_update.gtime = NULL;
3226
27
  }
3227
1.14k
  rv = sc_pkcs15_get_generalized_time(ctx, &p15card->tokeninfo->last_update.gtime);
3228
1.14k
  LOG_TEST_RET(ctx, rv, "Cannot allocate generalized time string");
3229
3230
1.14k
  if (profile->ops->emu_update_tokeninfo)
3231
31
    return profile->ops->emu_update_tokeninfo(profile, p15card, p15card->tokeninfo);
3232
3233
1.11k
  if (!p15card->file_tokeninfo)   {
3234
625
    sc_log(ctx, "No TokenInfo to update");
3235
625
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
3236
625
  }
3237
3238
491
  rv = sc_pkcs15_encode_tokeninfo(ctx, p15card->tokeninfo, &buf, &size);
3239
491
  if (rv >= 0)
3240
370
    rv = sc_pkcs15init_update_file(profile, p15card, p15card->file_tokeninfo, buf, size);
3241
491
  if (buf)
3242
370
    free(buf);
3243
3244
491
  LOG_FUNC_RETURN(ctx, rv);
3245
491
}
3246
3247
3248
static int
3249
sc_pkcs15init_update_lastupdate(struct sc_pkcs15_card *p15card, struct sc_profile *profile)
3250
1.21k
{
3251
1.21k
  struct sc_context *ctx = p15card->card->ctx;
3252
1.21k
  int   r;
3253
3254
1.21k
  LOG_FUNC_CALLED(ctx);
3255
1.21k
  if (p15card->tokeninfo->last_update.path.len)    {
3256
105
    static const struct sc_asn1_entry c_asn1_last_update[2] = {
3257
105
            { "generalizedTime",    SC_ASN1_GENERALIZEDTIME, SC_ASN1_TAG_GENERALIZEDTIME,   SC_ASN1_OPTIONAL, NULL, NULL },
3258
105
      { NULL, 0, 0, 0, NULL, NULL }
3259
105
    };
3260
105
    struct sc_asn1_entry asn1_last_update[2];
3261
105
    size_t lupdate_len;
3262
105
    struct sc_file *file = NULL;
3263
105
    struct sc_pkcs15_last_update *last_update = &p15card->tokeninfo->last_update;
3264
105
    unsigned char *buf = NULL;
3265
105
    size_t buflen;
3266
3267
    /* update 'lastUpdate' file */
3268
105
    if (last_update->gtime != NULL)
3269
1
      free(last_update->gtime);
3270
105
    r = sc_pkcs15_get_generalized_time(ctx, &last_update->gtime);
3271
105
    LOG_TEST_RET(ctx, r, "Cannot allocate generalized time string");
3272
3273
105
    sc_copy_asn1_entry(c_asn1_last_update, asn1_last_update);
3274
105
    lupdate_len = strlen(last_update->gtime);
3275
105
    sc_format_asn1_entry(asn1_last_update + 0, last_update->gtime, &lupdate_len, 1);
3276
3277
105
    r = sc_asn1_encode(ctx, asn1_last_update, &buf, &buflen);
3278
105
    LOG_TEST_RET(ctx, r, "select object path failed");
3279
3280
105
    r = sc_select_file(p15card->card, &last_update->path, &file);
3281
105
    if (r < 0)
3282
103
      free(buf);
3283
105
    LOG_TEST_RET(ctx, r, "select object path failed");
3284
3285
2
    r = sc_pkcs15init_update_file(profile, p15card, file, buf, buflen);
3286
2
    sc_file_free(file);
3287
2
    if (buf)
3288
2
      free(buf);
3289
2
    LOG_TEST_RET(ctx, r, "Cannot update 'LastUpdate' file");
3290
1
    LOG_FUNC_RETURN(ctx, r);
3291
1
  }
3292
3293
1.11k
  r = sc_pkcs15init_update_tokeninfo(p15card, profile);
3294
1.11k
  LOG_FUNC_RETURN(ctx, r);
3295
1.11k
}
3296
3297
3298
static int
3299
sc_pkcs15init_update_odf(struct sc_pkcs15_card *p15card, struct sc_profile *profile)
3300
984
{
3301
984
  struct sc_context *ctx = p15card->card->ctx;
3302
984
  unsigned char *buf = NULL;
3303
984
  size_t    size;
3304
984
  int   r;
3305
3306
984
  LOG_FUNC_CALLED(ctx);
3307
984
  r = sc_pkcs15_encode_odf(ctx, p15card, &buf, &size);
3308
984
  if (r >= 0)
3309
982
    r = sc_pkcs15init_update_file(profile, p15card, p15card->file_odf, buf, size);
3310
984
  if (buf)
3311
982
    free(buf);
3312
984
  LOG_FUNC_RETURN(ctx, r);
3313
984
}
3314
3315
/*
3316
 * Update any PKCS15 DF file (except ODF and DIR)
3317
 */
3318
int
3319
sc_pkcs15init_update_any_df(struct sc_pkcs15_card *p15card,
3320
    struct sc_profile *profile,
3321
    struct sc_pkcs15_df *df,
3322
    int is_new)
3323
1.35k
{
3324
1.35k
  struct sc_context *ctx = p15card->card->ctx;
3325
1.35k
  struct sc_card  *card = p15card->card;
3326
1.35k
  struct sc_file  *file = NULL;
3327
1.35k
  unsigned char *buf = NULL;
3328
1.35k
  size_t    bufsize = 0;
3329
1.35k
  int   update_odf = is_new, r = 0;
3330
3331
1.35k
  LOG_FUNC_CALLED(ctx);
3332
1.35k
  if (!df)
3333
1.35k
    LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "DF missing");
3334
3335
1.35k
  r = sc_profile_get_file_by_path(profile, &df->path, &file);
3336
1.35k
  if (r < 0 || file == NULL)
3337
95
    sc_select_file(card, &df->path, &file);
3338
3339
1.35k
  r = sc_pkcs15_encode_df(card->ctx, p15card, df, &buf, &bufsize);
3340
1.35k
  if (r >= 0) {
3341
1.33k
    r = sc_pkcs15init_update_file(profile, p15card, file, buf, bufsize);
3342
3343
    /* For better performance and robustness, we want
3344
     * to note which portion of the file actually
3345
     * contains valid data.
3346
     *
3347
     * This is particularly useful if we store certificates
3348
     * directly in the CDF - we may want to make the CDF
3349
     * fairly big, without having to read the entire file
3350
     * every time we parse the CDF.
3351
     */
3352
1.33k
    if (profile->pkcs15.encode_df_length) {
3353
70
      df->path.count = (int)bufsize;
3354
70
      df->path.index = 0;
3355
70
      update_odf = 1;
3356
70
    }
3357
1.33k
    free(buf);
3358
1.33k
  }
3359
1.35k
  sc_file_free(file);
3360
3361
1.35k
  LOG_TEST_RET(ctx, r, "Failed to encode or update xDF");
3362
3363
  /* Now update the ODF if we have to */
3364
1.03k
  if (update_odf)
3365
984
    r = sc_pkcs15init_update_odf(p15card, profile);
3366
1.03k
  LOG_TEST_RET(ctx, r, "Failed to encode or update ODF");
3367
3368
929
  LOG_FUNC_RETURN(ctx, r > 0 ? SC_SUCCESS : r);
3369
929
}
3370
3371
/*
3372
 * Add an object to one of the pkcs15 directory files.
3373
 */
3374
int
3375
sc_pkcs15init_add_object(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
3376
    unsigned int df_type, struct sc_pkcs15_object *object)
3377
1.99k
{
3378
1.99k
  struct sc_context *ctx = p15card->card->ctx;
3379
1.99k
  struct sc_pkcs15_df *df;
3380
1.99k
  int is_new = 0, r = 0, object_added = 0;
3381
3382
1.99k
  LOG_FUNC_CALLED(ctx);
3383
1.99k
  sc_log(ctx, "add object %p to DF of type %u", object, df_type);
3384
3385
1.99k
  df = find_df_by_type(p15card, df_type);
3386
1.99k
  if (df == NULL) {
3387
1.78k
    struct sc_file  *file;
3388
1.78k
    file = profile->df[df_type];
3389
1.78k
    if (file == NULL) {
3390
527
      sc_log(ctx, "Profile doesn't define a DF file %u", df_type);
3391
527
      LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "DF not found in profile");
3392
527
    }
3393
1.25k
    sc_pkcs15_add_df(p15card, df_type, &file->path);
3394
1.25k
    df = find_df_by_type(p15card, df_type);
3395
1.25k
    if (df == NULL)
3396
0
      return SC_ERROR_INTERNAL;
3397
1.25k
    is_new = 1;
3398
3399
    /* Mark the df as enumerated, so libopensc doesn't try
3400
     * to load the file at a most inconvenient moment */
3401
1.25k
    df->enumerated = 1;
3402
1.25k
  }
3403
3404
1.46k
  if (object == NULL) {
3405
897
    sc_log(ctx, "Add nothing; just instantiate this directory file");
3406
897
  }
3407
572
  else if (object->df == NULL) {
3408
572
    sc_log(ctx, "Append object");
3409
572
    object->df = df;
3410
572
    r = sc_pkcs15_add_object(p15card, object);
3411
572
    LOG_TEST_RET(ctx, r, "Failed to add pkcs15 object");
3412
572
    object_added = 1;
3413
572
  }
3414
0
  else {
3415
0
    sc_log(ctx, "Reuse existing object");
3416
0
    if (object->df != df)
3417
0
      return SC_ERROR_INTERNAL;
3418
0
  }
3419
3420
1.46k
  if (profile->ops->emu_update_any_df)
3421
118
    r = profile->ops->emu_update_any_df(profile, p15card, SC_AC_OP_CREATE, object);
3422
1.35k
  else
3423
1.35k
    r = sc_pkcs15init_update_any_df(p15card, profile, df, is_new);
3424
3425
1.46k
  if (r < 0 && object_added)
3426
332
    sc_pkcs15_remove_object(p15card, object);
3427
3428
1.46k
  LOG_FUNC_RETURN(ctx, r > 0 ? SC_SUCCESS : r);
3429
1.46k
}
3430
3431
3432
struct sc_pkcs15_object *
3433
sc_pkcs15init_new_object(int type, const char *label, struct sc_pkcs15_id *auth_id, void *data)
3434
34.8k
{
3435
34.8k
  struct sc_pkcs15_object *object;
3436
34.8k
  unsigned int data_size = 0;
3437
3438
34.8k
  object = calloc(1, sizeof(*object));
3439
34.8k
  if (object == NULL)
3440
0
    return NULL;
3441
34.8k
  object->type = type;
3442
3443
34.8k
  switch (type & SC_PKCS15_TYPE_CLASS_MASK) {
3444
6.56k
  case SC_PKCS15_TYPE_AUTH:
3445
6.56k
    object->flags = DEFAULT_PIN_FLAGS;
3446
6.56k
    data_size = sizeof(struct sc_pkcs15_auth_info);
3447
6.56k
    break;
3448
5.87k
  case SC_PKCS15_TYPE_PRKEY:
3449
5.87k
    object->flags = DEFAULT_PRKEY_FLAGS;
3450
5.87k
    data_size = sizeof(struct sc_pkcs15_prkey_info);
3451
5.87k
    break;
3452
16.7k
  case SC_PKCS15_TYPE_SKEY:
3453
16.7k
    object->flags = DEFAULT_SKEY_FLAGS;
3454
16.7k
    data_size = sizeof(struct sc_pkcs15_skey_info);
3455
16.7k
    break;
3456
29
  case SC_PKCS15_TYPE_PUBKEY:
3457
29
    object->flags = DEFAULT_PUBKEY_FLAGS;
3458
29
    data_size = sizeof(struct sc_pkcs15_pubkey_info);
3459
29
    break;
3460
0
  case SC_PKCS15_TYPE_CERT:
3461
0
    object->flags = DEFAULT_CERT_FLAGS;
3462
0
    data_size = sizeof(struct sc_pkcs15_cert_info);
3463
0
    break;
3464
5.59k
  case SC_PKCS15_TYPE_DATA_OBJECT:
3465
5.59k
    object->flags = DEFAULT_DATA_FLAGS;
3466
5.59k
    if (auth_id->len != 0)
3467
0
      object->flags |= SC_PKCS15_CO_FLAG_PRIVATE;
3468
5.59k
    data_size = sizeof(struct sc_pkcs15_data_info);
3469
5.59k
    break;
3470
34.8k
  }
3471
3472
34.8k
  if (data_size) {
3473
34.8k
    object->data = calloc(1, data_size);
3474
34.8k
    if (!object->data) {
3475
0
      free(object);
3476
0
      return NULL;
3477
0
    }
3478
3479
34.8k
    if (data)
3480
1.45k
      memcpy(object->data, data, data_size);
3481
34.8k
  }
3482
3483
34.8k
  if (label)
3484
34.8k
    strlcpy(object->label, label, sizeof(object->label));
3485
34.8k
  if (auth_id)
3486
28.2k
    object->auth_id = *auth_id;
3487
3488
34.8k
  return object;
3489
34.8k
}
3490
3491
3492
void
3493
sc_pkcs15init_free_object(struct sc_pkcs15_object *object)
3494
22.6k
{
3495
22.6k
  if (object) {
3496
9.37k
    free(object->data);
3497
9.37k
    free(object);
3498
9.37k
  }
3499
22.6k
}
3500
3501
3502
int
3503
sc_pkcs15init_change_attrib(struct sc_pkcs15_card *p15card, struct sc_profile *profile, struct sc_pkcs15_object *object,
3504
    int new_attrib_type, void *new_value, int new_len)
3505
0
{
3506
0
  struct sc_context *ctx = p15card->card->ctx;
3507
0
  struct sc_card  *card = p15card->card;
3508
0
  unsigned char *buf = NULL;
3509
0
  size_t    bufsize = 0;
3510
0
  int   df_type, r = 0;
3511
0
  struct sc_pkcs15_df *df;
3512
0
  struct sc_pkcs15_id new_id = *((struct sc_pkcs15_id *) new_value);
3513
3514
0
  LOG_FUNC_CALLED(ctx);
3515
0
  if (object == NULL || object->df == NULL)
3516
0
    LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Cannot change attribute");
3517
0
  df_type = object->df->type;
3518
3519
0
  df = find_df_by_type(p15card, df_type);
3520
0
  if (df == NULL)
3521
0
    LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "Cannot change attribute");
3522
3523
0
  sc_log(ctx, "type of attribute to change %i; DF type %i", new_attrib_type, df_type);
3524
0
  switch(new_attrib_type)   {
3525
0
  case P15_ATTR_TYPE_LABEL:
3526
0
    if (new_len >= SC_PKCS15_MAX_LABEL_SIZE)
3527
0
      LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "New label too long");
3528
0
    memcpy(object->label, new_value, new_len);
3529
0
    object->label[new_len] = '\0';
3530
0
    break;
3531
0
  case P15_ATTR_TYPE_ID:
3532
0
    switch(df_type) {
3533
0
    case SC_PKCS15_PRKDF:
3534
0
      ((struct sc_pkcs15_prkey_info *) object->data)->id = new_id;
3535
0
      break;
3536
0
    case SC_PKCS15_PUKDF:
3537
0
    case SC_PKCS15_PUKDF_TRUSTED:
3538
0
      ((struct sc_pkcs15_pubkey_info *) object->data)->id = new_id;
3539
0
      break;
3540
0
    case SC_PKCS15_SKDF:
3541
0
      ((struct sc_pkcs15_skey_info *) object->data)->id = new_id;
3542
0
      break;
3543
0
    case SC_PKCS15_CDF:
3544
0
    case SC_PKCS15_CDF_TRUSTED:
3545
0
    case SC_PKCS15_CDF_USEFUL:
3546
0
      ((struct sc_pkcs15_cert_info *) object->data)->id = new_id;
3547
0
      break;
3548
0
    default:
3549
0
      LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Cannot change ID attribute");
3550
0
    }
3551
0
    break;
3552
0
  case P15_ATTR_TYPE_VALUE:
3553
0
    switch(df_type) {
3554
0
    case SC_PKCS15_DODF: {
3555
0
      u8 *nv;
3556
0
      struct sc_pkcs15_data_info *info = (struct sc_pkcs15_data_info *) object->data;
3557
0
      struct sc_path old_data_path = info->path;
3558
0
      struct sc_path new_data_path;
3559
0
      struct sc_pkcs15_der new_data;
3560
0
      new_data.len = new_len;
3561
0
      new_data.value = (u8 *) new_value;
3562
3563
      /* save new data as a new data file on token */
3564
0
      r = sc_pkcs15init_store_data(p15card, profile, object, &new_data, &new_data_path);
3565
0
      profile->dirty = 1;
3566
0
      LOG_TEST_RET(ctx, r, "Failed to store new data");
3567
3568
0
      nv = (u8 *) malloc (new_len * sizeof(u8));
3569
0
      if (!nv) {
3570
0
        LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
3571
0
      }
3572
0
      memcpy(nv, new_value, new_len * sizeof(u8));
3573
0
      free(info->data.value);
3574
      /*  set object members to represent new CKA_VALUE value,
3575
        new path will be written to DODF later in this function*/
3576
0
      info->data.len = new_len;
3577
0
      info->data.value = nv;
3578
0
      info->path = new_data_path;
3579
3580
      /* delete old data file from token */
3581
0
      r = sc_pkcs15init_delete_by_path(profile, p15card, &old_data_path);
3582
0
      LOG_TEST_RET(ctx, r, "Failed to delete old data");
3583
0
      break;
3584
0
    }
3585
0
    default:
3586
0
      LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Cannot change value attribute");
3587
0
    }
3588
0
    break;
3589
0
  default:
3590
0
    LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Only 'LABEL' or 'ID' or 'VALUE'(for data objects) attributes can be changed");
3591
0
  }
3592
3593
0
  if (profile->ops->emu_update_any_df)   {
3594
0
    r = profile->ops->emu_update_any_df(profile, p15card, SC_AC_OP_CREATE, object);
3595
0
    LOG_TEST_RET(ctx, r, "Card specific DF update failed");
3596
0
  }
3597
0
  else   {
3598
0
    r = sc_pkcs15_encode_df(card->ctx, p15card, df, &buf, &bufsize);
3599
0
    if (r >= 0) {
3600
0
      struct sc_file *file = NULL;
3601
3602
0
      r = sc_profile_get_file_by_path(profile, &df->path, &file);
3603
0
      if (r < 0)
3604
0
        free(buf);
3605
0
      LOG_TEST_RET(ctx, r, "Cannot instantiate file by path");
3606
3607
0
      r = sc_pkcs15init_update_file(profile, p15card, file, buf, bufsize);
3608
0
      free(buf);
3609
0
      sc_file_free(file);
3610
0
    }
3611
0
  }
3612
3613
0
  if (r > 0)
3614
0
    r = 0;
3615
0
  LOG_FUNC_RETURN(ctx, r);
3616
0
}
3617
3618
3619
int
3620
sc_pkcs15init_delete_object(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
3621
    struct sc_pkcs15_object *obj)
3622
0
{
3623
0
  struct sc_context *ctx = p15card->card->ctx;
3624
0
  struct sc_file *file = NULL;
3625
0
  struct sc_path path;
3626
0
  struct sc_pkcs15_df *df;
3627
0
  int r = 0, stored_in_ef = 0;
3628
3629
0
  LOG_FUNC_CALLED(ctx);
3630
0
  r = get_object_path_from_object(obj, &path);
3631
0
  LOG_TEST_RET(ctx, r, "Failed to get object path");
3632
3633
0
  sc_log(ctx, "delete object(type:%X) with path(type:%X,%s)", obj->type, path.type, sc_print_path(&path));
3634
3635
0
  if (profile->ops->delete_object != NULL) {
3636
    /* If there's a card-specific way to delete objects, use it. */
3637
0
    r = profile->ops->delete_object(profile, p15card, obj, &path);
3638
0
    if (r != SC_ERROR_NOT_SUPPORTED)
3639
0
      LOG_TEST_RET(ctx, r, "Card specific delete object failed");
3640
0
  }
3641
3642
0
  if (profile->ops->delete_object == NULL || r == SC_ERROR_NOT_SUPPORTED)  {
3643
0
    if (path.len || path.aid.len)   {
3644
0
      r = sc_select_file(p15card->card, &path, &file);
3645
0
      if (r != SC_ERROR_FILE_NOT_FOUND)
3646
0
        LOG_TEST_RET(ctx, r, "select object path failed");
3647
3648
0
      stored_in_ef = (file->type != SC_FILE_TYPE_DF);
3649
0
      sc_file_free(file);
3650
0
    }
3651
3652
    /* If the object is stored in a normal EF, try to delete the EF. */
3653
0
    if (r == SC_SUCCESS && stored_in_ef) {
3654
0
      r = sc_pkcs15init_delete_by_path(profile, p15card, &path);
3655
0
      LOG_TEST_RET(ctx, r, "Failed to delete object by path");
3656
0
    }
3657
0
  }
3658
3659
0
  if (profile->ops->emu_update_any_df)   {
3660
0
    r = profile->ops->emu_update_any_df(profile, p15card, SC_AC_OP_ERASE, obj);
3661
0
    LOG_TEST_RET(ctx, r, "'ERASE' update DF failed");
3662
0
  }
3663
3664
  /* Get the DF we're part of. If there's no DF, fine, we haven't been added yet. */
3665
0
  df = obj->df;
3666
0
  if (df)   {
3667
    /* Unlink the object and update the DF */
3668
0
    sc_pkcs15_remove_object(p15card, obj);
3669
0
    sc_pkcs15_free_object(obj);
3670
0
  }
3671
3672
0
  if (!profile->ops->emu_update_any_df)
3673
0
    r = sc_pkcs15init_update_any_df(p15card, profile, df, 0);
3674
3675
  /* mark card as dirty */
3676
0
  profile->dirty = 1;
3677
3678
0
  LOG_FUNC_RETURN(ctx, r);
3679
0
}
3680
3681
3682
int
3683
sc_pkcs15init_update_certificate(struct sc_pkcs15_card *p15card,
3684
  struct sc_profile *profile, struct sc_pkcs15_object *obj,
3685
  const unsigned char *rawcert, size_t certlen)
3686
0
{
3687
0
  struct sc_context *ctx = p15card->card->ctx;
3688
0
  struct sc_file *file = NULL;
3689
0
  struct sc_path *path = &((struct sc_pkcs15_cert_info *)obj->data)->path;
3690
0
  int r;
3691
3692
0
  LOG_FUNC_CALLED(ctx);
3693
0
  r = sc_select_file(p15card->card, path, &file);
3694
0
  LOG_TEST_RET(ctx, r, "Failed to select cert file");
3695
3696
  /* If the new cert doesn't fit in the EF, delete it and make the same, but bigger EF */
3697
0
  if (file->size != certlen) {
3698
0
    struct sc_file *parent = NULL;
3699
3700
0
    r = sc_pkcs15init_delete_by_path(profile, p15card, path);
3701
0
    if (r < 0)
3702
0
      goto done;
3703
3704
0
    file->size = certlen;
3705
3706
0
    r = do_select_parent(profile, p15card, file, &parent);
3707
0
    if (r < 0)
3708
0
      goto done;
3709
3710
0
    r = sc_pkcs15init_authenticate(profile, p15card, parent, SC_AC_OP_CREATE);
3711
0
    sc_file_free(parent);
3712
0
    if (r < 0)   {
3713
0
      sc_log(ctx, "'CREATE' authentication failed");
3714
0
      goto done;
3715
0
    }
3716
3717
    /* ensure we are in the correct lifecycle */
3718
0
    r = sc_pkcs15init_set_lifecycle(p15card->card, SC_CARDCTRL_LIFECYCLE_ADMIN);
3719
0
    if (r < 0 && r != SC_ERROR_NOT_SUPPORTED)
3720
0
      goto done;
3721
3722
0
    r = sc_create_file(p15card->card, file);
3723
0
    if (r < 0)   {
3724
0
      sc_log(ctx, "Cannot create cert file");
3725
0
      goto done;
3726
0
    }
3727
0
  }
3728
3729
0
  if (!sc_file_get_acl_entry(file, SC_AC_OP_UPDATE))   {
3730
0
    struct sc_path tmp_path;
3731
3732
    /* FCI of selected cert file do not contains ACLs.
3733
     * For the 'UPDATE' authentication use instead sc_file
3734
     *  instantiated from card profile with default ACLs. */
3735
0
    sc_file_free(file);
3736
3737
0
    r = select_object_path(p15card, profile, obj, &tmp_path);
3738
0
    if (r < 0)   {
3739
0
      sc_log(ctx, "Select object path error");
3740
0
      goto done;
3741
0
    }
3742
3743
0
    r = sc_profile_get_file_by_path(profile, path, &file);
3744
0
    if (r < 0)   {
3745
0
      sc_log(ctx, "Cannot instantiate cert file");
3746
0
      goto done;
3747
0
    }
3748
0
  }
3749
3750
  /* Write the new cert */
3751
0
  r = sc_pkcs15init_authenticate(profile, p15card, file, SC_AC_OP_UPDATE);
3752
0
  if (r < 0)   {
3753
0
    sc_log(ctx, "'UPDATE' authentication failed");
3754
0
    goto done;
3755
0
  }
3756
3757
0
  r = sc_select_file(p15card->card, path, NULL);
3758
0
  if (r < 0)
3759
0
    goto done;
3760
3761
0
  r = sc_update_binary(p15card->card, 0, rawcert, certlen, 0);
3762
0
  if (r < 0)
3763
0
    goto done;
3764
3765
  /* Fill the remaining space in the EF (if any) with zeros */
3766
0
  if (certlen < file->size) {
3767
0
    unsigned char *tmp = calloc(1, file->size - certlen);
3768
0
    if (tmp == NULL) {
3769
0
      r = SC_ERROR_OUT_OF_MEMORY;
3770
0
      goto done;
3771
0
    }
3772
0
    r = sc_update_binary(p15card->card, (unsigned int)certlen, tmp, file->size - certlen, 0);
3773
0
    free(tmp);
3774
0
    if (r < 0)
3775
0
      sc_log(ctx, "Update cert file error");
3776
0
  }
3777
3778
0
  if (r >= 0) {
3779
    /* Update the CDF entry */
3780
0
    path = &((struct sc_pkcs15_cert_info *)obj->data)->path;
3781
0
    if (file->size != certlen) {
3782
0
      path->index = 0;
3783
0
      path->count = (int)certlen;
3784
0
    }
3785
0
    else   {
3786
0
      path->count = -1;
3787
0
    }
3788
3789
0
    if (profile->ops->emu_update_any_df) {
3790
0
      r = profile->ops->emu_update_any_df(profile, p15card, SC_AC_OP_UPDATE, obj);
3791
0
      if (r == SC_ERROR_NOT_SUPPORTED)
3792
0
        r = SC_SUCCESS;
3793
0
    }
3794
0
    else {
3795
0
      r = sc_pkcs15init_update_any_df(p15card, profile, obj->df, 0);
3796
0
    }
3797
3798
0
    if (r < 0)
3799
0
      sc_log(ctx, "Failed to update CDF");
3800
0
  }
3801
3802
  /* mark card as dirty */
3803
0
  profile->dirty = 1;
3804
3805
0
done:
3806
0
  sc_file_free(file);
3807
3808
0
  LOG_FUNC_RETURN(ctx, r);
3809
0
}
3810
3811
3812
static const char *
3813
get_pin_ident_name(int type, int reference)
3814
1.45k
{
3815
1.45k
  switch (type)   {
3816
1.16k
  case SC_AC_CHV:
3817
1.16k
    return "PIN";
3818
25
  case SC_AC_PRO:
3819
25
    return "secure messaging key";
3820
15
  case SC_AC_AUT:
3821
15
    return "authentication key";
3822
13
  case SC_AC_SEN:
3823
13
    return "security environment";
3824
6
  case SC_AC_IDA:
3825
6
    return "PKCS#15 reference";
3826
40
  case SC_AC_SCB:
3827
40
    return "SCB byte in IAS/ECC";
3828
76
  case SC_AC_SYMBOLIC:
3829
76
    switch (reference) {
3830
21
          case SC_PKCS15INIT_USER_PIN:
3831
21
      return "user PIN";
3832
23
    case SC_PKCS15INIT_SO_PIN:
3833
23
      return "SO PIN";
3834
8
          case SC_PKCS15INIT_USER_PUK:
3835
8
      return "user PUK";
3836
17
    case SC_PKCS15INIT_SO_PUK:
3837
17
      return "SO PUK";
3838
76
    }
3839
1.45k
  }
3840
124
  return "authentication data";
3841
1.45k
}
3842
3843
3844
static int
3845
sc_pkcs15init_get_transport_key(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
3846
    int type, int reference, unsigned char *pinbuf, size_t *pinsize)
3847
150
{
3848
150
  struct sc_context *ctx = p15card->card->ctx;
3849
150
  struct sc_pkcs15_object *pin_obj = NULL;
3850
150
  struct sc_pkcs15_auth_info auth_info;
3851
150
  struct sc_cardctl_default_key data;
3852
150
  size_t    defsize = 0;
3853
150
  unsigned char defbuf[0x100];
3854
150
  int rv;
3855
3856
150
  LOG_FUNC_CALLED(ctx);
3857
3858
150
  data.method = type;
3859
150
  data.key_ref = reference;
3860
150
  data.len = sizeof(defbuf);
3861
150
  data.key_data = defbuf;
3862
150
  rv = sc_card_ctl(p15card->card, SC_CARDCTL_GET_DEFAULT_KEY, &data);
3863
150
  if (rv >= 0)
3864
10
    defsize = data.len;
3865
3866
150
  if (callbacks.get_key)   {
3867
0
    rv = callbacks.get_key(profile, type, reference, defbuf, defsize, pinbuf, pinsize);
3868
0
    LOG_TEST_RET(ctx, rv, "Cannot get key");
3869
150
  } else if (rv >= 0) {
3870
10
    if (*pinsize < defsize)
3871
10
      LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Get transport key error");
3872
3873
10
    memcpy(pinbuf, data.key_data, data.len);
3874
10
    *pinsize = data.len;
3875
140
  } else {
3876
    /* pinbuf and pinsize were not filled */
3877
140
    LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "Get transport key error");
3878
140
  }
3879
3880
10
  memset(&auth_info, 0, sizeof(auth_info));
3881
10
  auth_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
3882
10
  auth_info.auth_method = type;
3883
10
  auth_info.attrs.pin.reference = reference;
3884
10
  auth_info.attrs.pin.stored_length = *pinsize;
3885
10
  auth_info.attrs.pin.max_length = *pinsize;
3886
10
  auth_info.attrs.pin.min_length = *pinsize;
3887
3888
10
  pin_obj = sc_pkcs15init_new_object(SC_PKCS15_TYPE_AUTH_PIN, "Default transport key", NULL, &auth_info);
3889
10
  if (!pin_obj)
3890
10
    LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate AUTH object");
3891
3892
10
  rv = sc_pkcs15_add_object(p15card, pin_obj);
3893
10
  LOG_TEST_RET(ctx, rv, "Cannot add PKCS#15 AUTH object");
3894
3895
10
  sc_pkcs15_pincache_add(p15card, pin_obj, pinbuf, *pinsize);
3896
3897
10
  LOG_FUNC_RETURN(ctx, rv);
3898
10
}
3899
3900
3901
/*
3902
 * PIN verification
3903
 */
3904
int
3905
sc_pkcs15init_verify_secret(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
3906
    struct sc_file *file, unsigned int type, int reference)
3907
1.45k
{
3908
1.45k
  struct sc_context *ctx = p15card->card->ctx;
3909
1.45k
  struct sc_pkcs15_object *pin_obj = NULL;
3910
1.45k
  struct sc_pkcs15_auth_info auth_info;
3911
1.45k
  struct sc_path  *path;
3912
1.45k
  int   r, use_pinpad = 0, pin_id = -1;
3913
1.45k
  const char  *ident, *label = NULL;
3914
1.45k
  unsigned char pinbuf[0x100];
3915
1.45k
  size_t    pinsize = 0;
3916
3917
3918
1.45k
  LOG_FUNC_CALLED(ctx);
3919
1.45k
  path = file? &file->path : NULL;
3920
3921
1.45k
  ident = get_pin_ident_name(type, reference);
3922
1.45k
  sc_log(ctx, "get and verify PIN('%s',type:0x%X,reference:0x%X)", ident, type, reference);
3923
3924
1.45k
  if (type == SC_AC_SEN)   {
3925
13
    r = sc_card_ctl(p15card->card, SC_CARDCTL_GET_CHV_REFERENCE_IN_SE, (void *)(&reference));
3926
13
    sc_log(ctx, "Card CTL(GET_CHV_REFERENCE_IN_SE) returned %i", r);
3927
13
    if (r > 0)   {
3928
0
      sc_log(ctx, "CHV(ref:%i) found in SE(ref:%i)", r, reference);
3929
0
      type = SC_AC_CHV;
3930
0
      reference = r;
3931
0
    }
3932
13
    else if (r != SC_ERROR_NOT_SUPPORTED)
3933
1
      LOG_TEST_RET(ctx, r, "Card CTL error: cannot get CHV reference");
3934
13
  }
3935
3936
1.45k
  memset(&auth_info, 0, sizeof(auth_info));
3937
1.45k
  auth_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
3938
1.45k
  auth_info.auth_method = type;
3939
1.45k
  auth_info.attrs.pin.reference = reference;
3940
3941
1.45k
  pin_id = sc_pkcs15init_get_pin_reference(p15card, profile, type, reference);
3942
1.45k
  sc_log(ctx, "found PIN reference %i", pin_id);
3943
1.45k
  if (type == SC_AC_SYMBOLIC) {
3944
76
    if (pin_id == -1)
3945
76
      LOG_FUNC_RETURN(ctx, SC_SUCCESS);
3946
35
    reference = pin_id;
3947
35
    type = SC_AC_CHV;
3948
35
    sc_log(ctx, "Symbolic PIN resolved to PIN(type:CHV,reference:%i)", reference);
3949
35
  }
3950
3951
1.41k
  if (path && path->len && path->len <= SC_MAX_PATH_SIZE) {
3952
1.27k
    struct sc_path tmp_path = *path;
3953
1.27k
    int iter;
3954
1.27k
    r = SC_ERROR_OBJECT_NOT_FOUND;
3955
4.15k
    for (iter = (int)tmp_path.len/2; iter >= 0 && r == SC_ERROR_OBJECT_NOT_FOUND; iter--, tmp_path.len -= 2) {
3956
2.88k
      r = sc_pkcs15_find_pin_by_type_and_reference(p15card,
3957
2.88k
          tmp_path.len ? &tmp_path : NULL,
3958
2.88k
          type, reference, &pin_obj);
3959
2.88k
    }
3960
1.27k
  }
3961
144
  else {
3962
144
    r = sc_pkcs15_find_pin_by_type_and_reference(p15card, NULL, type, reference, &pin_obj);
3963
144
  }
3964
3965
1.41k
  if (!r && pin_obj)   {
3966
272
    memcpy(&auth_info, pin_obj->data, sizeof(auth_info));
3967
272
    sc_log(ctx, "found PIN object '%.*s'", (int) sizeof pin_obj->label, pin_obj->label);
3968
272
  }
3969
3970
1.41k
  if (pin_obj)   {
3971
272
    sc_log(ctx,
3972
272
           "PIN object '%.*s'; pin_obj->content.len:%"SC_FORMAT_LEN_SIZE_T"u",
3973
272
           (int) sizeof pin_obj->label, pin_obj->label,
3974
272
           pin_obj->content.len);
3975
272
    if (pin_obj->content.value && pin_obj->content.len)   {
3976
8
      if (pin_obj->content.len > sizeof(pinbuf))
3977
8
        LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "PIN buffer is too small");
3978
8
      memcpy(pinbuf, pin_obj->content.value, pin_obj->content.len);
3979
8
      pinsize = pin_obj->content.len;
3980
8
      sc_log(ctx, "'ve got '%s' value from cache", ident);
3981
8
      goto found;
3982
8
    }
3983
272
  }
3984
3985
1.40k
  if (pin_obj && pin_obj->label[0])
3986
264
    label = pin_obj->label;
3987
3988
1.40k
  switch (type) {
3989
1.19k
  case SC_AC_CHV:
3990
1.19k
    if (callbacks.get_pin)   {
3991
0
      pinsize = sizeof(pinbuf);
3992
0
      r = callbacks.get_pin(profile, pin_id, &auth_info, label, pinbuf, &pinsize);
3993
0
      sc_log(ctx,
3994
0
             "'get_pin' callback returned %i; pinsize:%"SC_FORMAT_LEN_SIZE_T"u",
3995
0
             r, pinsize);
3996
0
    }
3997
1.19k
    break;
3998
40
  case SC_AC_SCB:
3999
65
  case SC_AC_PRO:
4000
65
    pinsize = 0;
4001
65
    r = 0;
4002
65
    break;
4003
150
  default:
4004
150
    pinsize = sizeof(pinbuf);
4005
150
    r = sc_pkcs15init_get_transport_key(profile, p15card, type, reference, pinbuf, &pinsize);
4006
150
    break;
4007
1.40k
  }
4008
4009
1.40k
  if (r == SC_ERROR_OBJECT_NOT_FOUND)   {
4010
928
    if (p15card->card->reader->capabilities & SC_READER_CAP_PIN_PAD)
4011
0
      r = 0, use_pinpad = 1;
4012
928
    else
4013
928
      r = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
4014
928
  }
4015
4016
1.40k
  LOG_TEST_RET(ctx, r, "Failed to get secret");
4017
339
  if (type == SC_AC_PRO)   {
4018
25
    sc_log(ctx, "No 'verify' for secure messaging");
4019
25
    LOG_FUNC_RETURN(ctx, r);
4020
25
  }
4021
4022
322
found:
4023
322
  if (pin_obj)   {
4024
    /*
4025
     * If pin cache is disabled or the reader is using pinpad, we can get here
4026
     * with no PIN data. This is ok as we can not asynchronously invoke the prompt
4027
     * (unless the pinpad is in use).
4028
     * In this case, check if the PIN has been already verified and
4029
     * the access condition is still open on card.
4030
     */
4031
272
    if (pinsize == 0) {
4032
264
      r = sc_pkcs15_get_pin_info(p15card, pin_obj);
4033
      /* update local copy of auth info */
4034
264
      memcpy(&auth_info, pin_obj->data, sizeof(auth_info));
4035
4036
264
      if (r == SC_SUCCESS && auth_info.logged_in & SC_PIN_STATE_LOGGED_IN)
4037
264
        LOG_FUNC_RETURN(ctx, r);
4038
264
    }
4039
4040
136
    r = sc_pkcs15_verify_pin(p15card, pin_obj, use_pinpad || pinsize == 0 ? NULL : pinbuf, use_pinpad ? 0 : pinsize);
4041
136
    LOG_TEST_RET(ctx, r, "Cannot validate pkcs15 PIN");
4042
136
  }
4043
4044
65
  if (file)   {
4045
65
    r = sc_select_file(p15card->card, &file->path, NULL);
4046
65
    LOG_TEST_RET(ctx, r, "Failed to select PIN path");
4047
65
  }
4048
4049
38
  if (!pin_obj) {
4050
24
    struct sc_pin_cmd_data pin_cmd;
4051
4052
24
    memset(&pin_cmd, 0, sizeof(pin_cmd));
4053
24
    pin_cmd.cmd = SC_PIN_CMD_VERIFY;
4054
24
    pin_cmd.pin_type = type;
4055
24
    pin_cmd.pin_reference = reference;
4056
24
    pin_cmd.pin1.data = use_pinpad ? NULL : pinbuf;
4057
24
    pin_cmd.pin1.len = use_pinpad ? 0: pinsize;
4058
4059
24
    r = sc_pin_cmd(p15card->card, &pin_cmd);
4060
24
    LOG_TEST_RET(ctx, r, "'VERIFY' pin cmd failed");
4061
24
  }
4062
4063
20
  LOG_FUNC_RETURN(ctx, r);
4064
20
}
4065
4066
4067
/*
4068
 * Present any authentication info as required by the file.
4069
 *
4070
 * Depending on the SC_CARD_CAP_USE_FCI_AC caps file in sc_card_t,
4071
 * we read the ACs of the file on the card, or rely on the ACL
4072
 * info for that file in the profile file.
4073
 *
4074
 * In the latter case, there's a problem here if e.g. the SO PIN
4075
 * defined by the profile is optional, and hasn't been set.
4076
 * On the other hands, some cards do not return access conditions
4077
 * in their response to SELECT FILE), so the latter case has been
4078
 * used in most cards while the first case was added much later.
4079
 */
4080
int
4081
sc_pkcs15init_authenticate(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
4082
    struct sc_file *file, int op)
4083
9.86k
{
4084
9.86k
  struct sc_context *ctx = p15card->card->ctx;
4085
9.86k
  const struct sc_acl_entry *acl = NULL;
4086
9.86k
  struct sc_file *file_tmp = NULL;
4087
9.86k
  int  r = 0;
4088
4089
9.86k
  LOG_FUNC_CALLED(ctx);
4090
9.86k
  if (file == NULL)
4091
0
    return SC_ERROR_INTERNAL;
4092
9.86k
  sc_log(ctx, "path '%s', op=%u", sc_print_path(&file->path), op);
4093
4094
9.86k
  if (file->acl_inactive) {
4095
2.86k
    sc_log(ctx, "access control mechanism is not active (always allowed)");
4096
2.86k
    LOG_FUNC_RETURN(ctx, r);
4097
2.86k
  }
4098
4099
6.99k
  if (p15card->card->caps & SC_CARD_CAP_USE_FCI_AC) {
4100
1.57k
    r = sc_select_file(p15card->card, &file->path, &file_tmp);
4101
1.57k
    LOG_TEST_RET(ctx, r, "Authentication failed: cannot select file.");
4102
4103
801
    acl = sc_file_get_acl_entry(file_tmp, op);
4104
801
  }
4105
5.42k
  else   {
4106
5.42k
    acl = sc_file_get_acl_entry(file, op);
4107
5.42k
  }
4108
6.22k
  sc_log(ctx, "acl %p",acl);
4109
4110
7.68k
  for (; r == 0 && acl; acl = acl->next) {
4111
2.90k
    if (acl->method == SC_AC_NEVER)   {
4112
34
      sc_file_free(file_tmp);
4113
34
      LOG_TEST_RET(ctx, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Authentication failed: never allowed");
4114
34
    }
4115
2.87k
    else if (acl->method == SC_AC_NONE)   {
4116
1.38k
      sc_log(ctx, "always allowed");
4117
1.38k
      break;
4118
1.38k
    }
4119
1.49k
    else if (acl->method == SC_AC_UNKNOWN)  {
4120
34
      sc_log(ctx, "unknown acl method");
4121
34
      break;
4122
34
    }
4123
1.45k
    sc_log(ctx, "verify acl(method:%i,reference:%i)", acl->method, acl->key_ref);
4124
1.45k
    r = sc_pkcs15init_verify_secret(profile, p15card, file_tmp ? file_tmp : file, acl->method, acl->key_ref);
4125
1.45k
  }
4126
4127
6.19k
  sc_file_free(file_tmp);
4128
4129
6.19k
  LOG_FUNC_RETURN(ctx, r);
4130
6.19k
}
4131
4132
4133
static int
4134
do_select_parent(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
4135
    struct sc_file *file, struct sc_file **parent)
4136
4.10k
{
4137
4.10k
  struct sc_context *ctx = p15card->card->ctx;
4138
4.10k
  struct sc_path  path;
4139
4.10k
  int   r;
4140
4141
4.10k
  LOG_FUNC_CALLED(ctx);
4142
  /* Get the parent's path */
4143
4.10k
  path = file->path;
4144
4.10k
  if (path.len >= 2)
4145
3.76k
    path.len -= 2;
4146
4.10k
  if (!path.len && !path.aid.len)
4147
1.18k
    sc_format_path("3F00", &path);
4148
4149
  /* Select the parent DF. */
4150
4.10k
  *parent = NULL;
4151
4.10k
  r = sc_select_file(p15card->card, &path, parent);
4152
  /* If DF doesn't exist, create it (unless it's the MF,
4153
   * but then something's badly broken anyway :-) */
4154
4.10k
  if (r == SC_ERROR_FILE_NOT_FOUND && path.len > 2) {
4155
320
    r = sc_profile_get_file_by_path(profile, &path, parent);
4156
320
    if (r < 0) {
4157
4
      sc_log(ctx, "no profile template for DF %s", sc_print_path(&path));
4158
4
      LOG_FUNC_RETURN(ctx, r);
4159
4
    }
4160
4161
316
    r = sc_pkcs15init_create_file(profile, p15card, *parent);
4162
316
    if (r < 0) {
4163
93
      sc_file_free(*parent);
4164
93
      *parent = NULL;
4165
93
    }
4166
316
    LOG_TEST_RET(ctx, r, "Cannot create parent DF");
4167
4168
223
    r = sc_select_file(p15card->card, &path, NULL);
4169
223
    if (r < 0) {
4170
43
      sc_file_free(*parent);
4171
43
      *parent = NULL;
4172
43
    }
4173
223
    LOG_TEST_RET(ctx, r, "Cannot select parent DF");
4174
223
  }
4175
3.78k
  else if (r == SC_SUCCESS && !strcmp(p15card->card->name, "STARCOS")) {
4176
    /* in case of starcos spk 2.3 SELECT FILE does not
4177
     * give us the ACLs => ask the profile */
4178
1
    sc_file_free(*parent);
4179
4180
1
    r = sc_profile_get_file_by_path(profile, &path, parent);
4181
1
    if (r < 0) {
4182
1
      sc_log(ctx, "in StarCOS profile there is no template for DF %s", sc_print_path(&path));
4183
1
      LOG_FUNC_RETURN(ctx, r);
4184
1
    }
4185
1
  }
4186
4187
3.96k
  LOG_FUNC_RETURN(ctx, r);
4188
3.96k
}
4189
4190
4191
int
4192
sc_pkcs15init_create_file(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
4193
    struct sc_file *file)
4194
4.10k
{
4195
4.10k
  struct sc_context *ctx = p15card->card->ctx;
4196
4.10k
  struct sc_file  *parent = NULL;
4197
4.10k
  int   r;
4198
4199
4.10k
  LOG_FUNC_CALLED(ctx);
4200
4.10k
  if (!file) {
4201
0
    return SC_ERROR_INVALID_ARGUMENTS;
4202
0
  }
4203
4204
4.10k
  sc_log(ctx, "create file '%s'", sc_print_path(&file->path));
4205
  /* Select parent DF and verify PINs/key as necessary */
4206
4.10k
  r = do_select_parent(profile, p15card, file, &parent);
4207
4.10k
  LOG_TEST_RET(ctx, r, "Cannot create file: select parent error");
4208
4209
3.13k
  r = sc_pkcs15init_authenticate(profile, p15card, parent, SC_AC_OP_CREATE);
4210
3.13k
  LOG_TEST_GOTO_ERR(ctx, r, "Cannot create file: 'CREATE' authentication failed");
4211
4212
  /* Fix up the file's ACLs */
4213
2.87k
  r = sc_pkcs15init_fixup_file(profile, p15card, file);
4214
2.87k
  LOG_TEST_GOTO_ERR(ctx, r, "Cannot create file: file fixup failed");
4215
4216
  /* ensure we are in the correct lifecycle */
4217
2.86k
  r = sc_pkcs15init_set_lifecycle(p15card->card, SC_CARDCTRL_LIFECYCLE_ADMIN);
4218
2.86k
  if (r != SC_ERROR_NOT_SUPPORTED)
4219
2.86k
    LOG_TEST_GOTO_ERR(ctx, r, "Cannot create file: failed to set lifecycle 'ADMIN'");
4220
4221
2.85k
  r = sc_create_file(p15card->card, file);
4222
2.85k
  LOG_TEST_GOTO_ERR(ctx, r, "Create file failed");
4223
4224
3.13k
err:
4225
3.13k
  sc_file_free(parent);
4226
3.13k
  LOG_FUNC_RETURN(ctx, r);
4227
3.13k
}
4228
4229
4230
int
4231
sc_pkcs15init_update_file(struct sc_profile *profile,
4232
    struct sc_pkcs15_card *p15card, struct sc_file *file,
4233
    void *data, size_t datalen)
4234
3.66k
{
4235
3.66k
  struct sc_context *ctx = p15card->card->ctx;
4236
3.66k
  struct sc_file  *selected_file = NULL;
4237
3.66k
  void    *copy = NULL;
4238
3.66k
  int   r, need_to_zap = 0;
4239
4240
3.66k
  LOG_FUNC_CALLED(ctx);
4241
3.66k
  if (!file)
4242
3.66k
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
4243
4244
3.59k
  sc_log(ctx, "path:%s; datalen:%zu", sc_print_path(&file->path), datalen);
4245
4246
3.59k
  r = sc_select_file(p15card->card, &file->path, &selected_file);
4247
3.59k
  if (!r)   {
4248
1.19k
    need_to_zap = 1;
4249
1.19k
  }
4250
2.40k
  else if (r == SC_ERROR_FILE_NOT_FOUND)   {
4251
    /* Create file if it doesn't exist */
4252
1.92k
    if (file->size < datalen)
4253
653
      file->size = datalen;
4254
4255
1.92k
    r = sc_pkcs15init_create_file(profile, p15card, file);
4256
1.92k
    LOG_TEST_RET(ctx, r, "Failed to create file");
4257
4258
1.36k
    r = sc_select_file(p15card->card, &file->path, &selected_file);
4259
1.36k
    LOG_TEST_RET(ctx, r, "Failed to select newly created file");
4260
1.36k
  }
4261
478
  else   {
4262
478
    LOG_TEST_RET(ctx, r, "Failed to select file");
4263
478
  }
4264
4265
2.43k
  if (selected_file->size < datalen) {
4266
81
    sc_log(ctx,
4267
81
           "File %s too small (require %zu, have %"SC_FORMAT_LEN_SIZE_T"u)",
4268
81
           sc_print_path(&file->path), datalen,
4269
81
           selected_file->size);
4270
81
    sc_file_free(selected_file);
4271
81
    LOG_TEST_RET(ctx, SC_ERROR_FILE_TOO_SMALL, "Update file failed");
4272
81
  }
4273
2.35k
  else if (selected_file->size > datalen && need_to_zap) {
4274
    /* zero out the rest of the file - we may have shrunk
4275
     * the file contents */
4276
1.10k
    if (selected_file->size > MAX_FILE_SIZE) {
4277
23
      sc_file_free(selected_file);
4278
23
      LOG_FUNC_RETURN(ctx, SC_ERROR_INTERNAL);
4279
23
    }
4280
4281
1.08k
    copy = calloc(1, selected_file->size);
4282
1.08k
    if (copy == NULL) {
4283
0
      sc_file_free(selected_file);
4284
0
      return SC_ERROR_OUT_OF_MEMORY;
4285
0
    }
4286
1.08k
    memcpy(copy, data, datalen);
4287
1.08k
    datalen = selected_file->size;
4288
1.08k
    data = copy;
4289
1.08k
  }
4290
4291
  /* Present authentication info needed */
4292
2.33k
  r = sc_pkcs15init_authenticate(profile, p15card, selected_file, SC_AC_OP_UPDATE);
4293
2.33k
  if (r >= 0 && datalen)
4294
1.41k
    r = sc_update_binary(p15card->card, 0, (const unsigned char *) data, datalen, 0);
4295
4296
2.33k
  if (copy)
4297
1.08k
    free(copy);
4298
2.33k
  sc_file_free(selected_file);
4299
2.33k
  LOG_FUNC_RETURN(ctx, r);
4300
2.33k
}
4301
4302
/*
4303
 * Fix up a file's ACLs by replacing all occurrences of a symbolic
4304
 * PIN name with the real reference.
4305
 */
4306
static int
4307
sc_pkcs15init_fixup_acls(struct sc_pkcs15_card *p15card, struct sc_file *file,
4308
    struct sc_acl_entry *so_acl, struct sc_acl_entry *user_acl)
4309
1.30k
{
4310
1.30k
  struct sc_context *ctx = p15card->card->ctx;
4311
1.30k
  unsigned int  op;
4312
1.30k
  int   r = 0;
4313
4314
1.30k
  LOG_FUNC_CALLED(ctx);
4315
40.1k
  for (op = 0; r == 0 && op < SC_MAX_AC_OPS; op++) {
4316
38.9k
    struct sc_acl_entry acls[SC_MAX_OP_ACS];
4317
38.9k
    const struct sc_acl_entry *acl;
4318
38.9k
    const char  *what;
4319
38.9k
    int   added = 0, num, ii;
4320
4321
    /* First, get original ACLs */
4322
38.9k
    acl = sc_file_get_acl_entry(file, op);
4323
77.8k
    for (num = 0; num < SC_MAX_OP_ACS && acl; num++, acl = acl->next)
4324
38.9k
      acls[num] = *acl;
4325
4326
38.9k
    sc_file_clear_acl_entries(file, op);
4327
77.8k
    for (ii = 0; ii < num; ii++) {
4328
38.9k
      acl = acls + ii;
4329
38.9k
      if (acl->method != SC_AC_SYMBOLIC)
4330
35.7k
        goto next;
4331
4332
3.18k
      if (acl->key_ref == SC_PKCS15INIT_SO_PIN) {
4333
1.20k
        acl = so_acl;
4334
1.20k
        what = "SO PIN";
4335
1.20k
      }
4336
1.97k
      else if (acl->key_ref == SC_PKCS15INIT_USER_PIN) {
4337
1.91k
        acl = user_acl;
4338
1.91k
        what = "user PIN";
4339
1.91k
      }
4340
61
      else {
4341
61
        sc_log(ctx, "ACL references unknown symbolic PIN %d", acl->key_ref);
4342
61
        return SC_ERROR_INVALID_ARGUMENTS;
4343
61
      }
4344
4345
      /* If we weren't given a replacement ACL,
4346
       * leave the original ACL untouched */
4347
3.11k
      if (acl->key_ref == (unsigned int)-1) {
4348
0
        sc_log(ctx, "ACL references %s, which is not defined", what);
4349
0
        return SC_ERROR_INVALID_ARGUMENTS;
4350
0
      }
4351
4352
3.11k
      if (acl->method == SC_AC_NONE)
4353
734
        continue;
4354
38.1k
    next:
4355
38.1k
      sc_file_add_acl_entry(file, op, acl->method, acl->key_ref);
4356
38.1k
      added++;
4357
38.1k
    }
4358
38.8k
    if (!added)
4359
734
      sc_file_add_acl_entry(file, op, SC_AC_NONE, 0);
4360
38.8k
  }
4361
4362
1.24k
  LOG_FUNC_RETURN(ctx, r);
4363
1.24k
}
4364
4365
4366
/*
4367
 * Fix up all file ACLs
4368
 */
4369
int
4370
sc_pkcs15init_fixup_file(struct sc_profile *profile,
4371
    struct sc_pkcs15_card *p15card, struct sc_file *file)
4372
5.24k
{
4373
5.24k
  struct sc_context *ctx = profile->card->ctx;
4374
5.24k
  struct sc_acl_entry so_acl, user_acl;
4375
5.24k
  unsigned int  op, needfix = 0;
4376
5.24k
  int   rv, pin_ref;
4377
4378
5.24k
  LOG_FUNC_CALLED(ctx);
4379
  /* First, loop over all ACLs to find out whether there
4380
   * are still any symbolic references.
4381
   */
4382
167k
  for (op = 0; op < SC_MAX_AC_OPS; op++) {
4383
162k
    const struct sc_acl_entry *acl;
4384
4385
162k
    acl = sc_file_get_acl_entry(file, op);
4386
324k
    for (; acl; acl = acl->next)
4387
162k
      if (acl->method == SC_AC_SYMBOLIC)
4388
3.27k
        needfix++;
4389
162k
  }
4390
4391
5.24k
  if (!needfix)
4392
5.24k
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
4393
4394
1.30k
  pin_ref = sc_pkcs15init_get_pin_reference(p15card, profile, SC_AC_SYMBOLIC, SC_PKCS15INIT_SO_PIN);
4395
1.30k
  if (pin_ref < 0) {
4396
367
    so_acl.method = SC_AC_NONE;
4397
367
    so_acl.key_ref = 0;
4398
367
  }
4399
941
  else {
4400
941
    so_acl.method = SC_AC_CHV;
4401
941
    so_acl.key_ref = pin_ref;
4402
941
  }
4403
4404
1.30k
  pin_ref = sc_pkcs15init_get_pin_reference(p15card, profile, SC_AC_SYMBOLIC, SC_PKCS15INIT_USER_PIN);
4405
1.30k
  if (pin_ref < 0) {
4406
416
    user_acl.method = SC_AC_NONE;
4407
416
    user_acl.key_ref = 0;
4408
416
  }
4409
892
  else {
4410
892
    user_acl.method = SC_AC_CHV;
4411
892
    user_acl.key_ref = pin_ref;
4412
892
  }
4413
1.30k
  sc_log(ctx, "so_acl(method:%X,ref:%X), user_acl(method:%X,ref:%X)",
4414
1.30k
      so_acl.method, so_acl.key_ref, user_acl.method, user_acl.key_ref);
4415
4416
1.30k
  rv = sc_pkcs15init_fixup_acls(p15card, file, &so_acl, &user_acl);
4417
4418
1.30k
  LOG_FUNC_RETURN(ctx, rv);
4419
1.30k
}
4420
4421
4422
static int
4423
sc_pkcs15init_get_pin_path(struct sc_pkcs15_card *p15card,
4424
    struct sc_pkcs15_id *auth_id, struct sc_path *path)
4425
56
{
4426
56
  struct sc_pkcs15_object *obj;
4427
56
  int r;
4428
4429
56
  r = sc_pkcs15_find_pin_by_auth_id(p15card, auth_id, &obj);
4430
56
  if (r < 0)
4431
35
    return r;
4432
21
  *path = ((struct sc_pkcs15_auth_info *) obj->data)->path;
4433
21
  return SC_SUCCESS;
4434
56
}
4435
4436
4437
int
4438
sc_pkcs15init_get_pin_info(struct sc_profile *profile, int id, struct sc_pkcs15_auth_info *pin)
4439
16.0k
{
4440
16.0k
  sc_profile_get_pin_info(profile, id, pin);
4441
16.0k
  return SC_SUCCESS;
4442
16.0k
}
4443
4444
4445
int
4446
sc_pkcs15init_get_manufacturer(struct sc_profile *profile, const char **res)
4447
0
{
4448
0
  *res = profile->p15_spec->tokeninfo->manufacturer_id;
4449
0
  return SC_SUCCESS;
4450
0
}
4451
4452
int
4453
sc_pkcs15init_get_serial(struct sc_profile *profile, const char **res)
4454
0
{
4455
0
  *res = profile->p15_spec->tokeninfo->serial_number;
4456
0
  return SC_SUCCESS;
4457
0
}
4458
4459
4460
int
4461
sc_pkcs15init_set_serial(struct sc_profile *profile, const char *serial)
4462
163
{
4463
163
  if (profile->p15_spec->tokeninfo->serial_number)
4464
163
    free(profile->p15_spec->tokeninfo->serial_number);
4465
163
  profile->p15_spec->tokeninfo->serial_number = strdup(serial);
4466
4467
163
  return SC_SUCCESS;
4468
163
}
4469
4470
4471
/*
4472
 * Card specific sanity check procedure.
4473
 */
4474
int
4475
sc_pkcs15init_sanity_check(struct sc_pkcs15_card *p15card, struct sc_profile *profile)
4476
5.59k
{
4477
5.59k
  struct sc_context *ctx = p15card->card->ctx;
4478
5.59k
  int rv = SC_ERROR_NOT_SUPPORTED;
4479
4480
5.59k
  LOG_FUNC_CALLED(ctx);
4481
5.59k
  if (profile->ops->sanity_check)
4482
421
    rv = profile->ops->sanity_check(profile, p15card);
4483
4484
5.59k
  LOG_FUNC_RETURN(ctx, rv);
4485
5.59k
}
4486
4487
4488
static int
4489
sc_pkcs15init_qualify_pin(struct sc_card *card, const char *pin_name,
4490
    size_t pin_len, struct sc_pkcs15_auth_info *auth_info)
4491
9.80k
{
4492
9.80k
  struct sc_context *ctx = card->ctx;
4493
9.80k
  struct sc_pkcs15_pin_attributes *pin_attrs;
4494
4495
9.80k
  LOG_FUNC_CALLED(ctx);
4496
9.80k
  if (auth_info == NULL)
4497
9.80k
    LOG_FUNC_RETURN(ctx, SC_ERROR_OBJECT_NOT_FOUND);
4498
4499
9.80k
  if (pin_len == 0 || auth_info->auth_type != SC_PKCS15_PIN_AUTH_TYPE_PIN)
4500
9.80k
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
4501
4502
9.58k
  pin_attrs = &auth_info->attrs.pin;
4503
4504
9.58k
  if (pin_len < pin_attrs->min_length) {
4505
13
    sc_log(ctx,
4506
13
           "%s too short (min length %"SC_FORMAT_LEN_SIZE_T"u)",
4507
13
           pin_name, pin_attrs->min_length);
4508
13
    LOG_FUNC_RETURN(ctx, SC_ERROR_WRONG_LENGTH);
4509
13
  }
4510
9.57k
  if (pin_len > pin_attrs->max_length) {
4511
6.19k
    sc_log(ctx,
4512
6.19k
           "%s too long (max length %"SC_FORMAT_LEN_SIZE_T"u)",
4513
6.19k
           pin_name, pin_attrs->max_length);
4514
6.19k
    LOG_FUNC_RETURN(ctx, SC_ERROR_WRONG_LENGTH);
4515
6.19k
  }
4516
4517
3.37k
  LOG_FUNC_RETURN(ctx, SC_SUCCESS);
4518
3.37k
}
4519
4520
4521
/*
4522
 * Get the list of options from the card, if it specifies them
4523
 */
4524
static int
4525
sc_pkcs15init_read_info(struct sc_card *card, struct sc_profile *profile)
4526
13.8k
{
4527
13.8k
  struct sc_path  path;
4528
13.8k
  struct sc_file  *file = NULL;
4529
13.8k
  unsigned char *mem = NULL;
4530
13.8k
  size_t    len = 0;
4531
13.8k
  int   r;
4532
4533
13.8k
  sc_format_path(OPENSC_INFO_FILEPATH, &path);
4534
13.8k
  r = sc_select_file(card, &path, &file);
4535
13.8k
  if (r >= 0) {
4536
1.03k
    len = file->size;
4537
1.03k
    sc_file_free(file);
4538
1.03k
    if (len > MAX_FILE_SIZE)
4539
24
      return SC_ERROR_INTERNAL;
4540
1.01k
    mem = malloc(len);
4541
1.01k
    if (mem != NULL)
4542
1.01k
      r = sc_read_binary(card, 0, mem, len, 0);
4543
0
    else
4544
0
      r = SC_ERROR_OUT_OF_MEMORY;
4545
1.01k
  }
4546
12.8k
  else   {
4547
12.8k
    r = 0;
4548
12.8k
    sc_file_free(file);
4549
12.8k
  }
4550
4551
13.8k
  if (r >= 0)
4552
13.5k
    r = sc_pkcs15init_parse_info(card, mem, r, profile);
4553
4554
13.8k
  if (mem)
4555
1.01k
    free(mem);
4556
13.8k
  return r;
4557
13.8k
}
4558
4559
4560
static int
4561
set_info_string(char **strp, const u8 *p, size_t len)
4562
918
{
4563
918
  char  *s;
4564
4565
918
  if (!(s = malloc(len+1)))
4566
0
    return SC_ERROR_OUT_OF_MEMORY;
4567
918
  memcpy(s, p, len);
4568
918
  s[len] = '\0';
4569
918
  if (*strp)
4570
687
    free(*strp);
4571
918
  *strp = s;
4572
918
  return SC_SUCCESS;
4573
918
}
4574
4575
/*
4576
 * Parse OpenSC Info file. We rudely clobber any information
4577
 * given on the command line.
4578
 *
4579
 * passed is a pointer (p) to (len) bytes. Those bytes contain
4580
 * one or several tag-length-value constructs, where tag and
4581
 * length are both single bytes. a final 0x00 or 0xff byte
4582
 * (with or without len byte) is ok.
4583
 */
4584
static int
4585
sc_pkcs15init_parse_info(struct sc_card *card,
4586
    const unsigned char *p, size_t len, struct sc_profile *profile)
4587
13.5k
{
4588
13.5k
  unsigned char tag;
4589
13.5k
  const unsigned char *end;
4590
13.5k
  unsigned int  nopts = 0;
4591
13.5k
  size_t    n;
4592
13.5k
  int r = 0;
4593
4594
13.5k
  if ((p == NULL) || (len == 0))
4595
13.3k
    return 0;
4596
4597
232
  end = p + (len - 1);
4598
1.49k
  while (p < end) { /* more bytes to look at */
4599
1.47k
    r = 0;
4600
4601
1.47k
    tag = *p; p++;
4602
1.47k
    if ((tag == 0) || (tag == 0xff) || (p >= end))
4603
151
      break;
4604
4605
1.31k
    n = *p;
4606
1.31k
    p++;
4607
4608
1.31k
    if (p >= end || p + n > end) { /* invalid length byte n */
4609
58
      r = SC_ERROR_PKCS15INIT;
4610
58
      goto error;
4611
58
    }
4612
4613
1.26k
    switch (tag) {
4614
687
    case OPENSC_INFO_TAG_PROFILE:
4615
687
      r = set_info_string(&profile->name, p, n);
4616
687
      if (r < 0)
4617
0
        goto error;
4618
687
      break;
4619
687
    case OPENSC_INFO_TAG_OPTION:
4620
232
      if (nopts >= SC_PKCS15INIT_MAX_OPTIONS - 1) {
4621
1
        sc_log(card->ctx, "Too many options in OpenSC Info file");
4622
1
        r = SC_ERROR_PKCS15INIT;
4623
1
        goto error;
4624
1
      }
4625
231
      r = set_info_string(&profile->options[nopts], p, n);
4626
231
      if (r < 0)
4627
0
        goto error;
4628
231
      profile->options[++nopts] = NULL;
4629
231
      break;
4630
342
    default:
4631
342
      /* Unknown options ignored */ ;
4632
1.26k
    }
4633
1.26k
    p += n;
4634
1.26k
  }
4635
173
  return 0;
4636
4637
59
error:
4638
59
  sc_log(card->ctx, "OpenSC info file corrupted");
4639
59
  if (profile->name) {
4640
59
    free(profile->name);
4641
59
    profile->name = NULL;
4642
59
  }
4643
100
  for (size_t i = 0; i < nopts; i++) {
4644
41
    if (profile->options[i])
4645
41
      free(profile->options[i]);
4646
41
    profile->options[i] = NULL;
4647
41
  }
4648
59
  return r;
4649
232
}
4650
4651
4652
static int
4653
do_encode_string(unsigned char **memp, unsigned char *end,
4654
    unsigned char tag, const char *s)
4655
95
{
4656
95
  unsigned char *p = *memp;
4657
95
  size_t  n;
4658
4659
95
  n = s ? strlen(s) : 0;
4660
95
  if (n > 255)
4661
0
    return SC_ERROR_BUFFER_TOO_SMALL;
4662
95
  if (p + 2 + n > end)
4663
0
    return SC_ERROR_BUFFER_TOO_SMALL;
4664
95
  *p++ = tag;
4665
95
  *p++ = n;
4666
95
  memcpy(p, s, n);
4667
95
  *memp = p + n;
4668
95
  return 0;
4669
95
}
4670
4671
4672
static int
4673
sc_pkcs15init_write_info(struct sc_pkcs15_card *p15card,
4674
    struct sc_profile *profile,
4675
    struct sc_pkcs15_object *pin_obj)
4676
95
{
4677
95
  struct sc_file  *file = NULL, *df = profile->df_info->file;
4678
95
  unsigned char buffer[128], *p, *end;
4679
95
  unsigned int  method;
4680
95
  unsigned long key_ref;
4681
95
  int   n, r;
4682
4683
95
  if (profile->ops->emu_write_info)
4684
0
    return profile->ops->emu_write_info(profile, p15card, pin_obj);
4685
4686
95
  memset(buffer, 0, sizeof(buffer));
4687
4688
95
  file = sc_file_new();
4689
95
  file->path.type = SC_PATH_TYPE_PATH;
4690
95
  memcpy(file->path.value, df->path.value, df->path.len);
4691
95
  file->path.len = df->path.len;
4692
95
  sc_append_file_id(&file->path, OPENSC_INFO_FILEID);
4693
95
  file->type = SC_FILE_TYPE_WORKING_EF;
4694
95
  file->ef_structure = SC_FILE_EF_TRANSPARENT;
4695
95
  file->id = OPENSC_INFO_FILEID;
4696
95
  file->size = sizeof(buffer);
4697
4698
95
  if (pin_obj != NULL) {
4699
95
    method = SC_AC_CHV;
4700
95
    key_ref = ((struct sc_pkcs15_auth_info *) pin_obj->data)->attrs.pin.reference;
4701
95
  }
4702
0
  else {
4703
0
    method = SC_AC_NONE; /* Unprotected */
4704
0
    key_ref = 0;
4705
0
  }
4706
3.04k
  for (n = 0; n < SC_MAX_AC_OPS; n++) {
4707
2.94k
    if (n == SC_AC_OP_READ)
4708
95
      sc_file_add_acl_entry(file, n, SC_AC_NONE, 0);
4709
2.85k
    else
4710
2.85k
      sc_file_add_acl_entry(file, n, method, key_ref);
4711
2.94k
  }
4712
4713
95
  p = buffer;
4714
95
  end = buffer + sizeof(buffer);
4715
4716
95
  r = do_encode_string(&p, end, OPENSC_INFO_TAG_PROFILE, profile->name);
4717
95
  for (n = 0; r >= 0 && profile->options[n]; n++)
4718
0
    r = do_encode_string(&p, end, OPENSC_INFO_TAG_OPTION, profile->options[n]);
4719
4720
95
  if (r >= 0)
4721
95
    r = sc_pkcs15init_update_file(profile, p15card, file, buffer, (unsigned int)file->size);
4722
4723
95
  sc_file_free(file);
4724
95
  return r;
4725
95
}