Coverage Report

Created: 2026-03-01 06:54

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
11.0k
#define OPENSC_INFO_FILEPATH    "3F0050154946"
72
180
#define OPENSC_INFO_FILEID    0x4946
73
3.82k
#define OPENSC_INFO_TAG_PROFILE   0x01
74
228
#define OPENSC_INFO_TAG_OPTION    0x02
75
76
/* Default ID for new key/pin */
77
18.1k
#define DEFAULT_ID      0x45
78
5.23k
#define DEFAULT_PIN_FLAGS   (SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE)
79
4.72k
#define DEFAULT_PRKEY_FLAGS   (SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE)
80
24
#define DEFAULT_PUBKEY_FLAGS    (SC_PKCS15_CO_FLAG_MODIFIABLE)
81
13.3k
#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
4.46k
#define DEFAULT_DATA_FLAGS    (SC_PKCS15_CO_FLAG_MODIFIABLE)
84
85
21.8k
#define TEMPLATE_INSTANTIATE_MIN_INDEX  0x0
86
25.2k
#define TEMPLATE_INSTANTIATE_MAX_INDEX  0xFE
87
88
/* Maximal number of access conditions that can be defined for one card operation. */
89
139k
#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
999
{
177
999
  struct sc_ec_parameters *ecparams = (struct sc_ec_parameters *)ptr;
178
999
  if (ecparams) {
179
999
    sc_clear_ec_params(ecparams);
180
999
    free(ecparams);
181
999
  }
182
999
}
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
6.42k
{
429
6.42k
  int r;
430
6.42k
  struct sc_context *ctx = profile->card->ctx;
431
432
6.42k
  LOG_FUNC_CALLED(ctx);
433
6.42k
  sc_log(ctx, "Pksc15init Unbind: %i:%p:%i", profile->dirty, profile->p15_data, profile->pkcs15.do_last_update);
434
6.42k
  if (profile->dirty != 0 && profile->p15_data != NULL && profile->pkcs15.do_last_update) {
435
939
    r = sc_pkcs15init_update_lastupdate(profile->p15_data, profile);
436
939
    if (r < 0)
437
443
      sc_log(ctx, "Failed to update TokenInfo: %s", sc_strerror(r));
438
939
  }
439
6.42k
  sc_profile_free(profile);
440
6.42k
}
441
442
443
void
444
sc_pkcs15init_set_p15card(struct sc_profile *profile, struct sc_pkcs15_card *p15card)
445
4.46k
{
446
4.46k
  struct sc_context *ctx = p15card->card->ctx;
447
4.46k
  struct sc_pkcs15_object *p15objects[10];
448
4.46k
  int i, r, nn_objs;
449
450
4.46k
  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
4.46k
  nn_objs = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_AUTH_PIN, p15objects, 10);
455
5.32k
  for (i = 0; i < nn_objs; i++) {
456
858
    struct sc_pkcs15_auth_info *auth_info = (struct sc_pkcs15_auth_info *) p15objects[i]->data;
457
858
    struct sc_pkcs15_pin_attributes *pin_attrs = &auth_info->attrs.pin;
458
858
    struct sc_file *file = NULL;
459
460
858
    if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN)
461
66
      continue;
462
792
    if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN)
463
399
      continue;
464
393
    if (!auth_info->path.len)
465
376
      continue;
466
467
17
    r = sc_profile_get_file_by_path(profile, &auth_info->path, &file);
468
17
                if (r == SC_ERROR_FILE_NOT_FOUND)   {
469
14
      if (!sc_select_file(p15card->card, &auth_info->path, &file))   {
470
4
        char pin_name[16];
471
472
4
        sprintf(pin_name, "pin-dir-%02X%02X", file->path.value[file->path.len - 2],
473
4
            file->path.value[file->path.len - 1]);
474
4
        sc_log(ctx, "add '%s' to profile file list", pin_name);
475
4
        sc_profile_add_file(profile, pin_name, file);
476
4
      }
477
14
    }
478
479
17
    sc_file_free(file);
480
17
  }
481
482
4.46k
  profile->p15_data = p15card;
483
4.46k
  sc_log(ctx, "sc_pkcs15init_set_p15card() returns");
484
4.46k
}
485
486
487
/*
488
 * Set the card's lifecycle
489
 */
490
int
491
sc_pkcs15init_set_lifecycle(struct sc_card *card, int lcycle)
492
14.3k
{
493
14.3k
  return sc_card_ctl(card, SC_CARDCTL_LIFECYCLE_SET, &lcycle);
494
14.3k
}
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
4.46k
{
504
4.46k
  struct sc_context *ctx = NULL;
505
4.46k
  int rv;
506
507
4.46k
  if (!p15card)
508
0
    return SC_ERROR_INVALID_ARGUMENTS;
509
510
4.46k
  ctx = p15card->card->ctx;
511
4.46k
  LOG_FUNC_CALLED(ctx);
512
  /* Needs the 'SOPIN' AUTH pkcs15 object.
513
   * So that, SOPIN can be found by it's reference. */
514
4.46k
  if (sc_pkcs15_bind(p15card->card, aid, &p15card) >= 0)
515
914
    profile->p15_data = p15card;
516
517
4.46k
  if (profile->ops->erase_card == NULL)
518
4.46k
    LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
519
520
3.99k
  rv = profile->ops->erase_card(profile, p15card);
521
522
3.99k
  LOG_FUNC_RETURN(ctx, rv);
523
3.99k
}
524
525
526
int
527
sc_pkcs15init_erase_card_recursively(struct sc_pkcs15_card *p15card,
528
    struct sc_profile *profile)
529
182
{
530
182
  struct sc_file  *df = profile->df_info->file, *dir;
531
182
  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
182
  if (sc_profile_get_file(profile, "DIR", &dir) >= 0) {
541
11
    r = sc_pkcs15init_rmdir(p15card, profile, dir);
542
11
    sc_file_free(dir);
543
11
    if (r < 0 && r != SC_ERROR_FILE_NOT_FOUND)   {
544
9
      sc_free_apps(p15card->card);
545
9
      return r;
546
9
    }
547
11
  }
548
549
173
  r = sc_select_file(p15card->card, &df->path, &df);
550
173
  if (r >= 0) {
551
22
    r = sc_pkcs15init_rmdir(p15card, profile, df);
552
22
    sc_file_free(df);
553
22
  }
554
173
  if (r == SC_ERROR_FILE_NOT_FOUND)
555
1
    r = 0;
556
557
173
  sc_free_apps(p15card->card);
558
173
  return r;
559
182
}
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.47k
{
566
1.47k
  struct sc_context *ctx = p15card->card->ctx;
567
1.47k
  struct sc_file *parent = NULL, *file = NULL;
568
1.47k
  struct sc_path path;
569
1.47k
  int rv;
570
  /*int file_type = SC_FILE_TYPE_DF;*/
571
572
1.47k
  LOG_FUNC_CALLED(ctx);
573
1.47k
  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.47k
  path = *file_path;
584
1.47k
  rv = sc_select_file(p15card->card, &path, &file);
585
1.47k
  LOG_TEST_RET(ctx, rv, "cannot select file to delete");
586
587
489
  if (sc_file_get_acl_entry(file, SC_AC_OP_DELETE_SELF))   {
588
0
    sc_log(ctx, "Found 'DELETE-SELF' acl");
589
0
    rv = sc_pkcs15init_authenticate(profile, p15card, file, SC_AC_OP_DELETE_SELF);
590
0
    sc_file_free(file);
591
0
  }
592
489
  else if (sc_file_get_acl_entry(file, SC_AC_OP_DELETE))   {
593
178
    sc_log(ctx, "Found 'DELETE' acl");
594
178
          rv = sc_pkcs15init_authenticate(profile, p15card, file, SC_AC_OP_DELETE);
595
178
    sc_file_free(file);
596
178
  }
597
311
  else    {
598
311
    sc_log(ctx, "Try to get the parent's 'DELETE' access");
599
    /*file_type = file->type;*/
600
311
    if (file_path->len >= 2) {
601
      /* Select the parent DF */
602
272
      path.len -= 2;
603
272
      rv = sc_select_file(p15card->card, &path, &parent);
604
272
      if (rv < 0)
605
44
        sc_file_free(file);
606
272
      LOG_TEST_RET(ctx, rv, "Cannot select parent");
607
608
228
      rv = sc_pkcs15init_authenticate(profile, p15card, parent, SC_AC_OP_DELETE);
609
228
      sc_file_free(parent);
610
228
      sc_file_free(file);
611
228
      LOG_TEST_RET(ctx, rv, "parent 'DELETE' authentication failed");
612
228
    }
613
39
    else {
614
      /* No 'DELETE' ACL of the file and not deleted for parent */
615
39
      rv = SC_ERROR_INVALID_ARGUMENTS;
616
39
      sc_file_free(file);
617
39
    }
618
311
  }
619
433
  LOG_TEST_RET(ctx, rv, "'DELETE' authentication failed");
620
621
  /* Reselect file to delete: current path could be changed by 'verify PIN' procedure */
622
338
  path = *file_path;
623
338
  rv = sc_select_file(p15card->card, &path, &file);
624
338
  LOG_TEST_RET(ctx, rv, "cannot select file to delete");
625
626
265
  memset(&path, 0, sizeof(path));
627
265
  path.type = SC_PATH_TYPE_FILE_ID;
628
265
  if (file_path->len < 2) {
629
2
    sc_file_free(file);
630
2
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
631
2
  }
632
263
  path.value[0] = file_path->value[file_path->len - 2];
633
263
  path.value[1] = file_path->value[file_path->len - 1];
634
263
  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
263
  sc_log(ctx, "Now really delete file");
645
263
  rv = sc_delete_file(p15card->card, &path);
646
263
  sc_file_free(file);
647
263
  LOG_FUNC_RETURN(ctx, rv);
648
263
}
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
34
{
660
34
  struct sc_context *ctx = p15card->card->ctx;
661
34
  unsigned char buffer[1024];
662
34
  struct sc_path  path;
663
34
  struct sc_file  *file, *parent;
664
34
  int   r = 0, nfids;
665
666
34
  if (df == NULL)
667
0
    return SC_ERROR_INTERNAL;
668
34
  sc_log(ctx, "sc_pkcs15init_rmdir(%s)", sc_print_path(&df->path));
669
670
34
  if (df->type == SC_FILE_TYPE_DF) {
671
21
    r = sc_pkcs15init_authenticate(profile, p15card, df, SC_AC_OP_LIST_FILES);
672
21
    if (r < 0)
673
1
      return r;
674
20
    r = sc_list_files(p15card->card, buffer, sizeof(buffer));
675
20
    if (r < 0)
676
14
      return r;
677
678
6
    path = df->path;
679
6
    path.len += 2;
680
6
    if (path.len > SC_MAX_PATH_SIZE)
681
1
      return SC_ERROR_INTERNAL;
682
683
5
    nfids = r / 2;
684
6
    while (r >= 0 && nfids--) {
685
4
      path.value[path.len-2] = buffer[2*nfids];
686
4
      path.value[path.len-1] = buffer[2*nfids+1];
687
4
      r = sc_select_file(p15card->card, &path, &file);
688
4
      if (r < 0) {
689
3
        if (r == SC_ERROR_FILE_NOT_FOUND)
690
0
          continue;
691
3
        break;
692
3
      }
693
1
      r = sc_pkcs15init_rmdir(p15card, profile, file);
694
1
      sc_file_free(file);
695
1
    }
696
697
5
    if (r < 0)
698
4
      return r;
699
5
  }
700
701
  /* Select the parent DF */
702
14
  path = df->path;
703
14
  if (path.len <= 2)
704
6
    return SC_ERROR_INVALID_ARGUMENTS;
705
8
  path.len -= 2;
706
8
  r = sc_select_file(p15card->card, &path, &parent);
707
8
  if (r < 0)
708
4
    return r;
709
710
4
  r = sc_pkcs15init_authenticate(profile, p15card, df, SC_AC_OP_DELETE);
711
4
  if (r < 0) {
712
2
    sc_file_free(parent);
713
2
    return r;
714
2
  }
715
2
  r = sc_pkcs15init_authenticate(profile, p15card, parent, SC_AC_OP_DELETE);
716
2
  sc_file_free(parent);
717
2
  if (r < 0)
718
1
    return r;
719
720
1
  memset(&path, 0, sizeof(path));
721
1
  path.type = SC_PATH_TYPE_FILE_ID;
722
1
  path.value[0] = df->id >> 8;
723
1
  path.value[1] = df->id & 0xFF;
724
1
  path.len = 2;
725
726
  /* ensure that the card is in the correct lifecycle */
727
1
  r = sc_pkcs15init_set_lifecycle(p15card->card, SC_CARDCTRL_LIFECYCLE_ADMIN);
728
1
  if (r < 0 && r != SC_ERROR_NOT_SUPPORTED)
729
1
    return r;
730
731
0
  r = sc_delete_file(p15card->card, &path);
732
0
  return r;
733
1
}
734
735
736
int
737
sc_pkcs15init_finalize_card(struct sc_card *card, struct sc_profile *profile)
738
4.46k
{
739
4.46k
  if (profile->ops->finalize_card == NULL)
740
3.20k
    return SC_ERROR_NOT_SUPPORTED;
741
1.26k
  return profile->ops->finalize_card(card);
742
4.46k
}
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
6.42k
{
782
6.42k
  struct sc_context *ctx = card->ctx;
783
6.42k
  struct sc_pkcs15_card *p15card = profile->p15_spec;
784
6.42k
  struct sc_pkcs15_auth_info pin_ainfo, puk_ainfo;
785
6.42k
  struct sc_pkcs15_pin_attributes *pin_attrs = &pin_ainfo.attrs.pin;
786
6.42k
  struct sc_pkcs15_object *pin_obj = NULL;
787
6.42k
  struct sc_app_info  *app;
788
6.42k
  struct sc_file    *df = profile->df_info->file;
789
6.42k
  int     r = SC_SUCCESS;
790
6.42k
  int     has_so_pin = args->so_pin_len != 0;
791
792
6.42k
  LOG_FUNC_CALLED(ctx);
793
6.42k
  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
6.42k
  p15card->opts.use_pin_cache = 1;
800
801
6.42k
  if (card->app_count >= SC_MAX_CARD_APPS)
802
6.42k
    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
6.42k
  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
6.42k
  if (has_so_pin) {
813
6.42k
    const char  *pin_label;
814
815
6.42k
    if (args->so_pin_len) {
816
6.42k
      sc_profile_get_pin_info(profile, SC_PKCS15INIT_SO_PIN, &pin_ainfo);
817
6.42k
      r = sc_pkcs15init_qualify_pin(card, "SO PIN", args->so_pin_len, &pin_ainfo);
818
6.42k
      LOG_TEST_RET(ctx, r, "Failed to qualify SO PIN");
819
6.42k
    }
820
821
    /* Path encoded only for local SO PIN */
822
1.67k
    if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_LOCAL)
823
1.43k
      pin_ainfo.path = df->path;
824
825
    /* Select the PIN reference */
826
1.67k
    if (profile->ops->select_pin_reference) {
827
1.54k
      r = profile->ops->select_pin_reference(profile, p15card, &pin_ainfo);
828
1.54k
      LOG_TEST_RET(ctx, r, "Failed to select card specific PIN reference");
829
1.54k
    }
830
831
1.38k
    sc_profile_get_pin_info(profile, SC_PKCS15INIT_SO_PUK, &puk_ainfo);
832
1.38k
    r = sc_pkcs15init_qualify_pin(card, "SO PUK", args->so_puk_len, &puk_ainfo);
833
1.38k
    LOG_TEST_RET(ctx, r, "Failed to qualify SO PUK");
834
835
1.13k
    if (!(pin_label = args->so_pin_label)) {
836
1.13k
      if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN)
837
257
        pin_label = "Security Officer PIN";
838
876
      else
839
876
        pin_label = "User PIN";
840
1.13k
    }
841
842
1.13k
    if (args->so_puk_len == 0)
843
178
      pin_attrs->flags |= SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED;
844
845
1.13k
    pin_obj = sc_pkcs15init_new_object(SC_PKCS15_TYPE_AUTH_PIN, pin_label, NULL, &pin_ainfo);
846
1.13k
    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.13k
      sc_log(ctx, "Add virtual SO_PIN('%.*s',flags:%X,reference:%i,path:'%s')", (int) sizeof pin_obj->label, pin_obj->label,
853
1.13k
          pin_attrs->flags, pin_attrs->reference, sc_print_path(&pin_ainfo.path));
854
855
1.13k
      r = sc_pkcs15_add_object(p15card, pin_obj);
856
1.13k
      LOG_TEST_GOTO_ERR(ctx, r, "Failed to add 'SOPIN' AUTH object");
857
1.13k
    }
858
1.13k
  }
859
860
  /* Perform card-specific initialization */
861
1.13k
  if (profile->ops->init_card)   {
862
912
    r = profile->ops->init_card(profile, p15card);
863
912
    if (r < 0 && pin_obj)   {
864
442
      sc_pkcs15_remove_object(p15card, pin_obj);
865
442
    }
866
912
    LOG_TEST_GOTO_ERR(ctx, r, "Card specific init failed");
867
912
  }
868
869
  /* Create the application directory */
870
691
  if (profile->ops->create_dir) {
871
619
    r = profile->ops->create_dir(profile, p15card, df);
872
619
    if (r < 0 && pin_obj)   {
873
411
      sc_pkcs15_remove_object(p15card, pin_obj);
874
411
    }
875
619
    LOG_TEST_GOTO_ERR(ctx, r, "Create 'DIR' error");
876
619
  }
877
878
  /* Store SO PIN */
879
280
  if (pin_obj && profile->ops->create_pin)
880
208
    r = profile->ops->create_pin(profile, p15card, df, pin_obj,
881
208
        args->so_pin, args->so_pin_len,
882
208
        args->so_puk, args->so_puk_len);
883
884
280
  if (pin_obj)
885
    /* Remove 'virtual' AUTH object . */
886
280
    sc_pkcs15_remove_object(p15card, pin_obj);
887
888
280
  LOG_TEST_GOTO_ERR(ctx, r, "Card specific create application DF failed");
889
890
  /* Store the PKCS15 information on the card */
891
199
  app = (struct sc_app_info *)calloc(1, sizeof(*app));
892
199
  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
199
  app->path = p15card->file_app->path;
898
199
  if (p15card->file_app->namelen <= SC_MAX_AID_SIZE) {
899
199
    app->aid.len = p15card->file_app->namelen;
900
199
    memcpy(app->aid.value, p15card->file_app->name, app->aid.len);
901
199
  }
902
903
  /* set serial number if explicitly specified */
904
199
  if (args->serial)   {
905
0
    sc_pkcs15init_set_serial(profile, args->serial);
906
0
  }
