1 /*
2  * CardOS specific operation for PKCS15 initialization
3  *
4  * Copyright (C) 2005 Nils Larsch <nils@larsch.net>
5  * Copyright (C) 2002 Olaf Kirch <okir@suse.de>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21 
22 #include "config.h"
23 
24 #include <sys/types.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <assert.h>
28 #include <stdarg.h>
29 
30 #include "libopensc/opensc.h"
31 #include "libopensc/cardctl.h"
32 #include "libopensc/log.h"
33 #include "libopensc/cards.h"
34 #include "libopensc/asn1.h"
35 #include "pkcs15-init.h"
36 #include "profile.h"
37 
38 #ifndef MIN
39 # define MIN(a, b)	(((a) < (b))? (a) : (b))
40 #endif
41 
42 struct tlv {
43 	unsigned char *		base;
44 	unsigned char *		end;
45 	unsigned char *		current;
46 	unsigned char *		next;
47 };
48 
49 /*
50  * Local functions
51  */
52 static int	cardos_store_pin(sc_profile_t *profile, sc_card_t *card,
53 			sc_pkcs15_auth_info_t *auth_info, int puk_id,
54 			const u8 *pin, size_t pin_len);
55 static int	cardos_create_sec_env(sc_profile_t *, sc_card_t *,
56 			unsigned int, unsigned int);
57 static int	cardos_put_key(struct sc_profile *, sc_pkcs15_card_t *,
58 			int, sc_pkcs15_prkey_info_t *,
59 		       	struct sc_pkcs15_prkey_rsa *);
60 static int	cardos_key_algorithm(unsigned int, size_t, int *);
61 static int	cardos_extract_pubkey(sc_card_t *, sc_pkcs15_pubkey_t *,
62 			sc_file_t *, int);
63 static int	do_cardos_extract_pubkey(sc_card_t *card, int nr, u8 tag,
64 			sc_pkcs15_bignum_t *bn);
65 static int	cardos_have_verifyrc_package(sc_card_t *card);
66 
67 /* Object IDs for PIN objects.
68  * SO PIN = 0x01, SO PUK = 0x02
69  * each user pin is 2*N+1, each corresponding PUK is 2*N+2
70  */
71 #define CARDOS_PIN_ID_MIN	1
72 #define CARDOS_PIN_ID_MAX	15
73 #define CARDOS_KEY_ID_MIN	16
74 #define CARDOS_KEY_ID_MAX	31
75 #define CARDOS_AC_NEVER		0xFF
76 
77 #define CARDOS_ALGO_RSA			0x08
78 #define CARDOS_ALGO_RSA_PURE		0x0C
79 #define CARDOS_ALGO_RSA_SIG		0x88
80 #define CARDOS_ALGO_RSA_PURE_SIG	0x8C
81 #define CARDOS_ALGO_RSA_SIG_SHA1	0xC8
82 #define CARDOS_ALGO_RSA_PURE_SIG_SHA1	0xCC
83 #define CARDOS_ALGO_EXT_RSA_PURE	0x0a
84 #define CARDOS_ALGO_EXT_RSA_SIG_PURE	0x8a
85 #define CARDOS_ALGO_PIN			0x87
86 
tlv_init(struct tlv * tlv,u8 * base,size_t size)87 static void tlv_init(struct tlv *tlv, u8 *base, size_t size)
88 {
89 	tlv->base = base;
90 	tlv->end = base + size;
91 	tlv->current = tlv->next = base;
92 }
93 
tlv_next(struct tlv * tlv,u8 tag)94 static void tlv_next(struct tlv *tlv, u8 tag)
95 {
96 	assert(tlv->next + 2 < tlv->end);
97 	tlv->current = tlv->next;
98 	*(tlv->next++) = tag;
99 	*(tlv->next++) = 0;
100 }
101 
tlv_add(struct tlv * tlv,u8 val)102 static void tlv_add(struct tlv *tlv, u8 val)
103 {
104 	assert(tlv->next + 1 < tlv->end);
105 	*(tlv->next++) = val;
106 	tlv->current[1]++;
107 }
108 
109 static size_t
tlv_len(struct tlv * tlv)110 tlv_len(struct tlv *tlv)
111 {
112 	return tlv->next - tlv->base;
113 }
114 
115 /*
116  * Try to delete pkcs15 structure
117  * This is not quite the same as erasing the whole token, but
118  * it's close enough to be useful.
119  */
120 static int
cardos_erase(struct sc_profile * profile,sc_pkcs15_card_t * p15card)121 cardos_erase(struct sc_profile *profile, sc_pkcs15_card_t *p15card)
122 {
123 	return sc_pkcs15init_erase_card_recursively(p15card, profile);
124 }
125 
126 /*
127  * Create the Application DF
128  */
129 static int
cardos_create_dir(sc_profile_t * profile,sc_pkcs15_card_t * p15card,sc_file_t * df)130 cardos_create_dir(sc_profile_t *profile, sc_pkcs15_card_t *p15card, sc_file_t *df)
131 {
132 	int	r;
133 
134 	/* Create the application DF */
135 	if ((r = sc_pkcs15init_create_file(profile, p15card, df)) < 0)
136 		return r;
137 
138 	if ((r = sc_select_file(p15card->card, &df->path, NULL)) < 0)
139 		return r;
140 
141 	/* Create a default security environment for this DF.
142 	 * This SE automatically becomes the current SE when the
143 	 * DF is selected. */
144 	if ((r = cardos_create_sec_env(profile, p15card->card, 0x01, 0x00)) < 0)
145 		return r;
146 
147 	return 0;
148 }
149 
150 /*
151  * Caller passes in a suggested PIN reference.
152  * See if it's good, and if it isn't, propose something better
153  */
154 static int
cardos_select_pin_reference(sc_profile_t * profile,sc_pkcs15_card_t * p15card,sc_pkcs15_auth_info_t * auth_info)155 cardos_select_pin_reference(sc_profile_t *profile, sc_pkcs15_card_t *p15card,
156 		sc_pkcs15_auth_info_t *auth_info)
157 {
158 	int	preferred, current;
159 
160 	if (auth_info->auth_type != SC_PKCS15_PIN_AUTH_TYPE_PIN)
161 		return SC_ERROR_OBJECT_NOT_VALID;
162 
163 	if ((current = auth_info->attrs.pin.reference) < 0)
164 		current = CARDOS_PIN_ID_MIN;
165 
166 	if (auth_info->attrs.pin.flags & SC_PKCS15_PIN_FLAG_SO_PIN) {
167 		preferred = 1;
168 		if (current > preferred)
169 			return SC_ERROR_TOO_MANY_OBJECTS;
170 	} else {
171 		preferred = current;
172 		/* PINs are even numbered, PUKs are odd */
173 		if (!(preferred & 1))
174 			preferred++;
175 	}
176 
177 	if (preferred > CARDOS_PIN_ID_MAX)
178 		return SC_ERROR_TOO_MANY_OBJECTS;
179 	auth_info->attrs.pin.reference = preferred;
180 
181 	return SC_SUCCESS;
182 }
183 
184 /*
185  * Store a PIN
186  */
187 static int
cardos_create_pin(sc_profile_t * profile,sc_pkcs15_card_t * p15card,sc_file_t * df,sc_pkcs15_object_t * pin_obj,const u8 * pin,size_t pin_len,const u8 * puk,size_t puk_len)188 cardos_create_pin(sc_profile_t *profile, sc_pkcs15_card_t *p15card, sc_file_t *df,
189 		sc_pkcs15_object_t *pin_obj,
190 		const u8 *pin, size_t pin_len,
191 		const u8 *puk, size_t puk_len)
192 {
193 	sc_pkcs15_auth_info_t *auth_info = (sc_pkcs15_auth_info_t *) pin_obj->data;
194 	struct sc_card *card = p15card->card;
195 	unsigned int	puk_id = CARDOS_AC_NEVER;
196 	int		r;
197 
198 	if (!pin || !pin_len)
199 		return SC_ERROR_INVALID_ARGUMENTS;
200 
201 	if (auth_info->auth_type != SC_PKCS15_PIN_AUTH_TYPE_PIN)
202 		return SC_ERROR_OBJECT_NOT_VALID;
203 
204 	r = sc_select_file(card, auth_info->attrs.pin.reference & 0x80 ? &df->path : sc_get_mf_path(), NULL);
205 	if (r < 0)
206 		return r;
207 
208 	if (puk && puk_len) {
209 		struct sc_pkcs15_auth_info puk_ainfo;
210 
211 		sc_profile_get_pin_info(profile,
212 				SC_PKCS15INIT_USER_PUK, &puk_ainfo);
213 		puk_ainfo.attrs.pin.reference = puk_id = auth_info->attrs.pin.reference + 1;
214 		r = cardos_store_pin(profile, card,
215 				&puk_ainfo, CARDOS_AC_NEVER,
216 				puk, puk_len);
217 	}
218 
219 	if (r >= 0) {
220 		r = cardos_store_pin(profile, card,
221 				auth_info, puk_id, pin, pin_len);
222 	}
223 
224 	return r;
225 }
226 
227 /*
228  * Select a key reference
229  */
230 static int
cardos_select_key_reference(sc_profile_t * profile,sc_pkcs15_card_t * p15card,sc_pkcs15_prkey_info_t * key_info)231 cardos_select_key_reference(sc_profile_t *profile, sc_pkcs15_card_t *p15card,
232 			sc_pkcs15_prkey_info_t *key_info)
233 {
234 	if (key_info->key_reference < CARDOS_KEY_ID_MIN)
235 		key_info->key_reference = CARDOS_KEY_ID_MIN;
236 	if (key_info->key_reference > CARDOS_KEY_ID_MAX)
237 		return SC_ERROR_TOO_MANY_OBJECTS;
238 	return 0;
239 }
240 
241 /*
242  * Create a private key object.
243  * This is a no-op.
244  */
245 static int
cardos_create_key(sc_profile_t * profile,sc_pkcs15_card_t * p15card,sc_pkcs15_object_t * obj)246 cardos_create_key(sc_profile_t *profile, sc_pkcs15_card_t *p15card,
247 			sc_pkcs15_object_t *obj)
248 {
249 	return 0;
250 }
251 
252 /*
253  * Store a private key object.
254  */
255 static int
cardos_store_key(sc_profile_t * profile,sc_pkcs15_card_t * p15card,sc_pkcs15_object_t * obj,sc_pkcs15_prkey_t * key)256 cardos_store_key(sc_profile_t *profile, sc_pkcs15_card_t *p15card,
257 			sc_pkcs15_object_t *obj,
258 			sc_pkcs15_prkey_t *key)
259 {
260 	struct sc_context *ctx = p15card->card->ctx;
261 	sc_pkcs15_prkey_info_t *key_info = (sc_pkcs15_prkey_info_t *) obj->data;
262 	struct sc_file *file = NULL;
263 	int		algorithm = 0, r;
264 
265 	if (obj->type != SC_PKCS15_TYPE_PRKEY_RSA) {
266 		sc_log(ctx,  "CardOS supports RSA keys only.");
267 		return SC_ERROR_NOT_SUPPORTED;
268 	}
269 
270 	if (cardos_key_algorithm(key_info->usage, key_info->modulus_length, &algorithm) < 0) {
271 		sc_log(ctx,  "CardOS does not support keys "
272 			       "that can both sign _and_ decrypt.");
273 		return SC_ERROR_NOT_SUPPORTED;
274 	}
275 
276 	r = sc_select_file(p15card->card, &key_info->path, &file);
277 	if (r)   {
278 		sc_log(ctx,  "Failed to store key: cannot select parent DF");
279 		return r;
280 	}
281 
282 	r = sc_pkcs15init_authenticate(profile, p15card, file, SC_AC_OP_UPDATE);
283 	sc_file_free(file);
284 	if (r)   {
285 		sc_log(ctx,  "Failed to store key: 'UPDATE' authentication failed");
286 		return r;
287 	}
288 
289 	r = cardos_put_key(profile, p15card, algorithm, key_info, &key->u.rsa);
290 
291 	return r;
292 }
293 
init_key_object(struct sc_pkcs15_prkey_rsa * key,u8 * data,size_t len)294 static void init_key_object(struct sc_pkcs15_prkey_rsa *key,
295 	u8 *data, size_t len)
296 {
297 	/* Create a key object, initializing components to 0xff */
298 	memset(key,  0x00, sizeof(*key));
299 	memset(data, 0xff, len);
300 	key->modulus.data = data;
301 	key->modulus.len  = len;
302 	key->d.data       = data;
303 	key->d.len        = len;
304 	key->p.len        = len >> 1;
305 	key->p.data       = data;
306 	key->q.len        = len >> 1;
307 	key->q.data       = data;
308 	key->iqmp.len     = len >> 1;
309 	key->iqmp.data    = data;
310 	key->dmp1.len     = len >> 1;
311 	key->dmp1.data    = data;
312 	key->dmq1.len     = len >> 1;
313 	key->dmq1.data    = data;
314 }
315 
316 /*
317  * Key generation
318  */
319 static int
cardos_generate_key(sc_profile_t * profile,sc_pkcs15_card_t * p15card,sc_pkcs15_object_t * obj,sc_pkcs15_pubkey_t * pubkey)320 cardos_generate_key(sc_profile_t *profile, sc_pkcs15_card_t *p15card,
321 		sc_pkcs15_object_t *obj,
322 		sc_pkcs15_pubkey_t *pubkey)
323 {
324 	struct sc_context *ctx = p15card->card->ctx;
325 	struct sc_pkcs15_prkey_info *key_info = (sc_pkcs15_prkey_info_t *) obj->data;
326 	struct sc_pkcs15_prkey_rsa key_obj;
327 	struct sc_cardctl_cardos_genkey_info args;
328 	struct sc_file	*temp;
329 	u8		abignum[256];
330 	int		algorithm = 0, r, delete_it = 0, use_ext_rsa = 0;
331 	size_t		keybits, rsa_max_size;
332 	int             pin_id = -1;
333 
334 	if (obj->type != SC_PKCS15_TYPE_PRKEY_RSA)
335 		return SC_ERROR_NOT_SUPPORTED;
336 
337 	rsa_max_size = (sc_card_find_rsa_alg(p15card->card, 2048) != NULL) ? 2048 : 1024;
338 	keybits = key_info->modulus_length & ~7UL;
339 	if (keybits > rsa_max_size) {
340 		sc_log(ctx,  "Unable to generate key, max size is %lu",
341 			(unsigned long) rsa_max_size);
342 		return SC_ERROR_INVALID_ARGUMENTS;
343 	}
344 
345 	if (keybits > 1024)
346 		use_ext_rsa = 1;
347 
348 	if (cardos_key_algorithm(key_info->usage, keybits, &algorithm) < 0) {
349 		sc_log(ctx,  "CardOS does not support keys "
350 			       "that can both sign _and_ decrypt.");
351 		return SC_ERROR_NOT_SUPPORTED;
352 	}
353 
354 	if (sc_profile_get_file(profile, "tempfile", &temp) < 0) {
355 		sc_log(ctx,  "Profile doesn't define temporary file "
356 				"for key generation.");
357 		return SC_ERROR_NOT_SUPPORTED;
358 	}
359 
360 	pin_id = sc_pkcs15init_get_pin_reference(p15card, profile,
361 			SC_AC_SYMBOLIC, SC_PKCS15INIT_USER_PIN);
362 	if (pin_id >= 0) {
363 		r = sc_pkcs15init_verify_secret(profile, p15card, NULL, SC_AC_CHV, pin_id);
364 		if (r < 0)
365 			return r;
366 	}
367 	if (use_ext_rsa == 0)
368 		temp->ef_structure = SC_FILE_EF_LINEAR_VARIABLE_TLV;
369 	else
370 		temp->ef_structure = SC_FILE_EF_TRANSPARENT;
371 
372 	if ((r = sc_pkcs15init_create_file(profile, p15card, temp)) < 0)
373 		goto out;
374 	delete_it = 1;
375 
376 	init_key_object(&key_obj, abignum, keybits >> 3);
377 
378 	r = cardos_put_key(profile, p15card, algorithm, key_info, &key_obj);
379 	if (r < 0)
380 		goto out;
381 
382 	memset(&args, 0, sizeof(args));
383 	args.key_id = key_info->key_reference;
384 	args.key_bits = keybits;
385 	args.fid = temp->id;
386 	r = sc_card_ctl(p15card->card, SC_CARDCTL_CARDOS_GENERATE_KEY, &args);
387 	if (r < 0)
388 		goto out;
389 
390 	r = cardos_extract_pubkey(p15card->card, pubkey, temp, use_ext_rsa);
391 out:
392 	if (delete_it != 0)
393 		sc_pkcs15init_rmdir(p15card, profile, temp);
394 	sc_file_free(temp);
395 
396 	if (r < 0) {
397 		if (pubkey->u.rsa.modulus.data)
398 			free (pubkey->u.rsa.modulus.data);
399 		if (pubkey->u.rsa.exponent.data)
400 			free (pubkey->u.rsa.exponent.data);
401 	}
402 	return r;
403 }
404 
405 /*
406  * Object deletion.
407  */
408 static int
cardos_delete_object(sc_profile_t * profile,struct sc_pkcs15_card * p15card,struct sc_pkcs15_object * obj,const struct sc_path * path)409 cardos_delete_object(sc_profile_t *profile, struct sc_pkcs15_card *p15card,
410 		struct sc_pkcs15_object *obj, const struct sc_path *path)
411 {
412 	int r = SC_SUCCESS, stored_in_ef = 0, algorithm = 0;
413 	size_t keybits;
414 	sc_file_t *file = NULL;
415 	struct sc_pkcs15_prkey_info *key_info;
416 	struct sc_pkcs15_prkey_rsa key_obj;
417 	struct sc_context *ctx = p15card->card->ctx;
418 	uint8_t abignum[256];
419 
420 	LOG_FUNC_CALLED(ctx);
421 	/*
422 	 * If we are deleting a private key, overwrite it so it can't be used.
423 	 */
424 	if ((obj->type & SC_PKCS15_TYPE_CLASS_MASK) == SC_PKCS15_TYPE_PRKEY) {
425 		key_info = obj->data;
426 		keybits = key_info->modulus_length & ~7UL;
427 		init_key_object(&key_obj, abignum, keybits >> 3);
428 		r = cardos_key_algorithm(key_info->usage, keybits, &algorithm);
429 		LOG_TEST_RET(ctx, r, "cardos_key_algorithm failed");
430 
431 		r = sc_select_file(p15card->card, &key_info->path, &file);
432 		LOG_TEST_RET(ctx, r, "Failed to store key: cannot select parent DF");
433 
434 		r = sc_pkcs15init_authenticate(profile, p15card, file, SC_AC_OP_UPDATE);
435 		sc_file_free(file);
436 		LOG_TEST_RET(ctx, r, "Failed to store key: UPDATE authentication failed");
437 
438 		r = cardos_put_key(profile, p15card, algorithm, key_info, &key_obj);
439 		LOG_TEST_RET(ctx, r, "cardos_put_key failed");
440 	}
441 
442 	/* Delete object from the PKCS15 file system. */
443 	if (path->len || path->aid.len)   {
444 		r = sc_select_file(p15card->card, path, &file);
445 		if (r != SC_ERROR_FILE_NOT_FOUND)
446 			LOG_TEST_RET(ctx, r, "select object path failed");
447 
448 		stored_in_ef = (file->type != SC_FILE_TYPE_DF);
449 		sc_file_free(file);
450 	}
451 
452 	/* If the object is stored in a normal EF, try to delete the EF. */
453 	if (r == SC_SUCCESS && stored_in_ef) {
454 		r = sc_pkcs15init_delete_by_path(profile, p15card, path);
455 		LOG_TEST_RET(ctx, r, "Failed to delete object by path");
456 	}
457 
458 	LOG_FUNC_RETURN(ctx, SC_SUCCESS);
459 }
460 
461 /*
462  * Store a PIN or PUK
463  */
464 static int
cardos_store_pin(sc_profile_t * profile,sc_card_t * card,sc_pkcs15_auth_info_t * auth_info,int puk_id,const u8 * pin,size_t pin_len)465 cardos_store_pin(sc_profile_t *profile, sc_card_t *card,
466 		sc_pkcs15_auth_info_t *auth_info, int puk_id,
467 		const u8 *pin, size_t pin_len)
468 {
469 	struct sc_cardctl_cardos_obj_info args;
470 	unsigned char	buffer[256];
471 	unsigned char	pinpadded[256];
472 	struct tlv	tlv;
473 	unsigned int	attempts, minlen, maxlen;
474 	int		r, hasverifyrc;
475 
476 	if (auth_info->auth_type != SC_PKCS15_PIN_AUTH_TYPE_PIN)
477 		return SC_ERROR_OBJECT_NOT_VALID;
478 
479 	/* We need to do padding because pkcs15-lib.c does it.
480 	 * Would be nice to have a flag in the profile that says
481 	 * "no padding required". */
482 	maxlen = MIN(profile->pin_maxlen, sizeof(pinpadded));
483 	if (pin_len > maxlen) {
484 		sc_log(card->ctx,
485 			 "invalid pin length: %"SC_FORMAT_LEN_SIZE_T"u (max %u)\n",
486 			 pin_len, maxlen);
487 		return SC_ERROR_INVALID_ARGUMENTS;
488 	}
489 	memcpy(pinpadded, pin, pin_len);
490 	while (pin_len < maxlen)
491 		pinpadded[pin_len++] = profile->pin_pad_char;
492 	pin = pinpadded;
493 
494 	attempts = auth_info->tries_left;
495 	minlen = auth_info->attrs.pin.min_length;
496 
497 	tlv_init(&tlv, buffer, sizeof(buffer));
498 
499 	/* object address: class, id */
500 	tlv_next(&tlv, 0x83);
501 	tlv_add(&tlv, 0x00);		/* class byte: usage TEST, k=0 */
502 	tlv_add(&tlv, auth_info->attrs.pin.reference & 0x7f);
503 
504 	/* parameters */
505 	tlv_next(&tlv, 0x85);
506 	tlv_add(&tlv, 0x02);		/* options byte */
507 	hasverifyrc = cardos_have_verifyrc_package(card);
508 	if (hasverifyrc == 1)
509 		/* Use 9 byte OCI parameters to be able to set VerifyRC bit	*/
510 		tlv_add(&tlv, 0x04);	/* options_2 byte with bit 2 set to return CurrentErrorCounter	*/
511 	tlv_add(&tlv, attempts & 0xf);	/* flags byte */
512 	tlv_add(&tlv, CARDOS_ALGO_PIN);	/* algorithm = pin-test */
513 	tlv_add(&tlv, attempts & 0xf);	/* errcount = attempts */
514 
515 	/* usecount: not documented, but seems to work like this:
516 	 *  -	value of 0xff means pin can be presented any number
517 	 *	of times
518 	 *  -	anything less: max # of times before BS object is blocked.
519 	 */
520 	tlv_add(&tlv, 0xff);
521 
522 	/* DEK: not documented, no idea what it means */
523 	tlv_add(&tlv, 0xff);
524 
525 	/* ARA counter: number of times the test object can be used before
526 	 *              another verification is required (~ user consent)
527 	 *              (0x00 unlimited usage)
528 	 */
529 	tlv_add(&tlv, 0x00);
530 
531 	tlv_add(&tlv, minlen);			/* minlen */
532 
533 	/* AC conditions */
534 	tlv_next(&tlv, 0x86);
535 	tlv_add(&tlv, 0x00);			/* use: always */
536 	tlv_add(&tlv, auth_info->attrs.pin.reference);	/* change: PIN */
537 	tlv_add(&tlv, puk_id);			/* unblock: PUK */
538 
539 	/* data: PIN */
540 	tlv_next(&tlv, 0x8f);
541 	while (pin_len--)
542 		tlv_add(&tlv, *pin++);
543 
544 	args.data = buffer;
545 	args.len = tlv_len(&tlv);
546 
547 	/* ensure we are in the correct lifecycle */
548 	r = sc_pkcs15init_set_lifecycle(card, SC_CARDCTRL_LIFECYCLE_ADMIN);
549 	if (r < 0 && r != SC_ERROR_NOT_SUPPORTED)
550 		return r;
551 
552 	return sc_card_ctl(card, SC_CARDCTL_CARDOS_PUT_DATA_OCI, &args);
553 }
554 
555 /*
556  * Create an empty security environment
557  */
558 static int
cardos_create_sec_env(struct sc_profile * profile,sc_card_t * card,unsigned int se_id,unsigned int key_id)559 cardos_create_sec_env(struct sc_profile *profile, sc_card_t *card,
560 		unsigned int se_id, unsigned int key_id)
561 {
562 	struct sc_cardctl_cardos_obj_info args;
563 	struct tlv	tlv;
564 	unsigned char	buffer[64];
565 	int		r;
566 
567 	tlv_init(&tlv, buffer, sizeof(buffer));
568 	tlv_next(&tlv, 0x83);
569 	tlv_add(&tlv, se_id);
570 
571 	tlv_next(&tlv, 0x86);
572 	tlv_add(&tlv, 0);
573 	tlv_add(&tlv, 0);
574 
575 	tlv_next(&tlv, 0x8f);
576 	tlv_add(&tlv, key_id);
577 	tlv_add(&tlv, key_id);
578 	tlv_add(&tlv, key_id);
579 	tlv_add(&tlv, key_id);
580 	tlv_add(&tlv, key_id);
581 	tlv_add(&tlv, key_id);
582 
583 	args.data = buffer;
584 	args.len = tlv_len(&tlv);
585 
586 	/* ensure we are in the correct lifecycle */
587 	r = sc_pkcs15init_set_lifecycle(card, SC_CARDCTRL_LIFECYCLE_ADMIN);
588 	if (r < 0 && r != SC_ERROR_NOT_SUPPORTED)
589 		return r;
590 
591 	return sc_card_ctl(card, SC_CARDCTL_CARDOS_PUT_DATA_SECI, &args);
592 }
593 
594 /*
595  * Determine the key algorithm based on the intended usage
596  * Note that CardOS/M4 does not support keys that can be used
597  * for signing _and_ decipherment
598  */
599 #define USAGE_ANY_SIGN		(SC_PKCS15_PRKEY_USAGE_SIGN|\
600 				 SC_PKCS15_PRKEY_USAGE_NONREPUDIATION)
601 #define USAGE_ANY_DECIPHER	(SC_PKCS15_PRKEY_USAGE_DECRYPT|\
602 				 SC_PKCS15_PRKEY_USAGE_UNWRAP)
603 
cardos_key_algorithm(unsigned int usage,size_t keylen,int * algop)604 static int cardos_key_algorithm(unsigned int usage, size_t keylen, int *algop)
605 {
606 	/* if it is sign and decipher, we use decipher and emulate sign */
607 	if (usage & USAGE_ANY_DECIPHER) {
608 		if (keylen <= 1024)
609 			*algop = CARDOS_ALGO_RSA_PURE;
610 		else
611 			*algop = CARDOS_ALGO_EXT_RSA_PURE;
612 		return 0;
613 	}
614 	if (usage & USAGE_ANY_SIGN) {
615 		if (keylen <= 1024)
616 			*algop = CARDOS_ALGO_RSA_PURE_SIG;
617 		else
618 			*algop = CARDOS_ALGO_EXT_RSA_SIG_PURE;
619 		return 0;
620 	}
621 	return -1;
622 }
623 
624 /*
625  * Create a private key object
626  */
627 #define CARDOS_KEY_OPTIONS	0x02
628 #define CARDOS_KEY_FLAGS	0x00
629 static int
cardos_store_key_component(sc_card_t * card,int algorithm,unsigned int key_id,unsigned int pin_id,unsigned int num,const u8 * data,size_t len,int last,int use_prefix)630 cardos_store_key_component(sc_card_t *card,
631 		int algorithm,
632 		unsigned int key_id, unsigned int pin_id,
633 		unsigned int num,
634 		const u8 *data, size_t len,
635 		int last, int use_prefix)
636 {
637 	struct sc_cardctl_cardos_obj_info args;
638 	struct tlv	tlv;
639 	unsigned char	buffer[256];
640 #ifdef SET_SM_BYTES
641 	unsigned int	n;
642 #endif
643 	int		r;
644 
645 	/* Initialize the TLV encoder */
646 	tlv_init(&tlv, buffer, sizeof(buffer));
647 
648 	/* Object address */
649 	tlv_next(&tlv, 0x83);
650 	tlv_add(&tlv, 0x20|num);	/* PSO, n-th component */
651 	tlv_add(&tlv, key_id);
652 
653 	/* Object parameters */
654 	tlv_next(&tlv, 0x85);
655 	tlv_add(&tlv, CARDOS_KEY_OPTIONS|(last? 0x00 : 0x20));
656 	tlv_add(&tlv, CARDOS_KEY_FLAGS);
657 	tlv_add(&tlv, algorithm);
658 	tlv_add(&tlv, 0x00);
659 	tlv_add(&tlv, 0xFF);	/* use count */
660 	tlv_add(&tlv, 0xFF);	/* DEK (whatever this is) */
661 	tlv_add(&tlv, 0x00);
662 	tlv_add(&tlv, 0x00);
663 
664 	/* AC bytes */
665 	tlv_next(&tlv, 0x86);
666 	tlv_add(&tlv, pin_id);	/* AC USE */
667 	tlv_add(&tlv, pin_id);	/* AC CHANGE */
668 	tlv_add(&tlv, pin_id);	/* UNKNOWN */
669 	tlv_add(&tlv, 0);	/* rfu */
670 	tlv_add(&tlv, 0);	/* rfu */
671 	tlv_add(&tlv, 0);	/* rfu */
672 	tlv_add(&tlv, 0);
673 
674 #ifdef SET_SM_BYTES
675 	/* it shouldn't be necessary to set the default value */
676 	/* SM bytes */
677 	tlv_next(&tlv, 0x8B);
678 	for (n = 0; n < 16; n++)
679 		tlv_add(&tlv, 0xFF);
680 #endif
681 
682 	/* key component */
683 	tlv_next(&tlv, 0x8f);
684 	if (use_prefix != 0) {
685 		tlv_add(&tlv, len+1);
686 		tlv_add(&tlv, 0);
687 	}
688 	while (len--)
689 		tlv_add(&tlv, *data++);
690 
691 	args.data = buffer;
692 	args.len = tlv_len(&tlv);
693 
694 	/* ensure we are in the correct lifecycle */
695 	r = sc_pkcs15init_set_lifecycle(card, SC_CARDCTRL_LIFECYCLE_ADMIN);
696 	if (r < 0 && r != SC_ERROR_NOT_SUPPORTED)
697 		return r;
698 
699 	return sc_card_ctl(card, SC_CARDCTL_CARDOS_PUT_DATA_OCI, &args);
700 }
701 
702 
703 static int
cardos_put_key(sc_profile_t * profile,struct sc_pkcs15_card * p15card,int algorithm,sc_pkcs15_prkey_info_t * key_info,struct sc_pkcs15_prkey_rsa * key)704 cardos_put_key(sc_profile_t *profile, struct sc_pkcs15_card *p15card,
705 	int algorithm, sc_pkcs15_prkey_info_t *key_info,
706 	struct sc_pkcs15_prkey_rsa *key)
707 {
708 	struct sc_card *card = p15card->card;
709 	int	r, key_id, pin_id;
710 
711 	pin_id = sc_pkcs15init_get_pin_reference(p15card, profile, SC_AC_SYMBOLIC,
712 			SC_PKCS15INIT_USER_PIN);
713 	if (pin_id < 0)
714 		pin_id = 0;
715 
716 	key_id = key_info->key_reference;
717 	if (key_info->modulus_length > 1024 && (card->type == SC_CARD_TYPE_CARDOS_M4_2 ||
718 	    card->type == SC_CARD_TYPE_CARDOS_M4_3 ||card->type == SC_CARD_TYPE_CARDOS_M4_2B ||
719 	    card->type == SC_CARD_TYPE_CARDOS_M4_2C ||card->type == SC_CARD_TYPE_CARDOS_M4_4)) {
720 		r = cardos_store_key_component(card, algorithm, key_id, pin_id, 0,
721 			key->p.data, key->p.len, 0, 0);
722 		if (r != SC_SUCCESS)
723 			return r;
724 		r = cardos_store_key_component(card, algorithm, key_id, pin_id, 1,
725 			key->q.data, key->q.len, 0, 0);
726 		if (r != SC_SUCCESS)
727 			return r;
728 		r = cardos_store_key_component(card, algorithm, key_id, pin_id, 2,
729 			key->dmp1.data, key->dmp1.len, 0, 0);
730 		if (r != SC_SUCCESS)
731 			return r;
732 		r = cardos_store_key_component(card, algorithm, key_id, pin_id, 3,
733 			key->dmq1.data, key->dmq1.len, 0, 0);
734 		if (r != SC_SUCCESS)
735 			return r;
736 		r = cardos_store_key_component(card, algorithm, key_id, pin_id, 4,
737 			key->iqmp.data, key->iqmp.len, 1, 0);
738 	} else {
739 		r = cardos_store_key_component(card, algorithm, key_id, pin_id, 0,
740 			key->modulus.data, key->modulus.len, 0, 1);
741 		if (r != SC_SUCCESS)
742 			return r;
743 		r = cardos_store_key_component(card, algorithm, key_id, pin_id, 1,
744 			key->d.data, key->d.len, 1, 1);
745 	}
746 
747 	return r;
748 }
749 
750 /*
751  * Extract a key component from the public key file populated by
752  * GENERATE KEY PAIR
753  */
parse_ext_pubkey_file(sc_card_t * card,const u8 * data,size_t len,sc_pkcs15_pubkey_t * pubkey)754 static int parse_ext_pubkey_file(sc_card_t *card, const u8 *data, size_t len,
755 	sc_pkcs15_pubkey_t *pubkey)
756 {
757 	const u8     *p;
758 	size_t       ilen = 0, tlen = 0;
759 
760 	if (data == NULL || len < 32)
761 		return SC_ERROR_INVALID_ARGUMENTS;
762 	data = sc_asn1_find_tag(card->ctx, data, len, 0x7f49, &ilen);
763 	if (data == NULL) {
764 		sc_log(card->ctx,  "invalid public key data: missing tag");
765 		return SC_ERROR_INTERNAL;
766 	}
767 
768 	p = sc_asn1_find_tag(card->ctx, data, ilen, 0x81, &tlen);
769 	if (p == NULL) {
770 		sc_log(card->ctx,  "invalid public key data: missing modulus");
771 		return SC_ERROR_INTERNAL;
772 	}
773 	pubkey->u.rsa.modulus.len  = tlen;
774 	pubkey->u.rsa.modulus.data = malloc(tlen);
775 	if (pubkey->u.rsa.modulus.data == NULL)
776 		return SC_ERROR_OUT_OF_MEMORY;
777 	memcpy(pubkey->u.rsa.modulus.data, p, tlen);
778 
779 	p = sc_asn1_find_tag(card->ctx, data, ilen, 0x82, &tlen);
780 	if (p == NULL) {
781 		sc_log(card->ctx,  "invalid public key data: missing exponent");
782 		return SC_ERROR_INTERNAL;
783 	}
784 	pubkey->u.rsa.exponent.len  = tlen;
785 	pubkey->u.rsa.exponent.data = malloc(tlen);
786 	if (pubkey->u.rsa.exponent.data == NULL)
787 		return SC_ERROR_OUT_OF_MEMORY;
788 	memcpy(pubkey->u.rsa.exponent.data, p, tlen);
789 
790 	return SC_SUCCESS;
791 }
792 
793 static int
do_cardos_extract_pubkey(sc_card_t * card,int nr,u8 tag,sc_pkcs15_bignum_t * bn)794 do_cardos_extract_pubkey(sc_card_t *card, int nr, u8 tag,
795 			sc_pkcs15_bignum_t *bn)
796 {
797 	u8	buf[256];
798 	int	r, count;
799 
800 	r = sc_read_record(card, nr, buf, sizeof(buf), SC_RECORD_BY_REC_NR);
801 	if (r < 0)
802 		return r;
803 	count = r - 4;
804 	if (count <= 0 || buf[0] != tag || buf[1] != count + 2
805 	    || buf[2] != count + 1 || buf[3] != 0)
806 		return SC_ERROR_INTERNAL;
807 	bn->len = count;
808 	bn->data = malloc(count);
809 	if (bn->data == NULL)
810 		return SC_ERROR_OUT_OF_MEMORY;
811 	memcpy(bn->data, buf + 4, count);
812 	return SC_SUCCESS;
813 }
814 
cardos_extract_pubkey(sc_card_t * card,sc_pkcs15_pubkey_t * pubkey,sc_file_t * tfile,int use_ext_rsa)815 static int cardos_extract_pubkey(sc_card_t *card, sc_pkcs15_pubkey_t *pubkey,
816 	sc_file_t *tfile, int use_ext_rsa)
817 {
818 	int r;
819 
820 	memset(pubkey, 0, sizeof(*pubkey));
821 
822 	r = sc_select_file(card, &tfile->path, NULL);
823 	if (r != SC_SUCCESS)
824 		return r;
825 
826 	if (use_ext_rsa == 0) {
827 		r = do_cardos_extract_pubkey(card, 1, 0x10, &pubkey->u.rsa.modulus);
828 		if (r != SC_SUCCESS)
829 			return r;
830 		r = do_cardos_extract_pubkey(card, 2, 0x11, &pubkey->u.rsa.exponent);
831 	} else {
832 		u8 *buf;
833 
834 		buf = malloc(tfile->size);
835 		if (buf == NULL)
836 			return SC_ERROR_OUT_OF_MEMORY;
837 		r = sc_read_binary(card, 0, buf, tfile->size, 0);
838 		if (r > 0)
839 			r = parse_ext_pubkey_file(card, buf, (size_t)r, pubkey);
840 		free(buf);
841 	}
842 
843 	pubkey->algorithm = SC_ALGORITHM_RSA;
844 
845 	return r;
846 }
847 
cardos_have_verifyrc_package(sc_card_t * card)848 static int cardos_have_verifyrc_package(sc_card_t *card)
849 {
850 	sc_apdu_t apdu;
851         u8        rbuf[SC_MAX_APDU_BUFFER_SIZE];
852         int       r;
853 	const u8  *p = rbuf, *q;
854 	size_t    len, tlen = 0, ilen = 0;
855 
856 	sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, 0x88);
857 	apdu.resp    = rbuf;
858 	apdu.resplen = sizeof(rbuf);
859 	apdu.lc = 0;
860 	apdu.le = 256;
861 	r = sc_transmit_apdu(card, &apdu);
862 	LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
863 
864 	if ((len = apdu.resplen) == 0)
865 		/* looks like no package has been installed  */
866 		return 0;
867 
868 	while (len != 0) {
869 		p = sc_asn1_find_tag(card->ctx, p, len, 0xe1, &tlen);
870 		if (p == NULL)
871 			return 0;
872 		if (card->type == SC_CARD_TYPE_CARDOS_M4_3)	{
873 			/* the verifyRC package on CardOS 4.3B use Manufacturer ID 0x01	*/
874 			/* and Package Number 0x07					*/
875 			q = sc_asn1_find_tag(card->ctx, p, tlen, 0x01, &ilen);
876 			if (q == NULL || ilen != 4)
877 				return 0;
878 			if (q[0] == 0x07)
879 				return 1;
880 		} else if (card->type == SC_CARD_TYPE_CARDOS_M4_4)	{
881 			/* the verifyRC package on CardOS 4.4 use Manufacturer ID 0x03	*/
882 			/* and Package Number 0x02					*/
883 			q = sc_asn1_find_tag(card->ctx, p, tlen, 0x03, &ilen);
884 			if (q == NULL || ilen != 4)
885 				return 0;
886 			if (q[0] == 0x02)
887 				return 1;
888 		} else	{
889 			return 0;
890 		}
891 		p   += tlen;
892 		len -= tlen + 2;
893 	}
894 
895 	return 0;
896 }
897 
898 static struct sc_pkcs15init_operations sc_pkcs15init_cardos_operations = {
899 	cardos_erase,
900 	NULL,				/* init_card */
901 	cardos_create_dir,
902 	NULL,				/* create_domain */
903 	cardos_select_pin_reference,
904 	cardos_create_pin,
905 	cardos_select_key_reference,
906 	cardos_create_key,
907 	cardos_store_key,
908 	cardos_generate_key,
909 	NULL, NULL, 			/* encode private/public key */
910 	NULL,				/* finalize_card */
911 	cardos_delete_object,
912 	NULL, NULL, NULL, NULL, NULL, 	/* pkcs15init emulation */
913 	NULL				/* sanity_check */
914 };
915 
916 struct sc_pkcs15init_operations *
sc_pkcs15init_get_cardos_ops(void)917 sc_pkcs15init_get_cardos_ops(void)
918 {
919 	return &sc_pkcs15init_cardos_operations;
920 }
921