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