907
199
  else {
908
    /* otherwise try to get the serial number from the card */
909
199
    struct sc_serial_number serialnr;
910
911
199
    r = sc_card_ctl(card, SC_CARDCTL_GET_SERIALNR, &serialnr);
912
199
    if (r == SC_SUCCESS) {
913
95
      char hex_serial[SC_MAX_SERIALNR * 2 + 1];
914
915
95
      sc_bin_to_hex(serialnr.value, serialnr.len, hex_serial, sizeof(hex_serial), 0);
916
95
      sc_pkcs15init_set_serial(profile, hex_serial);
917
95
    }
918
199
  }
919
920
199
  if (args->label) {
921
0
    free(p15card->tokeninfo->label);
922
0
    p15card->tokeninfo->label = strdup(args->label);
923
0
  }
924
199
  if (p15card->tokeninfo->label)
925
199
    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
199
  r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_AODF, pin_obj);
931
199
  if (r >= 0) {
932
90
    r = sc_pkcs15init_update_dir(p15card, profile, app);
933
90
    if (r >= 0) {
934
33
      r = sc_pkcs15init_update_tokeninfo(p15card, profile);
935
57
    } else {
936
      /* FIXED: what to do if sc_pkcs15init_update_dir failed? */
937
      /* sc_pkcs15init_update_dir may add app to card->app[] */
938
57
      int found = 0;
939
57
      int i;
940
57
      for (i = 0; i < card->app_count; i++) {
941
31
        if (card->app[i] == app) {
942
31
          found = 1;
943
31
          break;
944
31
        }
945
31
      }
946
57
      if (found == 0) { /* not in card->app[] free it */
947
26
        free(app->label);
948
26
        free(app); /* unused */
949
26
      }
950
57
    }
951
90
  }
952
109
  else {
953
109
    free(app->label);
954
109
    free(app); /* unused */
955
109
    LOG_TEST_GOTO_ERR(ctx, r, "Failed to add pin object.");
956
109
  }
957
958
90
  sc_pkcs15init_write_info(p15card, profile, pin_obj);
959
90
  pin_obj = NULL;
960
961
1.13k
err:
962
1.13k
  sc_pkcs15_free_object(pin_obj);
963
1.13k
  LOG_FUNC_RETURN(ctx, r);
964
1.13k
}
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
4.46k
{
1043
4.46k
  struct sc_context *ctx = p15card->card->ctx;
1044
4.46k
  struct sc_pkcs15_object *pin_obj;
1045
4.46k
  struct sc_pkcs15_auth_info *auth_info;
1046
4.46k
  int     r;
1047
1048
4.46k
  LOG_FUNC_CALLED(ctx);
1049
  /* No auth_id given: select one */
1050
4.46k
  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
4.46k
  else   {
1065
    /* Make sure we don't get duplicate PIN IDs */
1066
4.46k
    r = sc_pkcs15_find_pin_by_auth_id(p15card, &args->auth_id, NULL);
1067
4.46k
    if (r != SC_ERROR_OBJECT_NOT_FOUND)
1068
4.46k
      LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "There already is a PIN with this ID.");
1069
4.46k
  }
1070
1071
4.08k
  pin_obj = sc_pkcs15init_new_object(SC_PKCS15_TYPE_AUTH_PIN, args->label, NULL, NULL);
1072
4.08k
  if (pin_obj == NULL)
1073
4.08k
    LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate PIN object");
1074
1075
4.08k
  auth_info = (struct sc_pkcs15_auth_info *) pin_obj->data;
1076
1077
4.08k
  sc_profile_get_pin_info(profile, SC_PKCS15INIT_USER_PIN, auth_info);
1078
4.08k
  if (auth_info == NULL)
1079
4.08k
    LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "Failed to retrieve auth_info");
1080
1081
4.08k
  auth_info->auth_id = args->auth_id;
1082
1083
  /* Now store the PINs */
1084
4.08k
  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
4.08k
  if (profile->ops->create_pin) {
1086
3.51k
    r = sc_pkcs15init_create_pin(p15card, profile, pin_obj, args);
1087
3.51k
    LOG_TEST_GOTO_ERR(ctx, r, "Card specific create PIN failed.");
1088
3.51k
  } else {
1089
568
    r = SC_ERROR_NOT_SUPPORTED;
1090
568
    LOG_TEST_GOTO_ERR(ctx, r, "Store PIN operation is not supported");
1091
568
  }
1092
1093
273
  r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_AODF, pin_obj);
1094
273
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to add PIN object");
1095
1096
23
  if (args->puk_id.len)
1097
0
    r = sc_pkcs15init_store_puk(p15card, profile, args);
1098
1099
23
  profile->dirty = 1;
1100
1101
23
  pin_obj = NULL;
1102
1103
4.08k
err:
1104
4.08k
  sc_pkcs15_free_object(pin_obj);
1105
4.08k
  LOG_FUNC_RETURN(ctx, r);
1106
4.08k
}
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
3.51k
{
1115
3.51k
  struct sc_context *ctx = p15card->card->ctx;
1116
3.51k
  struct sc_pkcs15_auth_info *auth_info = (struct sc_pkcs15_auth_info *) pin_obj->data;
1117
3.51k
  struct sc_pkcs15_pin_attributes *pin_attrs = &auth_info->attrs.pin;
1118
3.51k
  struct sc_file  *df = profile->df_info->file;
1119
3.51k
  int   r, retry = 0;
1120
1121
3.51k
  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
3.51k
  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
3.51k
  if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_LOCAL)
1136
3.46k
    auth_info->path = df->path;
1137
1138
  /* pin_info->reference = 0; */
1139
1140
  /* Loop until we come up with an acceptable pin reference */
1141
3.51k
  while (1) {
1142
3.51k
    if (profile->ops->select_pin_reference) {
1143
3.24k
      r = profile->ops->select_pin_reference(profile, p15card, auth_info);
1144
3.24k
      LOG_TEST_RET(ctx, r, "Card specific select PIN reference failed");
1145
1146
2.17k
      retry = 1;
1147
2.17k
    }
1148
1149
2.44k
    r = sc_pkcs15_find_pin_by_reference(p15card, &auth_info->path, pin_attrs->reference, NULL);
1150
2.44k
    if (r == SC_ERROR_OBJECT_NOT_FOUND)
1151
2.44k
      break;
1152
1153
2
    if (r != 0 || !retry)
1154
      /* Other error trying to retrieve pin obj */
1155
2
      LOG_TEST_RET(ctx, SC_ERROR_TOO_MANY_OBJECTS, "Failed to allocate PIN reference.");
1156
1157
2
    pin_attrs->reference++;
1158
2
  }
1159
1160
2.44k
  if (args->puk_len == 0)
1161
0
    pin_attrs->flags |= SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED;
1162
1163
2.44k
  sc_log(ctx, "create PIN with reference:%X, flags:%X, path:%s",
1164
2.44k
      pin_attrs->reference, pin_attrs->flags, sc_print_path(&auth_info->path));
1165
2.44k
  r = profile->ops->create_pin(profile, p15card,
1166
2.44k
      df, pin_obj,
1167
2.44k
      args->pin, args->pin_len,
1168
2.44k
      args->puk, args->puk_len);
1169
1170
2.44k
  if (df != profile->df_info->file)
1171
0
    sc_file_free(df);
1172
1173
2.44k
  LOG_FUNC_RETURN(ctx, r);
1174
2.44k
}
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
4.72k
{
1229
4.72k
  struct sc_context *ctx = p15card->card->ctx;
1230
4.72k
  struct sc_pkcs15_prkey_info *key_info = NULL;
1231
4.72k
  struct sc_pkcs15_keyinfo_gostparams *keyinfo_gostparams;
1232
4.72k
  struct sc_pkcs15_object *object = NULL;
1233
4.72k
  const char  *label;
1234
4.72k
  unsigned int  usage;
1235
4.72k
  int   r = 0, key_type;
1236
4.72k
  struct sc_ec_parameters *new_ecparams = NULL;
1237
1238
4.72k
  LOG_FUNC_CALLED(ctx);
1239
4.72k
  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
4.72k
  *res_obj = NULL;
1245
1246
4.72k
  if ((usage = keyargs->usage) == 0) {
1247
4.72k
    usage = SC_PKCS15_PRKEY_USAGE_SIGN;
1248
4.72k
    if (keyargs->x509_usage)
1249
0
      usage = sc_pkcs15init_map_usage(keyargs->x509_usage, 1);
1250
4.72k
  }
1251
1252
4.72k
  if ((label = keyargs->label) == NULL)
1253
4.72k
    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
4.72k
  key_type = key_pkcs15_algo(p15card, key->algorithm);
1259
4.72k
  r = key_type;
1260
4.72k
  LOG_TEST_GOTO_ERR(ctx, r, "Unsupported key type");
1261
1262
4.72k
  object = sc_pkcs15init_new_object(key_type, label, &keyargs->auth_id, NULL);
1263
4.72k
  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
4.72k
  key_info = (struct sc_pkcs15_prkey_info *) object->data;
1269
4.72k
  key_info->usage = usage;
1270
4.72k
  key_info->native = 1;
1271
4.72k
  key_info->key_reference = 0;
1272
4.72k
  key_info->modulus_length = keybits;
1273
4.72k
  key_info->access_flags = keyargs->access_flags;
1274
4.72k
  object->user_consent = keyargs->user_consent;
1275
  /* Path is selected below */
1276
1277
4.72k
  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
4.72k
  r = select_id(p15card, SC_PKCS15_TYPE_PRKEY, &keyargs->id);
1284
4.72k
  LOG_TEST_GOTO_ERR(ctx, r, "Cannot select ID for PrKey object");
1285
1286
4.72k
  key_info->id = keyargs->id;
1287
1288
4.72k
  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
4.72k
  } else if (key->algorithm == SC_ALGORITHM_EC ||
1302
3.64k
      key->algorithm == SC_ALGORITHM_EDDSA ||
1303
3.64k
      key->algorithm == SC_ALGORITHM_XEDDSA) {
1304
    /* keyargs->key.u.ec.params.der.value is allocated in keyargs, which is on stack */
1305
1.07k
    struct sc_ec_parameters *ecparams = &keyargs->key.u.ec.params;
1306
1307
1.07k
    new_ecparams = calloc(1, sizeof(struct sc_ec_parameters));
1308
1.07k
    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.07k
    r = sc_copy_ec_params(new_ecparams, &keyargs->key.u.ec.params);
1313
1.07k
    LOG_TEST_GOTO_ERR(ctx, r, "Cannot copy EC parameters");
1314
1315
1.07k
    key_info->params.data = new_ecparams;
1316
1.07k
    key_info->params.free_params = sc_pkcs15init_free_ec_params;
1317
1.07k
    key_info->field_length = ecparams->field_length;
1318
1.07k
    key_info->modulus_length = 0;
1319
1.07k
  }
1320
1321
4.72k
  r = select_object_path(p15card, profile, object, &key_info->path);
1322
4.72k
  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
4.57k
  if (profile->ops->select_key_reference) {
1326
2.26k
    while (1) {
1327
2.26k
      sc_log(ctx, "Look for usable key reference starting from %i", key_info->key_reference);
1328
2.26k
      r = profile->ops->select_key_reference(profile, p15card, key_info);
1329
2.26k
      LOG_TEST_GOTO_ERR(ctx, r, "Failed to select card specific key reference");
1330
1331
1.87k
      r = sc_pkcs15_find_prkey_by_reference(p15card, &key_info->path, key_info->key_reference, NULL);
1332
1.87k
      if (r == SC_ERROR_OBJECT_NOT_FOUND)   {
1333
1.87k
        sc_log(ctx, "Will use key reference %i", key_info->key_reference);
1334
1.87k
        break;
1335
1.87k
      }
1336
1337
0
      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
0
      key_info->key_reference++;
1344
0
    }
1345
2.26k
  }
1346
1347
4.17k
  *res_obj = object;
1348
4.17k
  object = NULL;
1349
4.17k
  new_ecparams = NULL;
1350
4.17k
  r = SC_SUCCESS;
1351
1352
4.72k
err:
1353
4.72k
  if (new_ecparams) {
1354
80
    sc_clear_ec_params(new_ecparams);
1355
80
    free(new_ecparams);
1356
80
    key_info->params.data = NULL;
1357
80
  }
1358
4.72k
  sc_pkcs15init_free_object(object);
1359
4.72k
  LOG_FUNC_RETURN(ctx, r);
1360
4.72k
}
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
13.3k
{
1369
13.3k
  struct sc_context *ctx = p15card->card->ctx;
1370
13.3k
  struct sc_pkcs15_skey_info *key_info;
1371
13.3k
  struct sc_pkcs15_object *object = NULL;
1372
13.3k
  const char  *label;
1373
13.3k
  unsigned int  usage;
1374
13.3k
  unsigned long keybits = keyargs->value_len;
1375
13.3k
  int   r = 0, key_type;
1376
1377
13.3k
  LOG_FUNC_CALLED(ctx);
1378
13.3k
  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
13.3k
  *res_obj = NULL;
1384
1385
13.3k
  if ((usage = keyargs->usage) == 0) {
1386
0
    usage = SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_DECRYPT;
1387
0
  }
1388
1389
13.3k
  if ((label = keyargs->label) == NULL)
1390
13.3k
    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
13.3k
  key_type = key_pkcs15_algo(p15card, keyargs->algorithm);
1396
13.3k
  r = key_type;
1397
13.3k
  LOG_TEST_GOTO_ERR(ctx, r, "Unsupported key type");
1398
1399
13.3k
  object = sc_pkcs15init_new_object(key_type, label, &keyargs->auth_id, NULL);
1400
13.3k
  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
13.3k
  key_info = (struct sc_pkcs15_skey_info *) object->data;
1406
13.3k
  key_info->usage = usage;
1407
13.3k
  key_info->native = 1;
1408
13.3k
  key_info->key_reference = 0;
1409
13.3k
  switch (keyargs->algorithm) {
1410
4.46k
  case SC_ALGORITHM_DES:
1411
4.46k
    key_info->key_type = CKK_DES;
1412
4.46k
    break;
1413
4.46k
  case SC_ALGORITHM_3DES:
1414
4.46k
    key_info->key_type = CKK_DES3;
1415
4.46k
    break;
1416
4.46k
  case SC_ALGORITHM_AES:
1417
4.46k
    key_info->key_type = CKK_AES;
1418
4.46k
    break;
1419
0
  default:
1420
0
    key_info->key_type = CKK_GENERIC_SECRET;
1421
0
    break;
1422
13.3k
  }
1423
13.3k
  key_info->value_len = keybits;
1424
13.3k
  key_info->access_flags = keyargs->access_flags;
1425
  /* Path is selected below */
1426
1427
13.3k
  if (keyargs->access_flags & SC_PKCS15_PRKEY_ACCESS_EXTRACTABLE) {
1428
13.3k
    key_info->access_flags &= ~SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE;
1429
13.3k
  }
1430
1431
13.3k
  if (keyargs->session_object > 0)
1432
0
      object->session_object = 1;
1433
1434
13.3k
  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
13.3k
  r = select_id(p15card, SC_PKCS15_TYPE_SKEY, &keyargs->id);
1439
13.3k
  LOG_TEST_GOTO_ERR(ctx, r, "Cannot select ID for SKey object");
1440
1441
13.3k
  key_info->id = keyargs->id;
1442
1443
13.3k
  r = select_object_path(p15card, profile, object, &key_info->path);
1444
13.3k
  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
12.9k
  if (profile->ops->select_key_reference) {
1448
6.53k
    r = SC_ERROR_NOT_SUPPORTED;
1449
6.53k
    LOG_TEST_GOTO_ERR(ctx, r, "SKey keyreference selection not supported");
1450
6.53k
  }
1451
1452
6.41k
  *res_obj = object;
1453
6.41k
  object = NULL;
1454
6.41k
  r = SC_SUCCESS;
1455
1456
13.3k
err:
1457
13.3k
  sc_pkcs15init_free_object(object);
1458
13.3k
  LOG_FUNC_RETURN(ctx, r);
1459
13.3k
}
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
4.17k
{
1465
4.17k
  struct sc_context *ctx = p15card->card->ctx;
1466
4.17k
  unsigned char flags = SC_MD_CONTAINER_MAP_VALID_CONTAINER;
1467
4.17k
  char gd[SC_MD_MAX_CONTAINER_NAME_LEN + 1];
1468
4.17k
  int rv;
1469
1470
4.17k
  LOG_FUNC_CALLED(ctx);
1471
1472
4.17k
  if(!guid || !guid_len)
1473
4.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
8.92k
{
1525
8.92k
  struct sc_context *ctx = p15card->card->ctx;
1526
8.92k
  struct sc_pkcs15init_pubkeyargs pubkey_args;
1527
8.92k
  struct sc_pkcs15_object *object = NULL;
1528
8.92k
  struct sc_pkcs15_prkey_info *key_info = NULL;
1529
8.92k
  struct sc_pkcs15_pubkey *pubkey = NULL;
1530
8.92k
  int r, caller_supplied_id = 0;
1531
8.92k
  unsigned long algorithm = keygen_args->prkey_args.key.algorithm;
1532
1533
8.92k
  LOG_FUNC_CALLED(ctx);
1534
1535
8.92k
  memset(&pubkey_args, 0, sizeof(pubkey_args));
1536
1537
  /* check supported key size */
1538
8.92k
  r = check_keygen_params_consistency(p15card->card,
1539
8.92k
    algorithm, &keygen_args->prkey_args,
1540
8.92k
    &keybits);
1541
8.92k
  LOG_TEST_GOTO_ERR(ctx, r, "Invalid key size");
1542
1543
4.79k
  if (check_key_compatibility(p15card, algorithm,
1544
4.79k
      &keygen_args->prkey_args.key, keygen_args->prkey_args.x509_usage,
1545
4.79k
      keybits, SC_ALGORITHM_ONBOARD_KEY_GEN) != SC_SUCCESS) {
1546
63
    r = SC_ERROR_NOT_SUPPORTED;
1547
63
    LOG_TEST_GOTO_ERR(ctx, r, "Cannot generate key with the given parameters");
1548
63
  }
1549
1550
4.72k
  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
4.72k
  if (keygen_args->prkey_args.id.len)   {
1556
969
    caller_supplied_id = 1;
1557
1558
    /* Make sure that private key's ID is the unique inside the PKCS#15 application */
1559
969
    r = sc_pkcs15_find_prkey_by_id(p15card, &keygen_args->prkey_args.id, NULL);
1560
969
    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
966
    else if (r != SC_ERROR_OBJECT_NOT_FOUND) {
1565
0
      LOG_TEST_GOTO_ERR(ctx, r, "Find private key error");
1566
0
    }
1567
969
  }
1568
1569
  /* Set up the PrKDF object */
1570
4.72k
  r = sc_pkcs15init_init_prkdf(p15card, profile, &keygen_args->prkey_args,
1571
4.72k
    &keygen_args->prkey_args.key, keybits, &object);
1572
4.72k
  LOG_TEST_GOTO_ERR(ctx, r, "Set up private key object error");
1573
1574
4.17k
  key_info = (struct sc_pkcs15_prkey_info *) object->data;
1575
1576
4.17k
  r = _pkcd15init_set_aux_md_data(p15card, &key_info->aux_data,
1577
4.17k
      keygen_args->prkey_args.guid, keygen_args->prkey_args.guid_len);
1578
4.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
4.17k
  pubkey_args.id = keygen_args->prkey_args.id;
1584
4.17k
  pubkey_args.label = keygen_args->pubkey_label ? keygen_args->pubkey_label : object->label;
1585
4.17k
  pubkey_args.usage = keygen_args->prkey_args.usage;
1586
4.17k
  pubkey_args.x509_usage = keygen_args->prkey_args.x509_usage;
1587
4.17k
  pubkey_args.key.algorithm = algorithm;
1588
1589
4.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
4.17k
  } else if (algorithm == SC_ALGORITHM_EC ||
1594
3.17k
      algorithm == SC_ALGORITHM_EDDSA ||
1595
3.17k
      algorithm == SC_ALGORITHM_XEDDSA) {
1596
999
    r = sc_copy_ec_params(&pubkey_args.key.u.ec.params, &keygen_args->prkey_args.key.u.ec.params);
1597
999
    LOG_TEST_GOTO_ERR(ctx, r, "Cannot allocate EC parameters");
1598
999
  }
1599
1600
  /* Generate the private key on card */
1601
4.17k
  r = profile->ops->create_key(profile, p15card, object);
1602
4.17k
  LOG_TEST_GOTO_ERR(ctx, r, "Cannot generate key: create key failed");
1603
1604
2.31k
  r = profile->ops->generate_key(profile, p15card, object, &pubkey_args.key);
1605
2.31k
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to generate key");
1606
1607
  /* update PrKDF entry */
1608
52
  if (!caller_supplied_id)   {
1609
26
    struct sc_pkcs15_id iid;
1610
1611
    /* Caller not supplied ID, so,
1612
     * if intrinsic ID can be calculated -- overwrite the native one */
1613
26
    memset(&iid, 0, sizeof(iid));
1614
26
    r = sc_pkcs15init_select_intrinsic_id(p15card, profile, SC_PKCS15_TYPE_PUBKEY, &iid, &pubkey_args.key);
1615
26
    LOG_TEST_GOTO_ERR(ctx, r, "Select intrinsic ID error");
1616
1617
26
    if (iid.len)
1618
6
      key_info->id = iid;
1619
26
  }
1620
52
  pubkey = &pubkey_args.key;
1621
52
  if (!pubkey->alg_id)   {
1622
52
    pubkey->alg_id = calloc(1, sizeof(struct sc_algorithm_id));
1623
52
    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
52
    sc_init_oid(&pubkey->alg_id->oid);
1629
52
    pubkey->alg_id->algorithm = pubkey->algorithm;
1630
52
  }
1631
1632
52
  pubkey_args.id = key_info->id;
1633
52
  r = sc_pkcs15_encode_pubkey(ctx, pubkey, &object->content.value, &object->content.len);
1634
52
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to encode public key");
1635
1636
50
  r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_PRKDF, object);
1637
50
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to add generated private key object");
1638
1639
24
  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
24
  r = sc_pkcs15init_store_public_key(p15card, profile, &pubkey_args, NULL);
1649
24
  if (r < 0)
1650
18
    sc_pkcs15_remove_object(p15card, object);
1651
24
  LOG_TEST_GOTO_ERR(ctx, r, "Failed to store public key");
1652
1653
6
  if (res_obj)
1654
0
    *res_obj = object;
1655
6
  object = NULL;
1656
1657
6
  profile->dirty = 1;
1658
1659
8.92k
err:
1660
8.92k
  sc_pkcs15_free_object(object);
1661
8.92k
  sc_pkcs15_erase_pubkey(&pubkey_args.key);
1662
8.92k
  LOG_FUNC_RETURN(ctx, r);
1663
8.92k
}
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
13.3k
{
1672
13.3k
  struct sc_context *ctx = p15card->card->ctx;
1673
13.3k
  struct sc_pkcs15_object *object = NULL;
1674
13.3k
  unsigned int keybits = (unsigned int)skey_args->value_len;
1675
13.3k
  int r;
1676
1677
13.3k
  LOG_FUNC_CALLED(ctx);
1678
  /* check supported key size */
1679
13.3k
  r = check_keygen_params_consistency(p15card->card, skey_args->algorithm, NULL, &keybits);
1680
13.3k
  LOG_TEST_RET(ctx, r, "Invalid key size");
1681
1682
520
  if (check_key_compatibility(p15card, skey_args->algorithm, NULL, 0,
1683
520
      keybits, SC_ALGORITHM_ONBOARD_KEY_GEN) != SC_SUCCESS)
1684
520
    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
24
{
1837
24
  struct sc_context *ctx = p15card->card->ctx;
1838
24
  struct sc_pkcs15_object *object = NULL;
1839
24
  struct sc_pkcs15_pubkey_info *key_info;
1840
24
  struct sc_pkcs15_keyinfo_gostparams *keyinfo_gostparams;
1841
24
  struct sc_pkcs15_pubkey key;
1842
24
  struct sc_path  *path;
1843
24
  const char  *label;
1844
24
  unsigned int  type = 0;
1845
24
  unsigned int usage;
1846
24
  size_t keybits;
1847
24
  int   r;
1848
1849
24
  LOG_FUNC_CALLED(ctx);
1850
24
  if (!keyargs)
1851
24
    LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Store public key aborted");
1852
1853
  /* Create shallow a copy of the key first */
1854
24
  key = keyargs->key;
1855
1856
  /* Copy algorithm id structure */
1857
24
  if (keyargs->key.alg_id) {
1858
24
    key.alg_id = calloc(1, sizeof(struct sc_algorithm_id));
1859
24
    if (!key.alg_id)
1860
24
      LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Can not allocate memory for algorithm id");
1861
1862
24
    key.alg_id->algorithm = keyargs->key.alg_id->algorithm;
1863
24
    memcpy(&key.alg_id->oid, &keyargs->key.alg_id->oid, sizeof(struct sc_object_id));
1864
24
  }
1865
1866
  /* Copy algorithm related parameters */
1867
24
  switch (key.algorithm) {
1868
10
  case SC_ALGORITHM_RSA:
1869
10
    key.u.rsa.modulus.data = NULL;
1870
10
    key.u.rsa.exponent.data = NULL;
1871
    // copy RSA params
1872
10
    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
10
    memcpy(key.u.rsa.modulus.data, keyargs->key.u.rsa.modulus.data, keyargs->key.u.rsa.modulus.len);
1877
10
    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
10
    memcpy(key.u.rsa.exponent.data, keyargs->key.u.rsa.exponent.data, keyargs->key.u.rsa.exponent.len);
1882
10
    keybits = sc_pkcs15init_keybits(&key.u.rsa.modulus);
1883
10
    type = SC_PKCS15_TYPE_PUBKEY_RSA;
1884
10
    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
24
  }
1918
1919
24
  if ((usage = keyargs->usage) == 0) {
1920
24
    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
24
    } else {
1924
24
      sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Setting default usage to verify");
1925
24
      usage = SC_PKCS15_PRKEY_USAGE_VERIFY;
1926
24
    }
1927
24
    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
24
  }
1932
24
  sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Usage: 0x%X", usage);
1933
1934
24
  label = keyargs->label;
1935
24
  if (!label)
1936
0
    label = "Public Key";
1937
1938
  /* Set up the pkcs15 object. */
1939
24
  object = sc_pkcs15init_new_object(type, label, &keyargs->auth_id, NULL);
1940
24
  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
24
  key_info = (struct sc_pkcs15_pubkey_info *) object->data;
1946
24
  key_info->usage = usage;
1947
24
  key_info->id = keyargs->id;
1948
1949
24
  if (key.algorithm == SC_ALGORITHM_RSA) {
1950
10
    key_info->modulus_length = keybits;
1951
14
  } 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
24
  r = sc_pkcs15init_select_intrinsic_id(p15card, profile, SC_PKCS15_TYPE_PUBKEY, &keyargs->id, &key);
1996
24
  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
24
  r = select_id(p15card, SC_PKCS15_TYPE_PUBKEY, &keyargs->id);
2001
24
  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
24
  r = sc_pkcs15_find_pubkey_by_id(p15card, &keyargs->id, NULL);
2005
24
  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
24
  } else if (r != SC_ERROR_OBJECT_NOT_FOUND)  {
2009
0
    LOG_TEST_GOTO_ERR(ctx, r, "Find public key error");
2010
0
  }
2011
2012
24
  key_info->id = keyargs->id;
2013
2014
  /* DER encode public key components */
2015
24
  r = sc_pkcs15_encode_pubkey(p15card->card->ctx, &key, &object->content.value, &object->content.len);
2016
24
  LOG_TEST_GOTO_ERR(ctx, r, "Encode public key error");
2017
2018
24
  r = sc_pkcs15_encode_pubkey(p15card->card->ctx, &key, &key_info->direct.raw.value, &key_info->direct.raw.len);
2019
24
  LOG_TEST_GOTO_ERR(ctx, r, "RAW encode public key error");
2020
2021
  /* EC key are encoded as SPKI to preserve domain parameter */
2022
24
  r = sc_pkcs15_encode_pubkey_as_spki(p15card->card->ctx, &key, &key_info->direct.spki.value, &key_info->direct.spki.len);
2023
24
  LOG_TEST_GOTO_ERR(ctx, r, "SPKI encode public key error");
2024
2025
  /* Now create key file and store key */
2026
24
  if (type == SC_PKCS15_TYPE_PUBKEY_EC ||
2027
10
      type == SC_PKCS15_TYPE_PUBKEY_EDDSA ||
2028
10
      type == SC_PKCS15_TYPE_PUBKEY_XEDDSA)
2029
14
    r = sc_pkcs15init_store_data(p15card, profile, object, &key_info->direct.spki, &key_info->path);
2030
10
  else
2031
10
    r = sc_pkcs15init_store_data(p15card, profile, object, &object->content, &key_info->path);
2032
2033
24
  path = &key_info->path;
2034
24
  if (path->count == 0) {
2035
5
    path->index = 0;
2036
5
    path->count = -1;
2037
5
  }
2038
2039
  /* Update the PuKDF */
2040
24
  if (r >= 0)
2041
11
    r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_PUKDF, object);
2042
24
  LOG_TEST_GOTO_ERR(ctx, r, "Add object error");
2043
2044
6
  if (r >= 0 && res_obj)
2045
0
    *res_obj = object;
2046
6
  object = NULL;
2047
2048
6
  profile->dirty = 1;
2049
2050
24
err:
2051
24
  sc_pkcs15_erase_pubkey(&key);
2052
24
  sc_pkcs15_free_object(object);
2053
24
  LOG_FUNC_RETURN(ctx, r);
2054
24
}
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
13.3k
{
2064
13.3k
  struct sc_context *ctx = p15card->card->ctx;
2065
13.3k
  struct sc_pkcs15_object *object = NULL;
2066
13.3k
  int r = 0;
2067
2068
13.3k
  LOG_FUNC_CALLED(ctx);
2069
2070
  /* Now check whether the card is able to handle this key */
2071
13.3k
  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
12.8k
    if (!(keyargs->access_flags & SC_PKCS15_PRKEY_ACCESS_EXTRACTABLE))
2075
12.8k
      LOG_TEST_RET(ctx, SC_ERROR_INCOMPATIBLE_KEY, "Card does not support this key for crypto. Cannot store it as non extractable.");
2076
12.8k
  }
2077
2078
13.3k
#ifdef ENABLE_OPENSSL
2079
13.3k
  if (!keyargs->id.len) {
2080
    /* Calculating intrinsic Key ID for secret key does not make
2081
     * sense - just generate random one */
2082
4.46k
    if (RAND_bytes(keyargs->id.value, 20) == 1)
2083
4.46k
      keyargs->id.len = 20;
2084
4.46k
  }
2085
13.3k
#endif
2086
2087
  /* Make sure that secret key's ID is the unique inside the PKCS#15 application */
2088
13.3k
  r = sc_pkcs15_find_skey_by_id(p15card, &keyargs->id, NULL);
2089
13.3k
  if (!r)
2090
13.3k
    LOG_TEST_RET(ctx, SC_ERROR_NON_UNIQUE_ID, "Non unique ID of the secret key object");
2091
13.3k
  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
13.3k
  r = sc_pkcs15init_init_skdf(p15card, profile, keyargs, &object);
2096
13.3k
  LOG_TEST_RET(ctx, r, "Failed to initialize secret key object");
2097
2098
6.41k
  if (profile->ops->create_key)
2099
6.41k
    r = profile->ops->create_key(profile, p15card, object);
2100
6.41k
  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
1.75k
  if (keyargs->key.data_len > 0) {
2105
1.75k
    if (profile->ops->store_key) {
2106
1.75k
      struct sc_pkcs15_prkey key;
2107
1.75k
      memset(&key, 0, sizeof(key));
2108
1.75k
      key.algorithm = keyargs->algorithm;
2109
1.75k
      key.u.secret = keyargs->key;
2110
1.75k
      r = profile->ops->store_key(profile, p15card, object, &key);
2111
1.75k
    }
2112
1.75k
  }
2113
1.75k
  LOG_TEST_GOTO_ERR(ctx, r, "Card specific 'store key' failed");
2114
2115
66
  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
66
  if (!object->session_object) {
2123
66
    r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_SKDF, object);
2124
66
    LOG_TEST_GOTO_ERR(ctx, r, "Failed to add new secret key PKCS#15 object");
2125
66
  }
2126
2127
4
  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
4
  if (r >= 0 && res_obj)
2135
0
    *res_obj = object;
2136
4
  object = NULL;
2137
2138
4
  profile->dirty = 1;
2139
2140
6.41k
err:
2141
6.41k
  sc_pkcs15_free_object(object);
2142
6.41k
  LOG_FUNC_RETURN(ctx, r);
2143
6.41k
}
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
4.46k
{
2263
4.46k
  struct sc_context *ctx = p15card->card->ctx;
2264
4.46k
  struct sc_pkcs15_data_info *data_object_info;
2265
4.46k
  struct sc_pkcs15_object *object;
2266
4.46k
  struct sc_pkcs15_object *objs[32];
2267
4.46k
  const char  *label;
2268
4.46k
  int   r, i;
2269
4.46k
  unsigned int    tid = 0x01;
2270
2271
4.46k
  LOG_FUNC_CALLED(ctx);
2272
4.46k
  if (!profile)
2273
4.46k
    LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Missing profile");
2274
4.46k
  label = args->label;
2275
2276
4.46k
  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
4.46k
    r = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_DATA_OBJECT, objs, 32);
2282
4.46k
    LOG_TEST_RET(ctx, r, "Get 'DATA' objects error");
2283
2284
4.47k
    for (i = 0; i < r; i++) {
2285
6
      unsigned char cid;
2286
6
      struct sc_pkcs15_data_info *cinfo = (struct sc_pkcs15_data_info *) objs[i]->data;
2287
6
      if (!cinfo->path.len)
2288
0
        continue;
2289
6
      cid = cinfo->path.value[cinfo->path.len - 1];
2290
6
      if (cid >= tid)
2291
4
        tid = cid + 1;
2292
6
    }
2293
4.46k
    if (tid > 0xff)
2294
      /* too many data objects ... */
2295
1
      return SC_ERROR_TOO_MANY_OBJECTS;
2296
4.46k
    args->id.len = 1;
2297
4.46k
    args->id.value[0] = tid;
2298
4.46k
  }
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
4.46k
  object = sc_pkcs15init_new_object(SC_PKCS15_TYPE_DATA_OBJECT, label, &args->auth_id, NULL);
2307
4.46k
  if (object == NULL)
2308
0
    return SC_ERROR_OUT_OF_MEMORY;
2309
2310
4.46k
  data_object_info = (struct sc_pkcs15_data_info *) object->data;
2311
4.46k
  if (args->app_label != NULL)
2312
4.46k
    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
4.46k
  data_object_info->app_oid = args->app_oid;
2317
4.46k
  sc_der_copy(&data_object_info->data, &args->der_encoded);
2318
2319
4.46k
  r = sc_pkcs15init_store_data(p15card, profile, object, &args->der_encoded, &data_object_info->path);
2320
4.46k
  LOG_TEST_GOTO_ERR(ctx, r, "Store 'DATA' object error");
2321
2322
  /* Now update the DDF */
2323
348
  r = sc_pkcs15init_add_object(p15card, profile, SC_PKCS15_DODF, object);
2324
348
  LOG_TEST_GOTO_ERR(ctx, r, "'DODF' update error");
2325
2326
66
  if (r >= 0 && res_obj)
2327
0
    *res_obj = object;
2328
66
  object = NULL;
2329
2330
66
  profile->dirty = 1;
2331
2332
4.46k
err:
2333
4.46k
  sc_pkcs15_free_object(object);
2334
4.46k
  LOG_FUNC_RETURN(ctx, r);
2335
4.46k
}
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
3.56k
{
2342
3.56k
  struct sc_context *ctx = p15card->card->ctx;
2343
3.56k
  struct sc_pkcs15_auth_info auth_info;
2344
3.56k
  struct sc_pkcs15_object *auth_objs[0x10];
2345
3.56k
  int r, ii, nn_objs;
2346
2347
3.56k
  LOG_FUNC_CALLED(ctx);
2348
2349
  /* 1. Look for the corresponding pkcs15 PIN object. */
2350
2351
  /* Get all existing pkcs15 AUTH objects */
2352
3.56k
  r = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_AUTH_PIN, auth_objs, 0x10);
2353
3.56k
  LOG_TEST_RET(ctx, r, "Get PKCS#15 AUTH objects error");
2354
3.56k
  nn_objs = r;
2355
2356
3.56k
  sc_log(ctx, "found %i auth objects; looking for AUTH object(auth_method:%i,reference:%i)",
2357
3.56k
      nn_objs, auth_method, reference);
2358
4.98k
  for (ii=0; ii<nn_objs; ii++)   {
2359
2.56k
    struct sc_pkcs15_auth_info *auth_info = (struct sc_pkcs15_auth_info *)auth_objs[ii]->data;
2360
2.56k
    struct sc_pkcs15_pin_attributes *pin_attrs = &auth_info->attrs.pin;
2361
2362
2.56k
    sc_log(ctx, "check PIN(%.*s,auth_method:%i,type:%i,reference:%i,flags:%X)",
2363
2.56k
        (int) sizeof auth_objs[ii]->label, auth_objs[ii]->label, auth_info->auth_method, pin_attrs->type,
2364
2.56k
        pin_attrs->reference, pin_attrs->flags);
2365
    /* Find out if there is AUTH pkcs15 object with given 'type' and 'reference' */
2366
2.56k
    if (auth_info->auth_method == auth_method && pin_attrs->reference == reference)
2367
2.56k
      LOG_FUNC_RETURN(ctx, pin_attrs->reference);
2368
2369
2.36k
    if (auth_method != SC_AC_SYMBOLIC)
2370
232
      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.13k
    switch (reference)   {
2375
956
    case SC_PKCS15INIT_USER_PIN:
2376
956
      if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN)
2377
419
        continue;
2378
537
      if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN)
2379
15
        continue;
2380
522
      break;
2381
1.16k
    case SC_PKCS15INIT_SO_PIN:
2382
1.16k
      if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN)
2383
238
        continue;
2384
924
      if (!(pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN))
2385
506
        continue;
2386
418
      break;
2387
418
    case SC_PKCS15INIT_USER_PUK:
2388
10
      if (pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN)
2389
0
        continue;
2390
10
      if (!(pin_attrs->flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN))
2391
5
        continue;
2392
5
      break;
2393
6
    case SC_PKCS15INIT_SO_PUK:
2394
6
      if (!(pin_attrs->flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN))
2395
3
        continue;
2396
3
      if (!(pin_attrs->flags & SC_PKCS15_PIN_FLAG_SO_PIN))
2397
3
        continue;
2398
0
      break;
2399
1
    default:
2400
1
      LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid Symbolic PIN reference");
2401
2.13k
    }
2402
2403
945
    LOG_FUNC_RETURN(ctx, pin_attrs->reference);
2404
2405
945
  }
2406
2407
  /* 2. No existing pkcs15 PIN object
2408
   *  -- check if profile defines some PIN with 'reference' as PIN reference. */
2409
2.42k
  r = sc_profile_get_pin_id_by_reference(profile, auth_method, reference, &auth_info);
2410
2.42k
  if (r < 0)
2411
2.42k
    LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "PIN template not found");
2412
2413
1.25k
  LOG_FUNC_RETURN(ctx, auth_info.attrs.pin.reference);
2414
1.25k
}
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
4.48k
{
2422
4.48k
  struct sc_context *ctx = p15card->card->ctx;
2423
4.48k
  struct sc_file  *file = NULL;
2424
4.48k
  int   r;
2425
2426
4.48k
  LOG_FUNC_CALLED(ctx);
2427
2428
4.48k
  if (profile->ops->emu_store_data)   {
2429
1.09k
    r = profile->ops->emu_store_data(p15card, profile, object, data, path);
2430
1.09k
    if (r == SC_SUCCESS || r != SC_ERROR_NOT_IMPLEMENTED)
2431
1.09k
      LOG_FUNC_RETURN(ctx, r);
2432
1.09k
  }
2433
2434
3.72k
  r = select_object_path(p15card, profile, object, path);
2435
3.72k
  LOG_TEST_RET(ctx, r, "Failed to select object path");
2436
2437
3.58k
  r = sc_profile_get_file_by_path(profile, path, &file);
2438
3.58k
  LOG_TEST_RET(ctx, r, "Failed to get file by path");
2439
2440
1.41k
  if (file->path.count == 0) {
2441
127
    file->path.index = 0;
2442
127
    file->path.count = -1;
2443
127
  }
2444
2445
1.41k
  r = sc_pkcs15init_delete_by_path(profile, p15card, &file->path);
2446
1.41k
  if (r && r != SC_ERROR_FILE_NOT_FOUND) {
2447
835
    sc_file_free(file);
2448
835
    LOG_TEST_RET(ctx, r, "Cannot delete file");
2449
835
  }
2450
2451
577
  r = sc_pkcs15init_update_file(profile, p15card, file, data->value, data->len);
2452
2453
577
  *path = file->path;
2454
2455
577
  sc_file_free(file);
2456
577
  LOG_FUNC_RETURN(ctx, r);
2457
577
}
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
10
{
2516
10
  unsigned int  mask;
2517
10
  size_t bits;
2518
2519
10
  if (!bn || !bn->len)
2520
0
    return 0;
2521
10
  bits = bn->len << 3;
2522
28
  for (mask = 0x80; mask && !(bn->data[0] & mask); mask >>= 1)
2523
18
    bits--;
2524
10
  return bits;
2525
10
}
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
22.3k
{
2536
22.3k
  struct sc_context *ctx = card->ctx;
2537
22.3k
  int i, rv;
2538
2539
22.3k
  if (prkey && (alg == SC_ALGORITHM_EC ||
2540
4.46k
             alg == SC_ALGORITHM_EDDSA ||
2541
4.46k
             alg == SC_ALGORITHM_XEDDSA)) {
2542
4.46k
    struct sc_ec_parameters *ecparams = &prkey->key.u.ec.params;
2543
2544
4.46k
    rv = sc_pkcs15_fix_ec_parameters(ctx, ecparams);
2545
4.46k
    LOG_TEST_RET(ctx, rv, "Cannot fix EC parameters");
2546
2547
4.46k
    sc_log(ctx, "EC parameters: %s", sc_dump_hex(ecparams->der.value, ecparams->der.len));
2548
4.46k
    if (!*keybits)
2549
4.46k
      *keybits = (unsigned int)ecparams->field_length;
2550
4.46k
  }
2551
2552
102k
  for (i = 0; i < card->algorithm_count; i++) {
2553
85.6k
    struct sc_algorithm_info *info = &card->algorithms[i];
2554
2555
85.6k
    if (info->algorithm != alg)
2556
74.9k
      continue;
2557
2558
10.6k
    if (info->key_length != *keybits)
2559
5.34k
      continue;
2560
2561
5.31k
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
2562
5.31k
  }
2563
2564
17.0k
  if (prkey && (alg == SC_ALGORITHM_EC ||
2565
757
             alg == SC_ALGORITHM_EDDSA ||
2566
3.37k
             alg == SC_ALGORITHM_XEDDSA)) {
2567
    /* allocated in sc_pkcs15_fix_ec_parameters */
2568
3.37k
    free(prkey->key.u.ec.params.der.value);
2569
3.37k
    prkey->key.u.ec.params.der.value = NULL;
2570
3.37k
  }
2571
2572
17.0k
  LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
2573
17.0k
}
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
18.7k
{
2583
18.7k
  struct sc_context *ctx = p15card->card->ctx;
2584
18.7k
  struct sc_algorithm_info *info;
2585
18.7k
  unsigned int count;
2586
18.7k
  unsigned long talg = alg;
2587
2588
18.7k
  LOG_FUNC_CALLED(ctx);
2589
2590
18.7k
  if (alg == SC_ALGORITHM_EDDSA || alg == SC_ALGORITHM_XEDDSA)
2591
0
    talg = SC_ALGORITHM_EC; /* really testing ecparams */
2592
2593
18.7k
  count = p15card->card->algorithm_count;
2594
96.2k
  for (info = p15card->card->algorithms; count--; info++) {
2595
    /* don't check flags if none was specified */
2596
2597
82.7k
    if (alg != SC_ALGORITHM_EDDSA && alg != SC_ALGORITHM_XEDDSA) {
2598
82.7k
      if (info->algorithm != alg || info->key_length != key_length)
2599
76.9k
        continue;
2600
82.7k
    }
2601
5.83k
    if (flags != 0 && ((info->flags & flags) != flags))
2602
583
      continue;
2603
2604
5.24k
    if (alg == SC_ALGORITHM_RSA && prkey)   {
2605
3.64k
      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
3.64k
    } else if (talg == SC_ALGORITHM_EC) { /* includes EDDSA and XEDDSA */
2620
1.08k
      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.08k
      if (sc_valid_oid(&info->u._ec.params.id))
2624
515
        if (!sc_compare_oid(&info->u._ec.params.id, &prkey->u.ec.params.id))
2625
0
          continue;
2626
1.08k
    }
2627
2628
5.24k
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
2629
5.24k
  }
2630
2631
13.4k
  LOG_FUNC_RETURN(ctx, SC_ERROR_OBJECT_NOT_VALID);
2632
13.4k
}
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
18.1k
{
2797
18.1k
  struct sc_context *ctx = p15card->card->ctx;
2798
2799
18.1k
  switch (algorithm) {
2800
3.64k
  case SC_ALGORITHM_RSA:
2801
3.64k
    return SC_PKCS15_TYPE_PRKEY_RSA;
2802
0
  case SC_ALGORITHM_GOSTR3410:
2803
0
    return SC_PKCS15_TYPE_PRKEY_GOSTR3410;
2804
1.07k
  case SC_ALGORITHM_EC:
2805
1.07k
    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
4.46k
  case SC_ALGORITHM_DES:
2811
4.46k
    return SC_PKCS15_TYPE_SKEY_DES;
2812
4.46k
  case SC_ALGORITHM_3DES:
2813
4.46k
    return SC_PKCS15_TYPE_SKEY_3DES;
2814
4.46k
  case SC_ALGORITHM_AES:
2815
4.46k
  case SC_ALGORITHM_UNDEFINED:
2816
4.46k
    return SC_PKCS15_TYPE_SKEY_GENERIC;
2817
18.1k
  }
2818
0
  sc_log(ctx, "Unsupported key algorithm.");
2819
0
  return SC_ERROR_NOT_SUPPORTED;
2820
18.1k
}
2821
2822
2823
static struct sc_pkcs15_df *
2824
find_df_by_type(struct sc_pkcs15_card *p15card, unsigned int type)
2825
2.78k
{
2826
2.78k
  struct sc_pkcs15_df *df = p15card->df_list;
2827
2828
8.60k
  while (df != NULL && df->type != type)
2829
5.81k
    df = df->next;
2830
2.78k
  return df;
2831
2.78k
}
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
50
{
2838
#ifndef ENABLE_OPENSSL
2839
  LOG_FUNC_RETURN(p15card->card->ctx, SC_SUCCESS);
2840
#else
2841
50
  struct sc_context *ctx = p15card->card->ctx;
2842
50
  struct sc_pkcs15_pubkey *pubkey = NULL;
2843
50
  unsigned id_style;
2844
50
  struct sc_pkcs15_id id;
2845
50
  unsigned char *id_data = NULL;
2846
50
  size_t id_data_len = 0;
2847
50
  int rv, allocated = 0;
2848
2849
50
  LOG_FUNC_CALLED(ctx);
2850
2851
50
  if (!id_out || !profile)
2852
50
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
2853
2854
50
  id_style = profile->id_style;
2855
2856
  /* ID already exists */
2857
50
  if (id_out->len)
2858
50
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
2859
2860
  /* Native ID style is not intrinsic one */
2861
26
  if (id_style == SC_PKCS15INIT_ID_STYLE_NATIVE)
2862
26
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
2863
2864
7
  memset(&id, 0, sizeof(id));
2865
  /* Get PKCS15 public key */
2866
7
  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
7
  case SC_PKCS15_TYPE_PUBKEY:
2878
7
    pubkey = (struct sc_pkcs15_pubkey *)data;
2879
7
    allocated = 0;
2880
7
    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
7
  }
2885
2886
  /* Skip silently if key is not initialized. */
2887
7
  if (pubkey->algorithm == SC_ALGORITHM_RSA && !pubkey->u.rsa.modulus.len)
2888
1
    goto done;
2889
6
  else if (pubkey->algorithm == SC_ALGORITHM_GOSTR3410 &&
2890
0
      !pubkey->u.gostr3410.xy.data)
2891
0
    goto done;
2892
6
  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
6
  if (pubkey->algorithm == SC_ALGORITHM_GOSTR3410 && id_style == SC_PKCS15INIT_ID_STYLE_MOZILLA)
2898
0
    id_style = SC_PKCS15INIT_ID_STYLE_RFC2459;
2899
2900
6
  switch (id_style)  {
2901
6
  case SC_PKCS15INIT_ID_STYLE_MOZILLA:
2902
6
    if (pubkey->algorithm == SC_ALGORITHM_RSA)
2903
6
      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
6
    id.len = SHA_DIGEST_LENGTH;
2912
6
    break;
2913
0
  case SC_PKCS15INIT_ID_STYLE_RFC2459:
2914
0
    rv = sc_pkcs15_encode_pubkey(ctx, pubkey, &id_data, &id_data_len);
2915
0
    LOG_TEST_GOTO_ERR(ctx, rv, "Encoding public key error");
2916
2917
0
    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
0
    SHA1(id_data, id_data_len, id.value);
2923
0
    id.len = SHA_DIGEST_LENGTH;
2924
2925
0
    break;
2926
0
  default:
2927
0
    sc_log(ctx, "Unsupported ID style: %i", id_style);
2928
0
    rv = SC_ERROR_NOT_SUPPORTED;
2929
0
    LOG_TEST_GOTO_ERR(ctx, rv, "Non supported ID style");
2930
6
  }
2931
2932
7
done:
2933
7
  memcpy(id_out, &id, sizeof(*id_out));
2934
7
  rv = (int)id_out->len;
2935
2936
7
err:
2937
7
  if (id_data)
2938
0
    free(id_data);
2939
7
  if (allocated)
2940
0
    sc_pkcs15_free_pubkey(pubkey);
2941
2942
7
  LOG_FUNC_RETURN(ctx, rv);
2943
7
#endif
2944
7
}
2945
2946
2947
static int
2948
select_id(struct sc_pkcs15_card *p15card, int type, struct sc_pkcs15_id *id)
2949
18.1k
{
2950
18.1k
  struct sc_context *ctx = p15card->card->ctx;
2951
18.1k
  struct sc_pkcs15_id unused_id;
2952
18.1k
  struct sc_pkcs15_object *obj;
2953
18.1k
  unsigned int nid = DEFAULT_ID;
2954
18.1k
  int r;
2955
2956
18.1k
  LOG_FUNC_CALLED(ctx);
2957
  /* If the user provided an ID, make sure we can use it */
2958
18.1k
  if (id->len != 0) {
2959
14.3k
    r = sc_pkcs15_find_object_by_id(p15card, type, id, &obj);
2960
2961
14.3k
    if (r == SC_ERROR_OBJECT_NOT_FOUND)
2962
14.3k
      r = 0;
2963
0
    else if (!r)
2964
0
      r = SC_ERROR_NON_UNIQUE_ID;
2965
2966
14.3k
    LOG_FUNC_RETURN(ctx, r);
2967
14.3k
  }
2968
2969
3.76k
  memset(&unused_id, 0, sizeof(unused_id));
2970
703k
  while (nid < 255) {
2971
699k
    id->value[0] = nid++;
2972
699k
    id->len = 1;
2973
2974
699k
    r = sc_pkcs15_find_object_by_id(p15card, type, id, &obj);
2975
699k
    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
699k
      if (type == SC_PKCS15_TYPE_PRKEY) {
2981
699k
        struct sc_pkcs15_search_key search_key;
2982
2983
699k
        memset(&search_key, 0, sizeof(search_key));
2984
699k
        search_key.class_mask = SC_PKCS15_SEARCH_CLASS_PUBKEY | SC_PKCS15_SEARCH_CLASS_CERT;
2985
699k
        search_key.id = id;
2986
2987
699k
        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
699k
        if (r > 0)
2991
18
          continue;
2992
699k
      }
2993
699k
      if (!unused_id.len)
2994
3.76k
        unused_id = *id;
2995
699k
      continue;
2996
699k
    }
2997
699k
  }
2998
2999
3.76k
  if (unused_id.len) {
3000
3.76k
    *id = unused_id;
3001
3.76k
    LOG_FUNC_RETURN(ctx, 0);
3002
3.76k
  }
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
21.8k
{
3023
21.8k
  switch (obj->type & SC_PKCS15_TYPE_CLASS_MASK) {
3024
4.72k
  case SC_PKCS15_TYPE_PRKEY:
3025
4.72k
    return "private-key";
3026
22
  case SC_PKCS15_TYPE_PUBKEY:
3027
22
    return "public-key";
3028
13.3k
  case SC_PKCS15_TYPE_SKEY:
3029
13.3k
    return "secret-key";
3030
0
  case SC_PKCS15_TYPE_CERT:
3031
0
    return "certificate";
3032
3.70k
  case SC_PKCS15_TYPE_DATA_OBJECT:
3033
3.70k
    if (obj->flags & SC_PKCS15_CO_FLAG_PRIVATE)
3034
0
      return "privdata";
3035
3.70k
    else
3036
3.70k
      return "data";
3037
21.8k
  }
3038
3039
0
  return NULL;
3040
21.8k
}
3041
3042
3043
static int
3044
get_object_path_from_object (struct sc_pkcs15_object *obj,
3045
    struct sc_path *ret_path)
3046
2.45k
{
3047
2.45k
  if (!ret_path)
3048
0
    return SC_ERROR_INVALID_ARGUMENTS;
3049
3050
2.45k
  memset(ret_path, 0, sizeof(struct sc_path));
3051
3052
2.45k
  switch(obj->type & SC_PKCS15_TYPE_CLASS_MASK)   {
3053
2.17k
  case SC_PKCS15_TYPE_PRKEY:
3054
2.17k
    *ret_path = ((struct sc_pkcs15_prkey_info *)obj->data)->path;
3055
2.17k
    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
279
  case SC_PKCS15_TYPE_SKEY:
3060
279
    *ret_path = ((struct sc_pkcs15_skey_info *)obj->data)->path;
3061
279
    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
2.45k
  }
3072
0
  return SC_ERROR_NOT_SUPPORTED;
3073
2.45k
}
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
21.8k
{
3080
21.8k
  struct sc_context *ctx = p15card->card->ctx;
3081
21.8k
  struct sc_file  *file;
3082
21.8k
  struct sc_pkcs15_object *objs[32];
3083
21.8k
  struct sc_pkcs15_id index_id;
3084
21.8k
  struct sc_path obj_path;
3085
21.8k
  int ii, r, nn_objs, index;
3086
21.8k
  const char *name;
3087
3088
21.8k
  LOG_FUNC_CALLED(ctx);
3089
21.8k
  r = sc_pkcs15_get_objects(p15card, obj->type & SC_PKCS15_TYPE_CLASS_MASK, objs, sizeof(objs)/sizeof(objs[0]));
3090
21.8k
  LOG_TEST_RET(ctx, r, "Get PKCS#15 objects error");
3091
21.8k
  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
21.8k
  memset(path, 0, sizeof(*path));
3097
21.8k
  if (obj->auth_id.len && profile->pin_domains != 0) {
3098
50
    r = sc_pkcs15init_get_pin_path(p15card, &obj->auth_id, path);
3099
50
    LOG_TEST_RET(ctx, r, "Cannot get PIN path");
3100
50
  }
3101
21.7k
  else {
3102
21.7k
    *path = profile->df_info->file->path;
3103
21.7k
  }
3104
3105
  /* If the profile specifies a key directory template,
3106
   * instantiate it now and create the DF
3107
   */
3108
21.8k
  name = get_template_name_from_object (obj);
3109
21.8k
  if (!name)
3110
21.8k
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
3111
3112
21.8k
  sc_log(ctx, "key-domain.%s @%s (auth_id.len=%"SC_FORMAT_LEN_SIZE_T"u)",
3113
21.8k
         name, sc_print_path(path), obj->auth_id.len);
3114
3115
21.8k
  index_id.len = 1;
3116
24.1k
  for (index = TEMPLATE_INSTANTIATE_MIN_INDEX; index <= TEMPLATE_INSTANTIATE_MAX_INDEX; index++)   {
3117
24.1k
    index_id.value[0] = index;
3118
24.1k
    r = sc_profile_instantiate_template(profile, "key-domain", path, name, &index_id, &file);
3119
24.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
23.1k
      char t_name[0x40];
3123
3124
23.1k
      snprintf(t_name, sizeof(t_name), "template-%s", name);
3125
23.1k
      sc_log(ctx, "get instance %i of '%s'", index, t_name);
3126
23.1k
      r = sc_profile_get_file_instance(profile, t_name, index, &file);
3127
23.1k
      if (r == SC_ERROR_FILE_NOT_FOUND)
3128
23.1k
        LOG_FUNC_RETURN(ctx, SC_SUCCESS);
3129
23.1k
    }
3130
4.15k
    LOG_TEST_RET(ctx, r, "Template instantiation error");
3131
3132
3.46k
    if (file->type == SC_FILE_TYPE_BSO)
3133
19
      break;
3134
3135
3.44k
    sc_log(ctx, "instantiated template path %s", sc_print_path(&file->path));
3136
3.46k
    for (ii=0; ii<nn_objs; ii++)   {
3137
2.45k
      r = get_object_path_from_object(objs[ii], &obj_path);
3138
2.45k
      LOG_TEST_RET(ctx, r, "Failed to get object path from pkcs15 object");
3139
3140
2.45k
      if (obj_path.len != file->path.len)
3141
136
        break;
3142
3143
2.32k
      if (!memcmp(obj_path.value, file->path.value, obj_path.len))
3144
2.30k
        break;
3145
2.32k
    }
3146
3147
3.44k
    if (ii==nn_objs)
3148
1.01k
      break;
3149
3150
2.43k
    if (obj_path.len != file->path.len)
3151
136
      break;
3152
3153
2.30k
    sc_file_free(file);
3154
3155
2.30k
    index_id.value[0] += 1;
3156
2.30k
  }
3157
3158
1.17k
  if (index > TEMPLATE_INSTANTIATE_MAX_INDEX)
3159
1.17k
    LOG_TEST_RET(ctx, SC_ERROR_TOO_MANY_OBJECTS, "Template instantiation error");
3160
3161
1.16k
  *path = file->path;
3162
1.16k
  sc_file_free(file);
3163
3164
1.16k
  sc_log(ctx, "returns object path '%s'", sc_print_path(path));
3165
1.16k
  LOG_FUNC_RETURN(ctx, SC_SUCCESS);
3166
1.16k
}
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
90
{
3176
90
  struct sc_context *ctx = p15card->card->ctx;
3177
90
  struct sc_card  *card = p15card->card;
3178
90
  int r, retry = 1;
3179
3180
90
  LOG_FUNC_CALLED(ctx);
3181
90
  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
81
      break;
3193
    /* DIR file is not yet created. */
3194
3195
85
    sc_format_path("3F002F00", &path);
3196
85
    r = sc_profile_get_file_by_path(profile, &path, &dir_file);
3197
85
    LOG_TEST_RET(ctx, r, "DIR file not defined in profile");
3198
3199
    /* Create DIR file */
3200
83
    r = sc_pkcs15init_update_file(profile, p15card, dir_file, NULL, 0);
3201
83
    sc_file_free(dir_file);
3202
83
  } while (retry--);
3203
3204
88
  if (r >= 0) {
3205
64
    card->app[card->app_count++] = app;
3206
64
    r = sc_update_dir(card, NULL);
3207
64
  }
3208
88
  LOG_FUNC_RETURN(ctx, r);
3209
88
}
3210
3211
3212
static int
3213
sc_pkcs15init_update_tokeninfo(struct sc_pkcs15_card *p15card, struct sc_profile *profile)
3214
893
{
3215
893
  struct sc_context *ctx = p15card->card->ctx;
3216
893
  unsigned char *buf = NULL;
3217
893
  size_t    size;
3218
893
  int   rv;
3219
3220
893
  LOG_FUNC_CALLED(ctx);
3221
3222
  /* set lastUpdate field */
3223
893
  if (p15card->tokeninfo->last_update.gtime != NULL)   {
3224
20
    free(p15card->tokeninfo->last_update.gtime);
3225
20
    p15card->tokeninfo->last_update.gtime = NULL;
3226
20
  }
3227
893
  rv = sc_pkcs15_get_generalized_time(ctx, &p15card->tokeninfo->last_update.gtime);
3228
893
  LOG_TEST_RET(ctx, rv, "Cannot allocate generalized time string");
3229
3230
893
  if (profile->ops->emu_update_tokeninfo)
3231
22
    return profile->ops->emu_update_tokeninfo(profile, p15card, p15card->tokeninfo);
3232
3233
871
  if (!p15card->file_tokeninfo)   {
3234
460
    sc_log(ctx, "No TokenInfo to update");
3235
460
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
3236
460
  }
3237
3238
411
  rv = sc_pkcs15_encode_tokeninfo(ctx, p15card->tokeninfo, &buf, &size);
3239
411
  if (rv >= 0)
3240
328
    rv = sc_pkcs15init_update_file(profile, p15card, p15card->file_tokeninfo, buf, size);
3241
411
  if (buf)
3242
328
    free(buf);
3243
3244
411
  LOG_FUNC_RETURN(ctx, rv);
3245
411
}
3246
3247
3248
static int
3249
sc_pkcs15init_update_lastupdate(struct sc_pkcs15_card *p15card, struct sc_profile *profile)
3250
939
{
3251
939
  struct sc_context *ctx = p15card->card->ctx;
3252
939
  int   r;
3253
3254
939
  LOG_FUNC_CALLED(ctx);
3255
939
  if (p15card->tokeninfo->last_update.path.len)    {
3256
79
    static const struct sc_asn1_entry c_asn1_last_update[2] = {
3257
79
            { "generalizedTime",    SC_ASN1_GENERALIZEDTIME, SC_ASN1_TAG_GENERALIZEDTIME,   SC_ASN1_OPTIONAL, NULL, NULL },
3258
79
      { NULL, 0, 0, 0, NULL, NULL }
3259
79
    };
3260
79
    struct sc_asn1_entry asn1_last_update[2];
3261
79
    size_t lupdate_len;
3262
79
    struct sc_file *file = NULL;
3263
79
    struct sc_pkcs15_last_update *last_update = &p15card->tokeninfo->last_update;
3264
79
    unsigned char *buf = NULL;
3265
79
    size_t buflen;
3266
3267
    /* update 'lastUpdate' file */
3268
79
    if (last_update->gtime != NULL)
3269
0
      free(last_update->gtime);
3270
79
    r = sc_pkcs15_get_generalized_time(ctx, &last_update->gtime);
3271
79
    LOG_TEST_RET(ctx, r, "Cannot allocate generalized time string");
3272
3273
79
    sc_copy_asn1_entry(c_asn1_last_update, asn1_last_update);
3274
79
    lupdate_len = strlen(last_update->gtime);
3275
79
    sc_format_asn1_entry(asn1_last_update + 0, last_update->gtime, &lupdate_len, 1);
3276
3277
79
    r = sc_asn1_encode(ctx, asn1_last_update, &buf, &buflen);
3278
79
    LOG_TEST_RET(ctx, r, "select object path failed");
3279
3280
79
    r = sc_select_file(p15card->card, &last_update->path, &file);
3281
79
    if (r < 0)
3282
72
      free(buf);
3283
79
    LOG_TEST_RET(ctx, r, "select object path failed");
3284
3285
7
    r = sc_pkcs15init_update_file(profile, p15card, file, buf, buflen);
3286
7
    sc_file_free(file);
3287
7
    if (buf)
3288
7
      free(buf);
3289
7
    LOG_TEST_RET(ctx, r, "Cannot update 'LastUpdate' file");
3290
3
    LOG_FUNC_RETURN(ctx, r);
3291
3
  }
3292
3293
860
  r = sc_pkcs15init_update_tokeninfo(p15card, profile);
3294
860
  LOG_FUNC_RETURN(ctx, r);
3295
860
}
3296
3297
3298
static int
3299
sc_pkcs15init_update_odf(struct sc_pkcs15_card *p15card, struct sc_profile *profile)
3300
859
{
3301
859
  struct sc_context *ctx = p15card->card->ctx;
3302
859
  unsigned char *buf = NULL;
3303
859
  size_t    size;
3304
859
  int   r;
3305
3306
859
  LOG_FUNC_CALLED(ctx);
3307
859
  r = sc_pkcs15_encode_odf(ctx, p15card, &buf, &size);
3308
859
  if (r >= 0)
3309
856
    r = sc_pkcs15init_update_file(profile, p15card, p15card->file_odf, buf, size);
3310
859
  if (buf)
3311
856
    free(buf);
3312
859
  LOG_FUNC_RETURN(ctx, r);
3313
859
}
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.14k
{
3324
1.14k
  struct sc_context *ctx = p15card->card->ctx;
3325
1.14k
  struct sc_card  *card = p15card->card;
3326
1.14k
  struct sc_file  *file = NULL;
3327
1.14k
  unsigned char *buf = NULL;
3328
1.14k
  size_t    bufsize = 0;
3329
1.14k
  int   update_odf = is_new, r = 0;
3330
3331
1.14k
  LOG_FUNC_CALLED(ctx);
3332
1.14k
  if (!df)
3333
1.14k
    LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "DF missing");
3334
3335
1.14k
  r = sc_profile_get_file_by_path(profile, &df->path, &file);
3336
1.14k
  if (r < 0 || file == NULL)
3337
84
    sc_select_file(card, &df->path, &file);
3338
3339
1.14k
  r = sc_pkcs15_encode_df(card->ctx, p15card, df, &buf, &bufsize);
3340
1.14k
  if (r >= 0) {
3341
1.13k
    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.13k
    if (profile->pkcs15.encode_df_length) {
3353
76
      df->path.count = (int)bufsize;
3354
76
      df->path.index = 0;
3355
76
      update_odf = 1;
3356
76
    }
3357
1.13k
    free(buf);
3358
1.13k
  }
3359
1.14k
  sc_file_free(file);
3360
3361
1.14k
  LOG_TEST_RET(ctx, r, "Failed to encode or update xDF");
3362
3363
  /* Now update the ODF if we have to */
3364
896
  if (update_odf)
3365
859
    r = sc_pkcs15init_update_odf(p15card, profile);
3366
896
  LOG_TEST_RET(ctx, r, "Failed to encode or update ODF");
3367
3368
805
  LOG_FUNC_RETURN(ctx, r > 0 ? SC_SUCCESS : r);
3369
805
}
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.71k
{
3378
1.71k
  struct sc_context *ctx = p15card->card->ctx;
3379
1.71k
  struct sc_pkcs15_df *df;
3380
1.71k
  int is_new = 0, r = 0, object_added = 0;
3381
3382
1.71k
  LOG_FUNC_CALLED(ctx);
3383
1.71k
  sc_log(ctx, "add object %p to DF of type %u", object, df_type);
3384
3385
1.71k
  df = find_df_by_type(p15card, df_type);
3386
1.71k
  if (df == NULL) {
3387
1.52k
    struct sc_file  *file;
3388
1.52k
    file = profile->df[df_type];
3389
1.52k
    if (file == NULL) {
3390
453
      sc_log(ctx, "Profile doesn't define a DF file %u", df_type);
3391
453
      LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "DF not found in profile");
3392
453
    }
3393
1.07k
    sc_pkcs15_add_df(p15card, df_type, &file->path);
3394
1.07k
    df = find_df_by_type(p15card, df_type);
3395
1.07k
    assert(df != NULL);
3396
1.07k
    is_new = 1;
3397
3398
    /* Mark the df as enumerated, so libopensc doesn't try
3399
     * to load the file at a most inconvenient moment */
3400
1.07k
    df->enumerated = 1;
3401
1.07k
  }
3402
3403
1.25k
  if (object == NULL) {
3404
765
    sc_log(ctx, "Add nothing; just instantiate this directory file");
3405
765
  }
3406
494
  else if (object->df == NULL) {
3407
494
    sc_log(ctx, "Append object");
3408
494
    object->df = df;
3409
494
    r = sc_pkcs15_add_object(p15card, object);
3410
494
    LOG_TEST_RET(ctx, r, "Failed to add pkcs15 object");
3411
494
    object_added = 1;
3412
494
  }
3413
0
  else {
3414
0
    sc_log(ctx, "Reuse existing object");
3415
0
    assert(object->df == df);
3416
0
  }
3417
3418
1.25k
  if (profile->ops->emu_update_any_df)
3419
111
    r = profile->ops->emu_update_any_df(profile, p15card, SC_AC_OP_CREATE, object);
3420
1.14k
  else
3421
1.14k
    r = sc_pkcs15init_update_any_df(p15card, profile, df, is_new);
3422
3423
1.25k
  if (r < 0 && object_added)
3424
281
    sc_pkcs15_remove_object(p15card, object);
3425
3426
1.25k
  LOG_FUNC_RETURN(ctx, r > 0 ? SC_SUCCESS : r);
3427
1.25k
}
3428
3429
3430
struct sc_pkcs15_object *
3431
sc_pkcs15init_new_object(int type, const char *label, struct sc_pkcs15_id *auth_id, void *data)
3432
27.8k
{
3433
27.8k
  struct sc_pkcs15_object *object;
3434
27.8k
  unsigned int data_size = 0;
3435
3436
27.8k
  object = calloc(1, sizeof(*object));
3437
27.8k
  if (object == NULL)
3438
0
    return NULL;
3439
27.8k
  object->type = type;
3440
3441
27.8k
  switch (type & SC_PKCS15_TYPE_CLASS_MASK) {
3442
5.23k
  case SC_PKCS15_TYPE_AUTH:
3443
5.23k
    object->flags = DEFAULT_PIN_FLAGS;
3444
5.23k
    data_size = sizeof(struct sc_pkcs15_auth_info);
3445
5.23k
    break;
3446
4.72k
  case SC_PKCS15_TYPE_PRKEY:
3447
4.72k
    object->flags = DEFAULT_PRKEY_FLAGS;
3448
4.72k
    data_size = sizeof(struct sc_pkcs15_prkey_info);
3449
4.72k
    break;
3450
13.3k
  case SC_PKCS15_TYPE_SKEY:
3451
13.3k
    object->flags = DEFAULT_SKEY_FLAGS;
3452
13.3k
    data_size = sizeof(struct sc_pkcs15_skey_info);
3453
13.3k
    break;
3454
24
  case SC_PKCS15_TYPE_PUBKEY:
3455
24
    object->flags = DEFAULT_PUBKEY_FLAGS;
3456
24
    data_size = sizeof(struct sc_pkcs15_pubkey_info);
3457
24
    break;
3458
0
  case SC_PKCS15_TYPE_CERT:
3459
0
    object->flags = DEFAULT_CERT_FLAGS;
3460
0
    data_size = sizeof(struct sc_pkcs15_cert_info);
3461
0
    break;
3462
4.46k
  case SC_PKCS15_TYPE_DATA_OBJECT:
3463
4.46k
    object->flags = DEFAULT_DATA_FLAGS;
3464
4.46k
    if (auth_id->len != 0)
3465
0
      object->flags |= SC_PKCS15_CO_FLAG_PRIVATE;
3466
4.46k
    data_size = sizeof(struct sc_pkcs15_data_info);
3467
4.46k
    break;
3468
27.8k
  }
3469
3470
27.8k
  if (data_size) {
3471
27.8k
    object->data = calloc(1, data_size);
3472
27.8k
    if (data)
3473
1.14k
      memcpy(object->data, data, data_size);
3474
27.8k
  }
3475
3476
27.8k
  if (label)
3477
27.8k
    strlcpy(object->label, label, sizeof(object->label));
3478
27.8k
  if (auth_id)
3479
22.6k
    object->auth_id = *auth_id;
3480
3481
27.8k
  return object;
3482
27.8k
}
3483
3484
3485
void
3486
sc_pkcs15init_free_object(struct sc_pkcs15_object *object)
3487
18.1k
{
3488
18.1k
  if (object) {
3489
7.52k
    free(object->data);
3490
7.52k
    free(object);
3491
7.52k
  }
3492
18.1k
}
3493
3494
3495
int
3496
sc_pkcs15init_change_attrib(struct sc_pkcs15_card *p15card, struct sc_profile *profile, struct sc_pkcs15_object *object,
3497
    int new_attrib_type, void *new_value, int new_len)
3498
0
{
3499
0
  struct sc_context *ctx = p15card->card->ctx;
3500
0
  struct sc_card  *card = p15card->card;
3501
0
  unsigned char *buf = NULL;
3502
0
  size_t    bufsize = 0;
3503
0
  int   df_type, r = 0;
3504
0
  struct sc_pkcs15_df *df;
3505
0
  struct sc_pkcs15_id new_id = *((struct sc_pkcs15_id *) new_value);
3506
3507
0
  LOG_FUNC_CALLED(ctx);
3508
0
  if (object == NULL || object->df == NULL)
3509
0
    LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Cannot change attribute");
3510
0
  df_type = object->df->type;
3511
3512
0
  df = find_df_by_type(p15card, df_type);
3513
0
  if (df == NULL)
3514
0
    LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "Cannot change attribute");
3515
3516
0
  sc_log(ctx, "type of attribute to change %i; DF type %i", new_attrib_type, df_type);
3517
0
  switch(new_attrib_type)   {
3518
0
  case P15_ATTR_TYPE_LABEL:
3519
0
    if (new_len >= SC_PKCS15_MAX_LABEL_SIZE)
3520
0
      LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "New label too long");
3521
0
    memcpy(object->label, new_value, new_len);
3522
0
    object->label[new_len] = '\0';
3523
0
    break;
3524
0
  case P15_ATTR_TYPE_ID:
3525
0
    switch(df_type) {
3526
0
    case SC_PKCS15_PRKDF:
3527
0
      ((struct sc_pkcs15_prkey_info *) object->data)->id = new_id;
3528
0
      break;
3529
0
    case SC_PKCS15_PUKDF:
3530
0
    case SC_PKCS15_PUKDF_TRUSTED:
3531
0
      ((struct sc_pkcs15_pubkey_info *) object->data)->id = new_id;
3532
0
      break;
3533
0
    case SC_PKCS15_SKDF:
3534
0
      ((struct sc_pkcs15_skey_info *) object->data)->id = new_id;
3535
0
      break;
3536
0
    case SC_PKCS15_CDF:
3537
0
    case SC_PKCS15_CDF_TRUSTED:
3538
0
    case SC_PKCS15_CDF_USEFUL:
3539
0
      ((struct sc_pkcs15_cert_info *) object->data)->id = new_id;
3540
0
      break;
3541
0
    default:
3542
0
      LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Cannot change ID attribute");
3543
0
    }
3544
0
    break;
3545
0
  case P15_ATTR_TYPE_VALUE:
3546
0
    switch(df_type) {
3547
0
    case SC_PKCS15_DODF: {
3548
0
      u8 *nv;
3549
0
      struct sc_pkcs15_data_info *info = (struct sc_pkcs15_data_info *) object->data;
3550
0
      struct sc_path old_data_path = info->path;
3551
0
      struct sc_path new_data_path;
3552
0
      struct sc_pkcs15_der new_data;
3553
0
      new_data.len = new_len;
3554
0
      new_data.value = (u8 *) new_value;
3555
3556
      /* save new data as a new data file on token */
3557
0
      r = sc_pkcs15init_store_data(p15card, profile, object, &new_data, &new_data_path);
3558
0
      profile->dirty = 1;
3559
0
      LOG_TEST_RET(ctx, r, "Failed to store new data");
3560
3561
0
      nv = (u8 *) malloc (new_len * sizeof(u8));
3562
0
      if (!nv) {
3563
0
        LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
3564
0
      }
3565
0
      memcpy(nv, new_value, new_len * sizeof(u8));
3566
0
      free(info->data.value);
3567
      /*  set object members to represent new CKA_VALUE value,
3568
        new path will be written to DODF later in this function*/
3569
0
      info->data.len = new_len;
3570
0
      info->data.value = nv;
3571
0
      info->path = new_data_path;
3572
3573
      /* delete old data file from token */
3574
0
      r = sc_pkcs15init_delete_by_path(profile, p15card, &old_data_path);
3575
0
      LOG_TEST_RET(ctx, r, "Failed to delete old data");
3576
0
      break;
3577
0
    }
3578
0
    default:
3579
0
      LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Cannot change value attribute");
3580
0
    }
3581
0
    break;
3582
0
  default:
3583
0
    LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Only 'LABEL' or 'ID' or 'VALUE'(for data objects) attributes can be changed");
3584
0
  }
3585
3586
0
  if (profile->ops->emu_update_any_df)   {
3587
0
    r = profile->ops->emu_update_any_df(profile, p15card, SC_AC_OP_CREATE, object);
3588
0
    LOG_TEST_RET(ctx, r, "Card specific DF update failed");
3589
0
  }
3590
0
  else   {
3591
0
    r = sc_pkcs15_encode_df(card->ctx, p15card, df, &buf, &bufsize);
3592
0
    if (r >= 0) {
3593
0
      struct sc_file *file = NULL;
3594
3595
0
      r = sc_profile_get_file_by_path(profile, &df->path, &file);
3596
0
      if (r < 0)
3597
0
        free(buf);
3598
0
      LOG_TEST_RET(ctx, r, "Cannot instantiate file by path");
3599
3600
0
      r = sc_pkcs15init_update_file(profile, p15card, file, buf, bufsize);
3601
0
      free(buf);
3602
0
      sc_file_free(file);
3603
0
    }
3604
0
  }
3605
3606
0
  if (r > 0)
3607
0
    r = 0;
3608
0
  LOG_FUNC_RETURN(ctx, r);
3609
0
}
3610
3611
3612
int
3613
sc_pkcs15init_delete_object(struct sc_pkcs15_card *p15card, struct sc_profile *profile,
3614
    struct sc_pkcs15_object *obj)
3615
0
{
3616
0
  struct sc_context *ctx = p15card->card->ctx;
3617
0
  struct sc_file *file = NULL;
3618
0
  struct sc_path path;
3619
0
  struct sc_pkcs15_df *df;
3620
0
  int r = 0, stored_in_ef = 0;
3621
3622
0
  LOG_FUNC_CALLED(ctx);
3623
0
  r = get_object_path_from_object(obj, &path);
3624
0
  LOG_TEST_RET(ctx, r, "Failed to get object path");
3625
3626
0
  sc_log(ctx, "delete object(type:%X) with path(type:%X,%s)", obj->type, path.type, sc_print_path(&path));
3627
3628
0
  if (profile->ops->delete_object != NULL) {
3629
    /* If there's a card-specific way to delete objects, use it. */
3630
0
    r = profile->ops->delete_object(profile, p15card, obj, &path);
3631
0
    if (r != SC_ERROR_NOT_SUPPORTED)
3632
0
      LOG_TEST_RET(ctx, r, "Card specific delete object failed");
3633
0
  }
3634
3635
0
  if (profile->ops->delete_object == NULL || r == SC_ERROR_NOT_SUPPORTED)  {
3636
0
    if (path.len || path.aid.len)   {
3637
0
      r = sc_select_file(p15card->card, &path, &file);
3638
0
      if (r != SC_ERROR_FILE_NOT_FOUND)
3639
0
        LOG_TEST_RET(ctx, r, "select object path failed");
3640
3641
0
      stored_in_ef = (file->type != SC_FILE_TYPE_DF);
3642
0
      sc_file_free(file);
3643
0
    }
3644
3645
    /* If the object is stored in a normal EF, try to delete the EF. */
3646
0
    if (r == SC_SUCCESS && stored_in_ef) {
3647
0
      r = sc_pkcs15init_delete_by_path(profile, p15card, &path);
3648
0
      LOG_TEST_RET(ctx, r, "Failed to delete object by path");
3649
0
    }
3650
0
  }
3651
3652
0
  if (profile->ops->emu_update_any_df)   {
3653
0
    r = profile->ops->emu_update_any_df(profile, p15card, SC_AC_OP_ERASE, obj);
3654
0
    LOG_TEST_RET(ctx, r, "'ERASE' update DF failed");
3655
0
  }
3656
3657
  /* Get the DF we're part of. If there's no DF, fine, we haven't been added yet. */
3658
0
  df = obj->df;
3659
0
  if (df)   {
3660
    /* Unlink the object and update the DF */
3661
0
    sc_pkcs15_remove_object(p15card, obj);
3662
0
    sc_pkcs15_free_object(obj);
3663
0
  }
3664
3665
0
  if (!profile->ops->emu_update_any_df)
3666
0
    r = sc_pkcs15init_update_any_df(p15card, profile, df, 0);
3667
3668
  /* mark card as dirty */
3669
0
  profile->dirty = 1;
3670
3671
0
  LOG_FUNC_RETURN(ctx, r);
3672
0
}
3673
3674
3675
int
3676
sc_pkcs15init_update_certificate(struct sc_pkcs15_card *p15card,
3677
  struct sc_profile *profile, struct sc_pkcs15_object *obj,
3678
  const unsigned char *rawcert, size_t certlen)
3679
0
{
3680
0
  struct sc_context *ctx = p15card->card->ctx;
3681
0
  struct sc_file *file = NULL;
3682
0
  struct sc_path *path = &((struct sc_pkcs15_cert_info *)obj->data)->path;
3683
0
  int r;
3684
3685
0
  LOG_FUNC_CALLED(ctx);
3686
0
  r = sc_select_file(p15card->card, path, &file);
3687
0
  LOG_TEST_RET(ctx, r, "Failed to select cert file");
3688
3689
  /* If the new cert doesn't fit in the EF, delete it and make the same, but bigger EF */
3690
0
  if (file->size != certlen) {
3691
0
    struct sc_file *parent = NULL;
3692
3693
0
    r = sc_pkcs15init_delete_by_path(profile, p15card, path);
3694
0
    if (r < 0)
3695
0
      goto done;
3696
3697
0
    file->size = certlen;
3698
3699
0
    r = do_select_parent(profile, p15card, file, &parent);
3700
0
    if (r < 0)
3701
0
      goto done;
3702
3703
0
    r = sc_pkcs15init_authenticate(profile, p15card, parent, SC_AC_OP_CREATE);
3704
0
    sc_file_free(parent);
3705
0
    if (r < 0)   {
3706
0
      sc_log(ctx, "'CREATE' authentication failed");
3707
0
      goto done;
3708
0
    }
3709
3710
    /* ensure we are in the correct lifecycle */
3711
0
    r = sc_pkcs15init_set_lifecycle(p15card->card, SC_CARDCTRL_LIFECYCLE_ADMIN);
3712
0
    if (r < 0 && r != SC_ERROR_NOT_SUPPORTED)
3713
0
      goto done;
3714
3715
0
    r = sc_create_file(p15card->card, file);
3716
0
    if (r < 0)   {
3717
0
      sc_log(ctx, "Cannot create cert file");
3718
0
      goto done;
3719
0
    }
3720
0
  }
3721
3722
0
  if (!sc_file_get_acl_entry(file, SC_AC_OP_UPDATE))   {
3723
0
    struct sc_path tmp_path;
3724
3725
    /* FCI of selected cert file do not contains ACLs.
3726
     * For the 'UPDATE' authentication use instead sc_file
3727
     *  instantiated from card profile with default ACLs. */
3728
0
    sc_file_free(file);
3729
3730
0
    r = select_object_path(p15card, profile, obj, &tmp_path);
3731
0
    if (r < 0)   {
3732
0
      sc_log(ctx, "Select object path error");
3733
0
      goto done;
3734
0
    }
3735
3736
0
    r = sc_profile_get_file_by_path(profile, path, &file);
3737
0
    if (r < 0)   {
3738
0
      sc_log(ctx, "Cannot instantiate cert file");
3739
0
      goto done;
3740
0
    }
3741
0
  }
3742
3743
  /* Write the new cert */
3744
0
  r = sc_pkcs15init_authenticate(profile, p15card, file, SC_AC_OP_UPDATE);
3745
0
  if (r < 0)   {
3746
0
    sc_log(ctx, "'UPDATE' authentication failed");
3747
0
    goto done;
3748
0
  }
3749
3750
0
  r = sc_select_file(p15card->card, path, NULL);
3751
0
  if (r < 0)
3752
0
    goto done;
3753
3754
0
  r = sc_update_binary(p15card->card, 0, rawcert, certlen, 0);
3755
0
  if (r < 0)
3756
0
    goto done;
3757
3758
  /* Fill the remaining space in the EF (if any) with zeros */
3759
0
  if (certlen < file->size) {
3760
0
    unsigned char *tmp = calloc(1, file->size - certlen);
3761
0
    if (tmp == NULL) {
3762
0
      r = SC_ERROR_OUT_OF_MEMORY;
3763
0
      goto done;
3764
0
    }
3765
0
    r = sc_update_binary(p15card->card, (unsigned int)certlen, tmp, file->size - certlen, 0);
3766
0
    free(tmp);
3767
0
    if (r < 0)
3768
0
      sc_log(ctx, "Update cert file error");
3769
0
  }
3770
3771
0
  if (r >= 0) {
3772
    /* Update the CDF entry */
3773
0
    path = &((struct sc_pkcs15_cert_info *)obj->data)->path;
3774
0
    if (file->size != certlen) {
3775
0
      path->index = 0;
3776
0
      path->count = (int)certlen;
3777
0
    }
3778
0
    else   {
3779
0
      path->count = -1;
3780
0
    }
3781
3782
0
    if (profile->ops->emu_update_any_df) {
3783
0
      r = profile->ops->emu_update_any_df(profile, p15card, SC_AC_OP_UPDATE, obj);
3784
0
      if (r == SC_ERROR_NOT_SUPPORTED)
3785
0
        r = SC_SUCCESS;
3786
0
    }
3787
0
    else {
3788
0
      r = sc_pkcs15init_update_any_df(p15card, profile, obj->df, 0);
3789
0
    }
3790
3791
0
    if (r < 0)
3792
0
      sc_log(ctx, "Failed to update CDF");
3793
0
  }
3794
3795
  /* mark card as dirty */
3796
0
  profile->dirty = 1;
3797
3798
0
done:
3799
0
  sc_file_free(file);
3800
3801
0
  LOG_FUNC_RETURN(ctx, r);
3802
0
}
3803
3804
3805
static const char *
3806
get_pin_ident_name(int type, int reference)
3807
1.19k
{
3808
1.19k
  switch (type)   {
3809
992
  case SC_AC_CHV:
3810
992
    return "PIN";
3811
30
  case SC_AC_PRO:
3812
30
    return "secure messaging key";
3813
17
  case SC_AC_AUT:
3814
17
    return "authentication key";
3815
9
  case SC_AC_SEN:
3816
9
    return "security environment";
3817
6
  case SC_AC_IDA:
3818
6
    return "PKCS#15 reference";
3819
23
  case SC_AC_SCB:
3820
23
    return "SCB byte in IAS/ECC";
3821
54
  case SC_AC_SYMBOLIC:
3822
54
    switch (reference) {
3823
14
          case SC_PKCS15INIT_USER_PIN:
3824
14
      return "user PIN";
3825
11
    case SC_PKCS15INIT_SO_PIN:
3826
11
      return "SO PIN";
3827
6
          case SC_PKCS15INIT_USER_PUK:
3828
6
      return "user PUK";
3829
16
    case SC_PKCS15INIT_SO_PUK:
3830
16
      return "SO PUK";
3831
54
    }
3832
1.19k
  }
3833
74
  return "authentication data";
3834
1.19k
}
3835
3836
3837
static int
3838
sc_pkcs15init_get_transport_key(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
3839
    int type, int reference, unsigned char *pinbuf, size_t *pinsize)
3840
97
{
3841
97
  struct sc_context *ctx = p15card->card->ctx;
3842
97
  struct sc_pkcs15_object *pin_obj = NULL;
3843
97
  struct sc_pkcs15_auth_info auth_info;
3844
97
  struct sc_cardctl_default_key data;
3845
97
  size_t    defsize = 0;
3846
97
  unsigned char defbuf[0x100];
3847
97
  int rv;
3848
3849
97
  LOG_FUNC_CALLED(ctx);
3850
3851
97
  data.method = type;
3852
97
  data.key_ref = reference;
3853
97
  data.len = sizeof(defbuf);
3854
97
  data.key_data = defbuf;
3855
97
  rv = sc_card_ctl(p15card->card, SC_CARDCTL_GET_DEFAULT_KEY, &data);
3856
97
  if (rv >= 0)
3857
13
    defsize = data.len;
3858
3859
97
  if (callbacks.get_key)   {
3860
0
    rv = callbacks.get_key(profile, type, reference, defbuf, defsize, pinbuf, pinsize);
3861
0
    LOG_TEST_RET(ctx, rv, "Cannot get key");
3862
97
  } else if (rv >= 0) {
3863
13
    if (*pinsize < defsize)
3864
13
      LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Get transport key error");
3865
3866
13
    memcpy(pinbuf, data.key_data, data.len);
3867
13
    *pinsize = data.len;
3868
84
  } else {
3869
    /* pinbuf and pinsize were not filled */
3870
84
    LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "Get transport key error");
3871
84
  }
3872
3873
13
  memset(&auth_info, 0, sizeof(auth_info));
3874
13
  auth_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
3875
13
  auth_info.auth_method = type;
3876
13
  auth_info.attrs.pin.reference = reference;
3877
13
  auth_info.attrs.pin.stored_length = *pinsize;
3878
13
  auth_info.attrs.pin.max_length = *pinsize;
3879
13
  auth_info.attrs.pin.min_length = *pinsize;
3880
3881
13
  pin_obj = sc_pkcs15init_new_object(SC_PKCS15_TYPE_AUTH_PIN, "Default transport key", NULL, &auth_info);
3882
13
  if (!pin_obj)
3883
13
    LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate AUTH object");
3884
3885
13
  rv = sc_pkcs15_add_object(p15card, pin_obj);
3886
13
  LOG_TEST_RET(ctx, rv, "Cannot add PKCS#15 AUTH object");
3887
3888
13
  sc_pkcs15_pincache_add(p15card, pin_obj, pinbuf, *pinsize);
3889
3890
13
  LOG_FUNC_RETURN(ctx, rv);
3891
13
}
3892
3893
3894
/*
3895
 * PIN verification
3896
 */
3897
int
3898
sc_pkcs15init_verify_secret(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
3899
    struct sc_file *file, unsigned int type, int reference)
3900
1.19k
{
3901
1.19k
  struct sc_context *ctx = p15card->card->ctx;
3902
1.19k
  struct sc_pkcs15_object *pin_obj = NULL;
3903
1.19k
  struct sc_pkcs15_auth_info auth_info;
3904
1.19k
  struct sc_path  *path;
3905
1.19k
  int   r, use_pinpad = 0, pin_id = -1;
3906
1.19k
  const char  *ident, *label = NULL;
3907
1.19k
  unsigned char pinbuf[0x100];
3908
1.19k
  size_t    pinsize = 0;
3909
3910
3911
1.19k
  LOG_FUNC_CALLED(ctx);
3912
1.19k
  path = file? &file->path : NULL;
3913
3914
1.19k
  ident = get_pin_ident_name(type, reference);
3915
1.19k
  sc_log(ctx, "get and verify PIN('%s',type:0x%X,reference:0x%X)", ident, type, reference);
3916
3917
1.19k
  if (type == SC_AC_SEN)   {
3918
9
    r = sc_card_ctl(p15card->card, SC_CARDCTL_GET_CHV_REFERENCE_IN_SE, (void *)(&reference));
3919
9
    sc_log(ctx, "Card CTL(GET_CHV_REFERENCE_IN_SE) returned %i", r);
3920
9
    if (r > 0)   {
3921
0
      sc_log(ctx, "CHV(ref:%i) found in SE(ref:%i)", r, reference);
3922
0
      type = SC_AC_CHV;
3923
0
      reference = r;
3924
0
    }
3925
9
    else if (r != SC_ERROR_NOT_SUPPORTED)
3926
2
      LOG_TEST_RET(ctx, r, "Card CTL error: cannot get CHV reference");
3927
9
  }
3928
3929
1.19k
  memset(&auth_info, 0, sizeof(auth_info));
3930
1.19k
  auth_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
3931
1.19k
  auth_info.auth_method = type;
3932
1.19k
  auth_info.attrs.pin.reference = reference;
3933
3934
1.19k
  pin_id = sc_pkcs15init_get_pin_reference(p15card, profile, type, reference);
3935
1.19k
  sc_log(ctx, "found PIN reference %i", pin_id);
3936
1.19k
  if (type == SC_AC_SYMBOLIC) {
3937
54
    if (pin_id == -1)
3938
54
      LOG_FUNC_RETURN(ctx, SC_SUCCESS);
3939
23
    reference = pin_id;
3940
23
    type = SC_AC_CHV;
3941
23
    sc_log(ctx, "Symbolic PIN resolved to PIN(type:CHV,reference:%i)", reference);
3942
23
  }
3943
3944
1.16k
  if (path && path->len && path->len <= SC_MAX_PATH_SIZE) {
3945
1.07k
    struct sc_path tmp_path = *path;
3946
1.07k
    int iter;
3947
1.07k
    r = SC_ERROR_OBJECT_NOT_FOUND;
3948
3.49k
    for (iter = (int)tmp_path.len/2; iter >= 0 && r == SC_ERROR_OBJECT_NOT_FOUND; iter--, tmp_path.len -= 2) {
3949
2.42k
      r = sc_pkcs15_find_pin_by_type_and_reference(p15card,
3950
2.42k
          tmp_path.len ? &tmp_path : NULL,
3951
2.42k
          type, reference, &pin_obj);
3952
2.42k
    }
3953
1.07k
  }
3954
89
  else {
3955
89
    r = sc_pkcs15_find_pin_by_type_and_reference(p15card, NULL, type, reference, &pin_obj);
3956
89
  }
3957
3958
1.16k
  if (!r && pin_obj)   {
3959
209
    memcpy(&auth_info, pin_obj->data, sizeof(auth_info));
3960
209
    sc_log(ctx, "found PIN object '%.*s'", (int) sizeof pin_obj->label, pin_obj->label);
3961
209
  }
3962
3963
1.16k
  if (pin_obj)   {
3964
209
    sc_log(ctx,
3965
209
           "PIN object '%.*s'; pin_obj->content.len:%"SC_FORMAT_LEN_SIZE_T"u",
3966
209
           (int) sizeof pin_obj->label, pin_obj->label,
3967
209
           pin_obj->content.len);
3968
209
    if (pin_obj->content.value && pin_obj->content.len)   {
3969
9
      if (pin_obj->content.len > sizeof(pinbuf))
3970
9
        LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "PIN buffer is too small");
3971
9
      memcpy(pinbuf, pin_obj->content.value, pin_obj->content.len);
3972
9
      pinsize = pin_obj->content.len;
3973
9
      sc_log(ctx, "'ve got '%s' value from cache", ident);
3974
9
      goto found;
3975
9
    }
3976
209
  }
3977
3978
1.15k
  if (pin_obj && pin_obj->label[0])
3979
200
    label = pin_obj->label;
3980
3981
1.15k
  switch (type) {
3982
1.00k
  case SC_AC_CHV:
3983
1.00k
    if (callbacks.get_pin)   {
3984
0
      pinsize = sizeof(pinbuf);
3985
0
      r = callbacks.get_pin(profile, pin_id, &auth_info, label, pinbuf, &pinsize);
3986
0
      sc_log(ctx,
3987
0
             "'get_pin' callback returned %i; pinsize:%"SC_FORMAT_LEN_SIZE_T"u",
3988
0
             r, pinsize);
3989
0
    }
3990
1.00k
    break;
3991
23
  case SC_AC_SCB:
3992
53
  case SC_AC_PRO:
3993
53
    pinsize = 0;
3994
53
    r = 0;
3995
53
    break;
3996
97
  default:
3997
97
    pinsize = sizeof(pinbuf);
3998
97
    r = sc_pkcs15init_get_transport_key(profile, p15card, type, reference, pinbuf, &pinsize);
3999
97
    break;
4000
1.15k
  }
4001
4002
1.15k
  if (r == SC_ERROR_OBJECT_NOT_FOUND)   {
4003
806
    if (p15card->card->reader->capabilities & SC_READER_CAP_PIN_PAD)
4004
0
      r = 0, use_pinpad = 1;
4005
806
    else
4006
806
      r = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
4007
806
  }
4008
4009
1.15k
  LOG_TEST_RET(ctx, r, "Failed to get secret");
4010
266
  if (type == SC_AC_PRO)   {
4011
30
    sc_log(ctx, "No 'verify' for secure messaging");
4012
30
    LOG_FUNC_RETURN(ctx, r);
4013
30
  }
4014
4015
245
found:
4016
245
  if (pin_obj)   {
4017
    /*
4018
     * If pin cache is disabled or the reader is using pinpad, we can get here
4019
     * with no PIN data. This is ok as we can not asynchronously invoke the prompt
4020
     * (unless the pinpad is in use).
4021
     * In this case, check if the PIN has been already verified and
4022
     * the access condition is still open on card.
4023
     */
4024
209
    if (pinsize == 0) {
4025
200
      r = sc_pkcs15_get_pin_info(p15card, pin_obj);
4026
      /* update local copy of auth info */
4027
200
      memcpy(&auth_info, pin_obj->data, sizeof(auth_info));
4028
4029
200
      if (r == SC_SUCCESS && auth_info.logged_in & SC_PIN_STATE_LOGGED_IN)
4030
200
        LOG_FUNC_RETURN(ctx, r);
4031
200
    }
4032
4033
105
    r = sc_pkcs15_verify_pin(p15card, pin_obj, use_pinpad || pinsize == 0 ? NULL : pinbuf, use_pinpad ? 0 : pinsize);
4034
105
    LOG_TEST_RET(ctx, r, "Cannot validate pkcs15 PIN");
4035
105
  }
4036
4037
45
  if (file)   {
4038
45
    r = sc_select_file(p15card->card, &file->path, NULL);
4039
45
    LOG_TEST_RET(ctx, r, "Failed to select PIN path");
4040
45
  }
4041
4042
26
  if (!pin_obj) {
4043
20
    struct sc_pin_cmd_data pin_cmd;
4044
4045
20
    memset(&pin_cmd, 0, sizeof(pin_cmd));
4046
20
    pin_cmd.cmd = SC_PIN_CMD_VERIFY;
4047
20
    pin_cmd.pin_type = type;
4048
20
    pin_cmd.pin_reference = reference;
4049
20
    pin_cmd.pin1.data = use_pinpad ? NULL : pinbuf;
4050
20
    pin_cmd.pin1.len = use_pinpad ? 0: pinsize;
4051
4052
20
    r = sc_pin_cmd(p15card->card, &pin_cmd, NULL);
4053
20
    LOG_TEST_RET(ctx, r, "'VERIFY' pin cmd failed");
4054
20
  }
4055
4056
12
  LOG_FUNC_RETURN(ctx, r);
4057
12
}
4058
4059
4060
/*
4061
 * Present any authentication info as required by the file.
4062
 *
4063
 * Depending on the SC_CARD_CAP_USE_FCI_AC caps file in sc_card_t,
4064
 * we read the ACs of the file on the card, or rely on the ACL
4065
 * info for that file in the profile file.
4066
 *
4067
 * In the latter case, there's a problem here if e.g. the SO PIN
4068
 * defined by the profile is optional, and hasn't been set.
4069
 * On the other hands, some cards do not return access conditions
4070
 * in their response to SELECT FILE), so the latter case has been
4071
 * used in most cards while the first case was added much later.
4072
 */
4073
int
4074
sc_pkcs15init_authenticate(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
4075
    struct sc_file *file, int op)
4076
8.06k
{
4077
8.06k
  struct sc_context *ctx = p15card->card->ctx;
4078
8.06k
  const struct sc_acl_entry *acl = NULL;
4079
8.06k
  struct sc_file *file_tmp = NULL;
4080
8.06k
  int  r = 0;
4081
4082
8.06k
  LOG_FUNC_CALLED(ctx);
4083
8.06k
  assert(file != NULL);
4084
8.06k
  sc_log(ctx, "path '%s', op=%u", sc_print_path(&file->path), op);
4085
4086
8.06k
  if (file->acl_inactive) {
4087
2.64k
    sc_log(ctx, "access control mechanism is not active (always allowed)");
4088
2.64k
    LOG_FUNC_RETURN(ctx, r);
4089
2.64k
  }
4090
4091
5.41k
  if (p15card->card->caps & SC_CARD_CAP_USE_FCI_AC) {
4092
1.18k
    r = sc_select_file(p15card->card, &file->path, &file_tmp);
4093
1.18k
    LOG_TEST_RET(ctx, r, "Authentication failed: cannot select file.");
4094
4095
614
    acl = sc_file_get_acl_entry(file_tmp, op);
4096
614
  }
4097
4.23k
  else   {
4098
4.23k
    acl = sc_file_get_acl_entry(file, op);
4099
4.23k
  }
4100
4.84k
  sc_log(ctx, "acl %p",acl);
4101
4102
6.04k
  for (; r == 0 && acl; acl = acl->next) {
4103
2.33k
    if (acl->method == SC_AC_NEVER)   {
4104
27
      sc_file_free(file_tmp);
4105
27
      LOG_TEST_RET(ctx, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Authentication failed: never allowed");
4106
27
    }
4107
2.30k
    else if (acl->method == SC_AC_NONE)   {
4108
1.07k
      sc_log(ctx, "always allowed");
4109
1.07k
      break;
4110
1.07k
    }
4111
1.22k
    else if (acl->method == SC_AC_UNKNOWN)  {
4112
26
      sc_log(ctx, "unknown acl method");
4113
26
      break;
4114
26
    }
4115
1.19k
    sc_log(ctx, "verify acl(method:%i,reference:%i)", acl->method, acl->key_ref);
4116
1.19k
    r = sc_pkcs15init_verify_secret(profile, p15card, file_tmp ? file_tmp : file, acl->method, acl->key_ref);
4117
1.19k
  }
4118
4119
4.81k
  sc_file_free(file_tmp);
4120
4121
4.81k
  LOG_FUNC_RETURN(ctx, r);
4122
4.81k
}
4123
4124
4125
static int
4126
do_select_parent(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
4127
    struct sc_file *file, struct sc_file **parent)
4128
3.27k
{
4129
3.27k
  struct sc_context *ctx = p15card->card->ctx;
4130
3.27k
  struct sc_path  path;
4131
3.27k
  int   r;
4132
4133
3.27k
  LOG_FUNC_CALLED(ctx);
4134
  /* Get the parent's path */
4135
3.27k
  path = file->path;
4136
3.27k
  if (path.len >= 2)
4137
3.03k
    path.len -= 2;
4138
3.27k
  if (!path.len && !path.aid.len)
4139
783
    sc_format_path("3F00", &path);
4140
4141
  /* Select the parent DF. */
4142
3.27k
  *parent = NULL;
4143
3.27k
  r = sc_select_file(p15card->card, &path, parent);
4144
  /* If DF doesn't exist, create it (unless it's the MF,
4145
   * but then something's badly broken anyway :-) */
4146
3.27k
  if (r == SC_ERROR_FILE_NOT_FOUND && path.len > 2) {
4147
246
    r = sc_profile_get_file_by_path(profile, &path, parent);
4148
246
    if (r < 0) {
4149
1
      sc_log(ctx, "no profile template for DF %s", sc_print_path(&path));
4150
1
      LOG_FUNC_RETURN(ctx, r);
4151
1
    }
4152
4153
245
    r = sc_pkcs15init_create_file(profile, p15card, *parent);
4154
245
    if (r < 0) {
4155
78
      sc_file_free(*parent);
4156
78
      *parent = NULL;
4157
78
    }
4158
245
    LOG_TEST_RET(ctx, r, "Cannot create parent DF");
4159
4160
167
    r = sc_select_file(p15card->card, &path, NULL);
4161
167
    if (r < 0) {
4162
32
      sc_file_free(*parent);
4163
32
      *parent = NULL;
4164
32
    }
4165
167
    LOG_TEST_RET(ctx, r, "Cannot select parent DF");
4166
167
  }
4167
3.02k
  else if (r == SC_SUCCESS && !strcmp(p15card->card->name, "STARCOS")) {
4168
    /* in case of starcos spk 2.3 SELECT FILE does not
4169
     * give us the ACLs => ask the profile */
4170
0
    sc_file_free(*parent);
4171
4172
0
    r = sc_profile_get_file_by_path(profile, &path, parent);
4173
0
    if (r < 0) {
4174
0
      sc_log(ctx, "in StarCOS profile there is no template for DF %s", sc_print_path(&path));
4175
0
      LOG_FUNC_RETURN(ctx, r);
4176
0
    }
4177
0
  }
4178
4179
3.16k
  LOG_FUNC_RETURN(ctx, r);
4180
3.16k
}
4181
4182
4183
int
4184
sc_pkcs15init_create_file(struct sc_profile *profile, struct sc_pkcs15_card *p15card,
4185
    struct sc_file *file)
4186
3.27k
{
4187
3.27k
  struct sc_context *ctx = p15card->card->ctx;
4188
3.27k
  struct sc_file  *parent = NULL;
4189
3.27k
  int   r;
4190
4191
3.27k
  LOG_FUNC_CALLED(ctx);
4192
3.27k
  if (!file) {
4193
0
    return SC_ERROR_INVALID_ARGUMENTS;
4194
0
  }
4195
4196
3.27k
  sc_log(ctx, "create file '%s'", sc_print_path(&file->path));
4197
  /* Select parent DF and verify PINs/key as necessary */
4198
3.27k
  r = do_select_parent(profile, p15card, file, &parent);
4199
3.27k
  LOG_TEST_RET(ctx, r, "Cannot create file: select parent error");
4200
4201
2.57k
  r = sc_pkcs15init_authenticate(profile, p15card, parent, SC_AC_OP_CREATE);
4202
2.57k
  LOG_TEST_GOTO_ERR(ctx, r, "Cannot create file: 'CREATE' authentication failed");
4203
4204
  /* Fix up the file's ACLs */
4205
2.37k
  r = sc_pkcs15init_fixup_file(profile, p15card, file);
4206
2.37k
  LOG_TEST_GOTO_ERR(ctx, r, "Cannot create file: file fixup failed");
4207
4208
  /* ensure we are in the correct lifecycle */
4209
2.36k
  r = sc_pkcs15init_set_lifecycle(p15card->card, SC_CARDCTRL_LIFECYCLE_ADMIN);
4210
2.36k
  if (r != SC_ERROR_NOT_SUPPORTED)
4211
2.36k
    LOG_TEST_GOTO_ERR(ctx, r, "Cannot create file: failed to set lifecycle 'ADMIN'");
4212
4213
2.35k
  r = sc_create_file(p15card->card, file);
4214
2.35k
  LOG_TEST_GOTO_ERR(ctx, r, "Create file failed");
4215
4216
2.57k
err:
4217
2.57k
  sc_file_free(parent);
4218
2.57k
  LOG_FUNC_RETURN(ctx, r);
4219
2.57k
}
4220
4221
4222
int
4223
sc_pkcs15init_update_file(struct sc_profile *profile,
4224
    struct sc_pkcs15_card *p15card, struct sc_file *file,
4225
    void *data, size_t datalen)
4226
3.07k
{
4227
3.07k
  struct sc_context *ctx = p15card->card->ctx;
4228
3.07k
  struct sc_file  *selected_file = NULL;
4229
3.07k
  void    *copy = NULL;
4230
3.07k
  int   r, need_to_zap = 0;
4231
4232
3.07k
  LOG_FUNC_CALLED(ctx);
4233
3.07k
  if (!file)
4234
3.07k
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
4235
4236
3.00k
  sc_log(ctx, "path:%s; datalen:%zu", sc_print_path(&file->path), datalen);
4237
4238
3.00k
  r = sc_select_file(p15card->card, &file->path, &selected_file);
4239
3.00k
  if (!r)   {
4240
983
    need_to_zap = 1;
4241
983
  }
4242
2.02k
  else if (r == SC_ERROR_FILE_NOT_FOUND)   {
4243
    /* Create file if it doesn't exist */
4244
1.60k
    if (file->size < datalen)
4245
509
      file->size = datalen;
4246
4247
1.60k
    r = sc_pkcs15init_create_file(profile, p15card, file);
4248
1.60k
    LOG_TEST_RET(ctx, r, "Failed to create file");
4249
4250
1.16k
    r = sc_select_file(p15card->card, &file->path, &selected_file);
4251
1.16k
    LOG_TEST_RET(ctx, r, "Failed to select newly created file");
4252
1.16k
  }
4253
417
  else   {
4254
417
    LOG_TEST_RET(ctx, r, "Failed to select file");
4255
417
  }
4256
4257
2.06k
  if (selected_file->size < datalen) {
4258
56
    sc_log(ctx,
4259
56
           "File %s too small (require %zu, have %"SC_FORMAT_LEN_SIZE_T"u)",
4260
56
           sc_print_path(&file->path), datalen,
4261
56
           selected_file->size);
4262
56
    sc_file_free(selected_file);
4263
56
    LOG_TEST_RET(ctx, SC_ERROR_FILE_TOO_SMALL, "Update file failed");
4264
56
  }
4265
2.01k
  else if (selected_file->size > datalen && need_to_zap) {
4266
    /* zero out the rest of the file - we may have shrunk
4267
     * the file contents */
4268
921
    if (selected_file->size > MAX_FILE_SIZE) {
4269
20
      sc_file_free(selected_file);
4270
20
      LOG_FUNC_RETURN(ctx, SC_ERROR_INTERNAL);
4271
20
    }
4272
4273
901
    copy = calloc(1, selected_file->size);
4274
901
    if (copy == NULL) {
4275
0
      sc_file_free(selected_file);
4276
0
      return SC_ERROR_OUT_OF_MEMORY;
4277
0
    }
4278
901
    memcpy(copy, data, datalen);
4279
901
    datalen = selected_file->size;
4280
901
    data = copy;
4281
901
  }
4282
4283
  /* Present authentication info needed */
4284
1.99k
  r = sc_pkcs15init_authenticate(profile, p15card, selected_file, SC_AC_OP_UPDATE);
4285
1.99k
  if (r >= 0 && datalen)
4286
1.18k
    r = sc_update_binary(p15card->card, 0, (const unsigned char *) data, datalen, 0);
4287
4288
1.99k
  if (copy)
4289
901
    free(copy);
4290
1.99k
  sc_file_free(selected_file);
4291
1.99k
  LOG_FUNC_RETURN(ctx, r);
4292
1.99k
}
4293
4294
/*
4295
 * Fix up a file's ACLs by replacing all occurrences of a symbolic
4296
 * PIN name with the real reference.
4297
 */
4298
static int
4299
sc_pkcs15init_fixup_acls(struct sc_pkcs15_card *p15card, struct sc_file *file,
4300
    struct sc_acl_entry *so_acl, struct sc_acl_entry *user_acl)
4301
1.16k
{
4302
1.16k
  struct sc_context *ctx = p15card->card->ctx;
4303
1.16k
  unsigned int  op;
4304
1.16k
  int   r = 0;
4305
4306
1.16k
  LOG_FUNC_CALLED(ctx);
4307
36.0k
  for (op = 0; r == 0 && op < SC_MAX_AC_OPS; op++) {
4308
34.8k
    struct sc_acl_entry acls[SC_MAX_OP_ACS];
4309
34.8k
    const struct sc_acl_entry *acl;
4310
34.8k
    const char  *what;
4311
34.8k
    int   added = 0, num, ii;
4312
4313
    /* First, get original ACLs */
4314
34.8k
    acl = sc_file_get_acl_entry(file, op);
4315
69.7k
    for (num = 0; num < SC_MAX_OP_ACS && acl; num++, acl = acl->next)
4316
34.8k
      acls[num] = *acl;
4317
4318
34.8k
    sc_file_clear_acl_entries(file, op);
4319
69.7k
    for (ii = 0; ii < num; ii++) {
4320
34.8k
      acl = acls + ii;
4321
34.8k
      if (acl->method != SC_AC_SYMBOLIC)
4322
32.2k
        goto next;
4323
4324
2.66k
      if (acl->key_ref == SC_PKCS15INIT_SO_PIN) {
4325
919
        acl = so_acl;
4326
919
        what = "SO PIN";
4327
919
      }
4328
1.74k
      else if (acl->key_ref == SC_PKCS15INIT_USER_PIN) {
4329
1.70k
        acl = user_acl;
4330
1.70k
        what = "user PIN";
4331
1.70k
      }
4332
46
      else {
4333
46
        sc_log(ctx, "ACL references unknown symbolic PIN %d", acl->key_ref);
4334
46
        return SC_ERROR_INVALID_ARGUMENTS;
4335
46
      }
4336
4337
      /* If we weren't given a replacement ACL,
4338
       * leave the original ACL untouched */
4339
2.61k
      if (acl->key_ref == (unsigned int)-1) {
4340
0
        sc_log(ctx, "ACL references %s, which is not defined", what);
4341
0
        return SC_ERROR_INVALID_ARGUMENTS;
4342
0
      }
4343
4344
2.61k
      if (acl->method == SC_AC_NONE)
4345
524
        continue;
4346
34.3k
    next:
4347
34.3k
      sc_file_add_acl_entry(file, op, acl->method, acl->key_ref);
4348
34.3k
      added++;
4349
34.3k
    }
4350
34.8k
    if (!added)
4351
524
      sc_file_add_acl_entry(file, op, SC_AC_NONE, 0);
4352
34.8k
  }
4353
4354
1.11k
  LOG_FUNC_RETURN(ctx, r);
4355
1.11k
}
4356
4357
4358
/*
4359
 * Fix up all file ACLs
4360
 */
4361
int
4362
sc_pkcs15init_fixup_file(struct sc_profile *profile,
4363
    struct sc_pkcs15_card *p15card, struct sc_file *file)
4364
4.17k
{
4365
4.17k
  struct sc_context *ctx = profile->card->ctx;
4366
4.17k
  struct sc_acl_entry so_acl, user_acl;
4367
4.17k
  unsigned int  op, needfix = 0;
4368
4.17k
  int   rv, pin_ref;
4369
4370
4.17k
  LOG_FUNC_CALLED(ctx);
4371
  /* First, loop over all ACLs to find out whether there
4372
   * are still any symbolic references.
4373
   */
4374
133k
  for (op = 0; op < SC_MAX_AC_OPS; op++) {
4375
129k
    const struct sc_acl_entry *acl;
4376
4377
129k
    acl = sc_file_get_acl_entry(file, op);
4378
257k
    for (; acl; acl = acl->next)
4379
128k
      if (acl->method == SC_AC_SYMBOLIC)
4380
2.69k
        needfix++;
4381
129k
  }
4382
4383
4.17k
  if (!needfix)
4384
4.17k
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
4385
4386
1.16k
  pin_ref = sc_pkcs15init_get_pin_reference(p15card, profile, SC_AC_SYMBOLIC, SC_PKCS15INIT_SO_PIN);
4387
1.16k
  if (pin_ref < 0) {
4388
331
    so_acl.method = SC_AC_NONE;
4389
331
    so_acl.key_ref = 0;
4390
331
  }
4391
832
  else {
4392
832
    so_acl.method = SC_AC_CHV;
4393
832
    so_acl.key_ref = pin_ref;
4394
832
  }
4395
4396
1.16k
  pin_ref = sc_pkcs15init_get_pin_reference(p15card, profile, SC_AC_SYMBOLIC, SC_PKCS15INIT_USER_PIN);
4397
1.16k
  if (pin_ref < 0) {
4398
370
    user_acl.method = SC_AC_NONE;
4399
370
    user_acl.key_ref = 0;
4400
370
  }
4401
793
  else {
4402
793
    user_acl.method = SC_AC_CHV;
4403
793
    user_acl.key_ref = pin_ref;
4404
793
  }
4405
1.16k
  sc_log(ctx, "so_acl(method:%X,ref:%X), user_acl(method:%X,ref:%X)",
4406
1.16k
      so_acl.method, so_acl.key_ref, user_acl.method, user_acl.key_ref);
4407
4408
1.16k
  rv = sc_pkcs15init_fixup_acls(p15card, file, &so_acl, &user_acl);
4409
4410
1.16k
  LOG_FUNC_RETURN(ctx, rv);
4411
1.16k
}
4412
4413
4414
static int
4415
sc_pkcs15init_get_pin_path(struct sc_pkcs15_card *p15card,
4416
    struct sc_pkcs15_id *auth_id, struct sc_path *path)
4417
50
{
4418
50
  struct sc_pkcs15_object *obj;
4419
50
  int r;
4420
4421
50
  r = sc_pkcs15_find_pin_by_auth_id(p15card, auth_id, &obj);
4422
50
  if (r < 0)
4423
33
    return r;
4424
17
  *path = ((struct sc_pkcs15_auth_info *) obj->data)->path;
4425
17
  return SC_SUCCESS;
4426
50
}
4427
4428
4429
int
4430
sc_pkcs15init_get_pin_info(struct sc_profile *profile, int id, struct sc_pkcs15_auth_info *pin)
4431
12.8k
{
4432
12.8k
  sc_profile_get_pin_info(profile, id, pin);
4433
12.8k
  return SC_SUCCESS;
4434
12.8k
}
4435
4436
4437
int
4438
sc_pkcs15init_get_manufacturer(struct sc_profile *profile, const char **res)
4439
0
{
4440
0
  *res = profile->p15_spec->tokeninfo->manufacturer_id;
4441
0
  return SC_SUCCESS;
4442
0
}
4443
4444
int
4445
sc_pkcs15init_get_serial(struct sc_profile *profile, const char **res)
4446
0
{
4447
0
  *res = profile->p15_spec->tokeninfo->serial_number;
4448
0
  return SC_SUCCESS;
4449
0
}
4450
4451
4452
int
4453
sc_pkcs15init_set_serial(struct sc_profile *profile, const char *serial)
4454
129
{
4455
129
  if (profile->p15_spec->tokeninfo->serial_number)
4456
129
    free(profile->p15_spec->tokeninfo->serial_number);
4457
129
  profile->p15_spec->tokeninfo->serial_number = strdup(serial);
4458
4459
129
  return SC_SUCCESS;
4460
129
}
4461
4462
4463
/*
4464
 * Card specific sanity check procedure.
4465
 */
4466
int
4467
sc_pkcs15init_sanity_check(struct sc_pkcs15_card *p15card, struct sc_profile *profile)
4468
4.46k
{
4469
4.46k
  struct sc_context *ctx = p15card->card->ctx;
4470
4.46k
  int rv = SC_ERROR_NOT_SUPPORTED;
4471
4472
4.46k
  LOG_FUNC_CALLED(ctx);
4473
4.46k
  if (profile->ops->sanity_check)
4474
339
    rv = profile->ops->sanity_check(profile, p15card);
4475
4476
4.46k
  LOG_FUNC_RETURN(ctx, rv);
4477
4.46k
}
4478
4479
4480
static int
4481
sc_pkcs15init_qualify_pin(struct sc_card *card, const char *pin_name,
4482
    size_t pin_len, struct sc_pkcs15_auth_info *auth_info)
4483
7.80k
{
4484
7.80k
  struct sc_context *ctx = card->ctx;
4485
7.80k
  struct sc_pkcs15_pin_attributes *pin_attrs;
4486
4487
7.80k
  LOG_FUNC_CALLED(ctx);
4488
7.80k
  if (auth_info == NULL)
4489
7.80k
    LOG_FUNC_RETURN(ctx, SC_ERROR_OBJECT_NOT_FOUND);
4490
4491
7.80k
  if (pin_len == 0 || auth_info->auth_type != SC_PKCS15_PIN_AUTH_TYPE_PIN)
4492
7.80k
    LOG_FUNC_RETURN(ctx, SC_SUCCESS);
4493
4494
7.63k
  pin_attrs = &auth_info->attrs.pin;
4495
4496
7.63k
  if (pin_len < pin_attrs->min_length) {
4497
9
    sc_log(ctx,
4498
9
           "%s too short (min length %"SC_FORMAT_LEN_SIZE_T"u)",
4499
9
           pin_name, pin_attrs->min_length);
4500
9
    LOG_FUNC_RETURN(ctx, SC_ERROR_WRONG_LENGTH);
4501
9
  }
4502
7.62k
  if (pin_len > pin_attrs->max_length) {
4503
4.99k
    sc_log(ctx,
4504
4.99k
           "%s too long (max length %"SC_FORMAT_LEN_SIZE_T"u)",
4505
4.99k
           pin_name, pin_attrs->max_length);
4506
4.99k
    LOG_FUNC_RETURN(ctx, SC_ERROR_WRONG_LENGTH);
4507
4.99k
  }
4508
4509
2.63k
  LOG_FUNC_RETURN(ctx, SC_SUCCESS);
4510
2.63k
}
4511
4512
4513
/*
4514
 * Get the list of options from the card, if it specifies them
4515
 */
4516
static int
4517
sc_pkcs15init_read_info(struct sc_card *card, struct sc_profile *profile)
4518
11.0k
{
4519
11.0k
  struct sc_path  path;
4520
11.0k
  struct sc_file  *file = NULL;
4521
11.0k
  unsigned char *mem = NULL;
4522
11.0k
  size_t    len = 0;
4523
11.0k
  int   r;
4524
4525
11.0k
  sc_format_path(OPENSC_INFO_FILEPATH, &path);
4526
11.0k
  r = sc_select_file(card, &path, &file);
4527
11.0k
  if (r >= 0) {
4528
858
    len = file->size;
4529
858
    sc_file_free(file);
4530
858
    if (len > MAX_FILE_SIZE)
4531
26
      return SC_ERROR_INTERNAL;
4532
832
    mem = malloc(len);
4533
832
    if (mem != NULL)
4534
832
      r = sc_read_binary(card, 0, mem, len, 0);
4535
0
    else
4536
0
      r = SC_ERROR_OUT_OF_MEMORY;
4537
832
  }
4538
10.1k
  else   {
4539
10.1k
    r = 0;
4540
10.1k
    sc_file_free(file);
4541
10.1k
  }
4542
4543
10.9k
  if (r >= 0)
4544
10.7k
    r = sc_pkcs15init_parse_info(card, mem, r, profile);
4545
4546
10.9k
  if (mem)
4547
832
    free(mem);
4548
10.9k
  return r;
4549
11.0k
}
4550
4551
4552
static int
4553
set_info_string(char **strp, const u8 *p, size_t len)
4554
3.96k
{
4555
3.96k
  char  *s;
4556
4557
3.96k
  if (!(s = malloc(len+1)))
4558
0
    return SC_ERROR_OUT_OF_MEMORY;
4559
3.96k
  memcpy(s, p, len);
4560
3.96k
  s[len] = '\0';
4561
3.96k
  if (*strp)
4562
3.73k
    free(*strp);
4563
3.96k
  *strp = s;
4564
3.96k
  return SC_SUCCESS;
4565
3.96k
}
4566
4567
/*
4568
 * Parse OpenSC Info file. We rudely clobber any information
4569
 * given on the command line.
4570
 *
4571
 * passed is a pointer (p) to (len) bytes. Those bytes contain
4572
 * one or several tag-length-value constructs, where tag and
4573
 * length are both single bytes. a final 0x00 or 0xff byte
4574
 * (with or without len byte) is ok.
4575
 */
4576
static int
4577
sc_pkcs15init_parse_info(struct sc_card *card,
4578
    const unsigned char *p, size_t len, struct sc_profile *profile)
4579
10.7k
{
4580
10.7k
  unsigned char tag;
4581
10.7k
  const unsigned char *end;
4582
10.7k
  unsigned int  nopts = 0;
4583
10.7k
  size_t    n;
4584
10.7k
  int r = 0;
4585
4586
10.7k
  if ((p == NULL) || (len == 0))
4587
10.5k
    return 0;
4588
4589
222
  end = p + (len - 1);
4590
4.70k
  while (p < end) { /* more bytes to look at */
4591
4.61k
    r = 0;
4592
4593
4.61k
    tag = *p; p++;
4594
4.61k
    if ((tag == 0) || (tag == 0xff) || (p >= end))
4595
90
      break;
4596
4597
4.52k
    n = *p;
4598
4.52k
    p++;
4599
4600
4.52k
    if (p >= end || p + n > end) { /* invalid length byte n */
4601
43
      r = SC_ERROR_PKCS15INIT;
4602
43
      goto error;
4603
43
    }
4604
4605
4.48k
    switch (tag) {
4606
3.73k
    case OPENSC_INFO_TAG_PROFILE:
4607
3.73k
      r = set_info_string(&profile->name, p, n);
4608
3.73k
      if (r < 0)
4609
0
        goto error;
4610
3.73k
      break;
4611
3.73k
    case OPENSC_INFO_TAG_OPTION:
4612
228
      if (nopts >= SC_PKCS15INIT_MAX_OPTIONS - 1) {
4613
1
        sc_log(card->ctx, "Too many options in OpenSC Info file");
4614
1
        r = SC_ERROR_PKCS15INIT;
4615
1
        goto error;
4616
1
      }
4617
227
      r = set_info_string(&profile->options[nopts], p, n);
4618
227
      if (r < 0)
4619
0
        goto error;
4620
227
      profile->options[++nopts] = NULL;
4621
227
      break;
4622
522
    default:
4623
522
      /* Unknown options ignored */ ;
4624
4.48k
    }
4625
4.48k
    p += n;
4626
4.48k
  }
4627
178
  return 0;
4628
4629
44
error:
4630
44
  sc_log(card->ctx, "OpenSC info file corrupted");
4631
44
  if (profile->name) {
4632
44
    free(profile->name);
4633
44
    profile->name = NULL;
4634
44
  }
4635
81
  for (size_t i = 0; i < nopts; i++) {
4636
37
    if (profile->options[i])
4637
37
      free(profile->options[i]);
4638
37
    profile->options[i] = NULL;
4639
37
  }
4640
44
  return r;
4641
222
}
4642
4643
4644
static int
4645
do_encode_string(unsigned char **memp, unsigned char *end,
4646
    unsigned char tag, const char *s)
4647
90
{
4648
90
  unsigned char *p = *memp;
4649
90
  size_t  n;
4650
4651
90
  n = s ? strlen(s) : 0;
4652
90
  if (n > 255)
4653
0
    return SC_ERROR_BUFFER_TOO_SMALL;
4654
90
  if (p + 2 + n > end)
4655
0
    return SC_ERROR_BUFFER_TOO_SMALL;
4656
90
  *p++ = tag;
4657
90
  *p++ = n;
4658
90
  memcpy(p, s, n);
4659
90
  *memp = p + n;
4660
90
  return 0;
4661
90
}
4662
4663
4664
static int
4665
sc_pkcs15init_write_info(struct sc_pkcs15_card *p15card,
4666
    struct sc_profile *profile,
4667
    struct sc_pkcs15_object *pin_obj)
4668
90
{
4669
90
  struct sc_file  *file = NULL, *df = profile->df_info->file;
4670
90
  unsigned char buffer[128], *p, *end;
4671
90
  unsigned int  method;
4672
90
  unsigned long key_ref;
4673
90
  int   n, r;
4674
4675
90
  if (profile->ops->emu_write_info)
4676
0
    return profile->ops->emu_write_info(profile, p15card, pin_obj);
4677
4678
90
  memset(buffer, 0, sizeof(buffer));
4679
4680
90
  file = sc_file_new();
4681
90
  file->path.type = SC_PATH_TYPE_PATH;
4682
90
  memcpy(file->path.value, df->path.value, df->path.len);
4683
90
  file->path.len = df->path.len;
4684
90
  sc_append_file_id(&file->path, OPENSC_INFO_FILEID);
4685
90
  file->type = SC_FILE_TYPE_WORKING_EF;
4686
90
  file->ef_structure = SC_FILE_EF_TRANSPARENT;
4687
90
  file->id = OPENSC_INFO_FILEID;
4688
90
  file->size = sizeof(buffer);
4689
4690
90
  if (pin_obj != NULL) {
4691
90
    method = SC_AC_CHV;
4692
90
    key_ref = ((struct sc_pkcs15_auth_info *) pin_obj->data)->attrs.pin.reference;
4693
90
  }
4694
0
  else {
4695
0
    method = SC_AC_NONE; /* Unprotected */
4696
0
    key_ref = 0;
4697
0
  }
4698
2.88k
  for (n = 0; n < SC_MAX_AC_OPS; n++) {
4699
2.79k
    if (n == SC_AC_OP_READ)
4700
90
      sc_file_add_acl_entry(file, n, SC_AC_NONE, 0);
4701
2.70k
    else
4702
2.70k
      sc_file_add_acl_entry(file, n, method, key_ref);
4703
2.79k
  }
4704
4705
90
  p = buffer;
4706
90
  end = buffer + sizeof(buffer);
4707
4708
90
  r = do_encode_string(&p, end, OPENSC_INFO_TAG_PROFILE, profile->name);
4709
90
  for (n = 0; r >= 0 && profile->options[n]; n++)
4710
0
    r = do_encode_string(&p, end, OPENSC_INFO_TAG_OPTION, profile->options[n]);
4711
4712
90
  if (r >= 0)
4713
90
    r = sc_pkcs15init_update_file(profile, p15card, file, buffer, (unsigned int)file->size);
4714
4715
90
  sc_file_free(file);
4716
90
  return r;
4717
90
}