1 /*
2  * card.c: General smart card functions
3  *
4  * Copyright (C) 2001, 2002  Juha Yrjölä <juha.yrjola@iki.fi>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20 
21 #if HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24 
25 #include <assert.h>
26 #include <stdlib.h>
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30 #include <string.h>
31 #include <limits.h>
32 
33 #include "reader-tr03119.h"
34 #include "internal.h"
35 #include "asn1.h"
36 #include "common/compat_strlcpy.h"
37 
38 #ifdef ENABLE_SM
39 static int sc_card_sm_load(sc_card_t *card, const char *path, const char *module);
40 static int sc_card_sm_unload(sc_card_t *card);
41 static int sc_card_sm_check(sc_card_t *card);
42 #endif
43 
sc_check_sw(sc_card_t * card,unsigned int sw1,unsigned int sw2)44 int sc_check_sw(sc_card_t *card, unsigned int sw1, unsigned int sw2)
45 {
46 	if (card == NULL)
47 		return SC_ERROR_INVALID_ARGUMENTS;
48 	if (card->ops->check_sw == NULL)
49 		return SC_ERROR_NOT_SUPPORTED;
50 	return card->ops->check_sw(card, sw1, sw2);
51 }
52 
sc_format_apdu(sc_card_t * card,sc_apdu_t * apdu,int cse,int ins,int p1,int p2)53 void sc_format_apdu(sc_card_t *card, sc_apdu_t *apdu,
54 		    int cse, int ins, int p1, int p2)
55 {
56 	if (card == NULL || apdu == NULL) {
57 		return;
58 	}
59 	memset(apdu, 0, sizeof(*apdu));
60 	apdu->cla = (u8) card->cla;
61 	apdu->cse = cse;
62 	apdu->ins = (u8) ins;
63 	apdu->p1 = (u8) p1;
64 	apdu->p2 = (u8) p2;
65 }
66 
sc_format_apdu_cse_lc_le(struct sc_apdu * apdu)67 void sc_format_apdu_cse_lc_le(struct sc_apdu *apdu)
68 {
69 	/* TODO calculating the APDU case, Lc and Le should actually only be
70 	 * done in sc_apdu2bytes, but to gradually change OpenSC we start here. */
71 	/* Let sc_detect_apdu_cse set short or extended  and test for chaining */
72 
73 	if (!apdu)
74 		return;
75 	if (apdu->datalen > SC_MAX_APDU_DATA_SIZE
76 			|| apdu->resplen > SC_MAX_APDU_RESP_SIZE) {
77 		/* extended length  or data chaining and/or get response */
78 		if (apdu->datalen <= SC_MAX_EXT_APDU_DATA_SIZE)
79 			apdu->lc = apdu->datalen;
80 		if (apdu->resplen <= SC_MAX_EXT_APDU_RESP_SIZE)
81 			apdu->le = apdu->resplen;
82 		if (apdu->resplen && !apdu->datalen)
83 			apdu->cse = SC_APDU_CASE_2;
84 		if (!apdu->resplen && apdu->datalen)
85 			apdu->cse = SC_APDU_CASE_3;
86 		if (apdu->resplen && apdu->datalen)
87 			apdu->cse = SC_APDU_CASE_4;
88 	} else {
89 		/* short length */
90 		if (apdu->datalen <= SC_MAX_APDU_DATA_SIZE)
91 			apdu->lc = apdu->datalen;
92 		if (apdu->resplen <= SC_MAX_APDU_RESP_SIZE)
93 			apdu->le = apdu->resplen;
94 		if (!apdu->resplen && !apdu->datalen)
95 			apdu->cse = SC_APDU_CASE_1;
96 		if (apdu->resplen && !apdu->datalen)
97 			apdu->cse = SC_APDU_CASE_2_SHORT;
98 		if (!apdu->resplen && apdu->datalen)
99 			apdu->cse = SC_APDU_CASE_3_SHORT;
100 		if (apdu->resplen && apdu->datalen)
101 			apdu->cse = SC_APDU_CASE_4_SHORT;
102 	}
103 }
104 
sc_format_apdu_ex(struct sc_apdu * apdu,u8 cla,u8 ins,u8 p1,u8 p2,const u8 * data,size_t datalen,u8 * resp,size_t resplen)105 void sc_format_apdu_ex(struct sc_apdu *apdu,
106 		u8 cla, u8 ins, u8 p1, u8 p2,
107 		const u8 *data, size_t datalen,
108 		u8 *resp, size_t resplen)
109 {
110 	if (!apdu) {
111 		return;
112 	}
113 
114 	memset(apdu, 0, sizeof(*apdu));
115 	apdu->cla = cla;
116 	apdu->ins = ins;
117 	apdu->p1 = p1;
118 	apdu->p2 = p2;
119 	apdu->resp = resp;
120 	apdu->resplen = resplen;
121 	apdu->data = data;
122 	apdu->datalen = datalen;
123 	sc_format_apdu_cse_lc_le(apdu);
124 }
125 
sc_card_new(sc_context_t * ctx)126 static sc_card_t * sc_card_new(sc_context_t *ctx)
127 {
128 	sc_card_t *card;
129 
130 	if (ctx == NULL)
131 		return NULL;
132 
133 	card = calloc(1, sizeof(struct sc_card));
134 	if (card == NULL)
135 		return NULL;
136 	card->ops = malloc(sizeof(struct sc_card_operations));
137 	if (card->ops == NULL) {
138 		free(card);
139 		return NULL;
140 	}
141 
142 	card->ctx = ctx;
143 	if (sc_mutex_create(ctx, &card->mutex) != SC_SUCCESS) {
144 		free(card->ops);
145 		free(card);
146 		return NULL;
147 	}
148 
149 	card->type = -1;
150 	card->app_count = -1;
151 
152 	return card;
153 }
154 
sc_card_free(sc_card_t * card)155 static void sc_card_free(sc_card_t *card)
156 {
157 	sc_free_apps(card);
158 	sc_free_ef_atr(card);
159 
160 	free(card->ops);
161 
162 	if (card->algorithms != NULL)   {
163 		int i;
164 		for (i=0; i<card->algorithm_count; i++)   {
165 			struct sc_algorithm_info *info = (card->algorithms + i);
166 			if (info->algorithm == SC_ALGORITHM_EC) {
167 				struct sc_ec_parameters ep = info->u._ec.params;
168 
169 				free(ep.named_curve);
170 				free(ep.der.value);
171 			}
172 		}
173 		free(card->algorithms);
174 
175 		card->algorithms = NULL;
176 		card->algorithm_count = 0;
177 	}
178 
179 	sc_file_free(card->cache.current_ef);
180 	sc_file_free(card->cache.current_df);
181 
182 	if (card->mutex != NULL) {
183 		int r = sc_mutex_destroy(card->ctx, card->mutex);
184 		if (r != SC_SUCCESS)
185 			sc_log(card->ctx, "unable to destroy mutex");
186 	}
187 	sc_mem_clear(card, sizeof(*card));
188 	free(card);
189 }
190 
sc_get_max_recv_size(const sc_card_t * card)191 size_t sc_get_max_recv_size(const sc_card_t *card)
192 {
193 	size_t max_recv_size;
194 	if (card == NULL || card->reader == NULL) {
195 		return 0;
196 	}
197 	max_recv_size = card->max_recv_size;
198 
199 	/* initialize max_recv_size to a meaningful value */
200 	if (card->caps & SC_CARD_CAP_APDU_EXT) {
201 		if (!max_recv_size)
202 			max_recv_size = 65536;
203 	} else {
204 		if (!max_recv_size)
205 			max_recv_size = 256;
206 	}
207 
208 	/*  Override card limitations with reader limitations. */
209 	if (card->reader->max_recv_size != 0
210 			&& (card->reader->max_recv_size < card->max_recv_size))
211 		max_recv_size = card->reader->max_recv_size;
212 
213 	return max_recv_size;
214 }
215 
sc_get_max_send_size(const sc_card_t * card)216 size_t sc_get_max_send_size(const sc_card_t *card)
217 {
218 	size_t max_send_size;
219 
220 	if (card == NULL || card->reader == NULL) {
221 		return 0;
222 	}
223 
224 	max_send_size = card->max_send_size;
225 
226 	/* initialize max_send_size to a meaningful value */
227 	if (card->caps & SC_CARD_CAP_APDU_EXT
228 			&& card->reader->active_protocol != SC_PROTO_T0) {
229 		if (!max_send_size)
230 			max_send_size = 65535;
231 	} else {
232 		if (!max_send_size)
233 			max_send_size = 255;
234 	}
235 
236 	/*  Override card limitations with reader limitations. */
237 	if (card->reader->max_send_size != 0
238 			&& (card->reader->max_send_size < card->max_send_size))
239 		max_send_size = card->reader->max_send_size;
240 
241 	return max_send_size;
242 }
243 
sc_connect_card(sc_reader_t * reader,sc_card_t ** card_out)244 int sc_connect_card(sc_reader_t *reader, sc_card_t **card_out)
245 {
246 	sc_card_t *card;
247 	sc_context_t *ctx;
248 	struct sc_card_driver *driver;
249 	int i, r = 0, idx, connected = 0;
250 
251 	if (card_out == NULL || reader == NULL)
252 		return SC_ERROR_INVALID_ARGUMENTS;
253 	ctx = reader->ctx;
254 	SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE);
255 	if (reader->ops->connect == NULL)
256 		LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
257 
258 	card = sc_card_new(ctx);
259 	if (card == NULL)
260 		LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
261 	r = reader->ops->connect(reader);
262 	if (r)
263 		goto err;
264 
265 	connected = 1;
266 	card->reader = reader;
267 	card->ctx = ctx;
268 
269 	if (reader->flags & SC_READER_ENABLE_ESCAPE)
270 		sc_detect_escape_cmds(reader);
271 
272 	memcpy(&card->atr, &reader->atr, sizeof(card->atr));
273 	memcpy(&card->uid, &reader->uid, sizeof(card->uid));
274 
275 	_sc_parse_atr(reader);
276 
277 	/* See if the ATR matches any ATR specified in the config file */
278 	if ((driver = ctx->forced_driver) == NULL) {
279 		sc_log(ctx, "matching configured ATRs");
280 		for (i = 0; ctx->card_drivers[i] != NULL; i++) {
281 			driver = ctx->card_drivers[i];
282 
283 			if (driver->atr_map == NULL ||
284 			    !strcmp(driver->short_name, "default")) {
285 				driver = NULL;
286 				continue;
287 			}
288 			sc_log(ctx, "trying driver '%s'", driver->short_name);
289 			idx = _sc_match_atr(card, driver->atr_map, NULL);
290 			if (idx >= 0) {
291 				struct sc_atr_table *src = &driver->atr_map[idx];
292 
293 				sc_log(ctx, "matched driver '%s'", driver->name);
294 				/* It's up to card driver to notice these correctly */
295 				card->name = src->name;
296 				card->type = src->type;
297 				card->flags = src->flags;
298 				break;
299 			}
300 			driver = NULL;
301 		}
302 	}
303 
304 	if (driver != NULL) {
305 		/* Forced driver, or matched via ATR mapping from config file */
306 		card->driver = driver;
307 
308 		memcpy(card->ops, card->driver->ops, sizeof(struct sc_card_operations));
309 		if (card->ops->match_card != NULL)
310 			if (card->ops->match_card(card) != 1)
311 				sc_log(ctx, "driver '%s' match_card() failed: %s (will continue anyway)", card->driver->name, sc_strerror(r));
312 
313 		if (card->ops->init != NULL) {
314 			r = card->ops->init(card);
315 			if (r) {
316 				sc_log(ctx, "driver '%s' init() failed: %s", card->driver->name, sc_strerror(r));
317 				goto err;
318 			}
319 		}
320 	}
321 	else {
322 		sc_card_t uninitialized = *card;
323 		sc_log(ctx, "matching built-in ATRs");
324 		for (i = 0; ctx->card_drivers[i] != NULL; i++) {
325 			/* FIXME If we had a clean API description, we'd probably get a
326 			 * cleaner implementation of the driver's match_card and init,
327 			 * which should normally *not* modify the card object if
328 			 * unsuccessful. However, after years of relentless hacking, reality
329 			 * is different: The card object is changed in virtually every card
330 			 * driver so in order to prevent unwanted interaction, we reset the
331 			 * card object here and hope that the card driver at least doesn't
332 			 * allocate any internal resources that need to be freed. If we
333 			 * had more time, we should refactor the existing code to not
334 			 * modify sc_card_t until complete success (possibly by combining
335 			 * `match_card()` and `init()`) */
336 			*card = uninitialized;
337 
338 			struct sc_card_driver *drv = ctx->card_drivers[i];
339 			const struct sc_card_operations *ops = drv->ops;
340 
341 			sc_log(ctx, "trying driver '%s'", drv->short_name);
342 			if (ops == NULL || ops->match_card == NULL)   {
343 				continue;
344 			}
345 			else if (!(ctx->flags & SC_CTX_FLAG_ENABLE_DEFAULT_DRIVER)
346 				   	&& !strcmp("default", drv->short_name))   {
347 				sc_log(ctx , "ignore 'default' card driver");
348 				continue;
349 			}
350 
351 			/* Needed if match_card() needs to talk with the card (e.g. card-muscle) */
352 			*card->ops = *ops;
353 			if (ops->match_card(card) != 1)
354 				continue;
355 			sc_log(ctx, "matched: %s", drv->name);
356 			memcpy(card->ops, ops, sizeof(struct sc_card_operations));
357 			card->driver = drv;
358 			r = ops->init(card);
359 			if (r) {
360 				sc_log(ctx, "driver '%s' init() failed: %s", drv->name, sc_strerror(r));
361 				if (r == SC_ERROR_INVALID_CARD) {
362 					card->driver = NULL;
363 					continue;
364 				}
365 				goto err;
366 			}
367 			break;
368 		}
369 	}
370 	if (card->driver == NULL) {
371 		sc_log(ctx, "unable to find driver for inserted card");
372 		r = SC_ERROR_INVALID_CARD;
373 		goto err;
374 	}
375 	if (card->name == NULL)
376 		card->name = card->driver->name;
377 
378 	/* initialize max_send_size/max_recv_size to a meaningful value */
379 	card->max_recv_size = sc_get_max_recv_size(card);
380 	card->max_send_size = sc_get_max_send_size(card);
381 
382 	sc_log(ctx,
383 	       "card info name:'%s', type:%i, flags:0x%lX, max_send/recv_size:%"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u",
384 	       card->name, card->type, card->flags, card->max_send_size,
385 	       card->max_recv_size);
386 
387 #ifdef ENABLE_SM
388         /* Check, if secure messaging module present. */
389 	r = sc_card_sm_check(card);
390 	if (r)   {
391 		sc_log(ctx, "cannot load secure messaging module");
392 		goto err;
393 	}
394 #endif
395 	*card_out = card;
396 
397 	LOG_FUNC_RETURN(ctx, SC_SUCCESS);
398 err:
399 	if (connected)
400 		reader->ops->disconnect(reader);
401 	if (card != NULL)
402 		sc_card_free(card);
403 	LOG_FUNC_RETURN(ctx, r);
404 }
405 
sc_disconnect_card(sc_card_t * card)406 int sc_disconnect_card(sc_card_t *card)
407 {
408 	sc_context_t *ctx;
409 
410 	if (!card)
411 		return SC_ERROR_INVALID_ARGUMENTS;
412 
413 	ctx = card->ctx;
414 	LOG_FUNC_CALLED(ctx);
415 
416 	if (card->lock_count != 0)
417 		return SC_ERROR_NOT_ALLOWED;
418 	if (card->ops->finish) {
419 		int r = card->ops->finish(card);
420 		if (r)
421 			sc_log(ctx, "card driver finish() failed: %s", sc_strerror(r));
422 	}
423 
424 	if (card->reader->ops->disconnect) {
425 		int r = card->reader->ops->disconnect(card->reader);
426 		if (r)
427 			sc_log(ctx, "disconnect() failed: %s", sc_strerror(r));
428 	}
429 
430 #ifdef ENABLE_SM
431 	/* release SM related resources */
432 	sc_card_sm_unload(card);
433 #endif
434 
435 	sc_card_free(card);
436 	LOG_FUNC_RETURN(ctx, SC_SUCCESS);
437 }
438 
sc_reset(sc_card_t * card,int do_cold_reset)439 int sc_reset(sc_card_t *card, int do_cold_reset)
440 {
441 	int r, r2;
442 
443 	if (card == NULL)
444 		return SC_ERROR_INVALID_ARGUMENTS;
445 	if (card->reader->ops->reset == NULL)
446 		return SC_ERROR_NOT_SUPPORTED;
447 
448 	r = sc_mutex_lock(card->ctx, card->mutex);
449 	if (r != SC_SUCCESS)
450 		return r;
451 
452 	r = card->reader->ops->reset(card->reader, do_cold_reset);
453 	sc_invalidate_cache(card);
454 
455 	r2 = sc_mutex_unlock(card->ctx, card->mutex);
456 	if (r2 != SC_SUCCESS) {
457 		sc_log(card->ctx, "unable to release lock");
458 		r = r != SC_SUCCESS ? r : r2;
459 	}
460 
461 	return r;
462 }
463 
sc_lock(sc_card_t * card)464 int sc_lock(sc_card_t *card)
465 {
466 	int r = 0, r2 = 0;
467 	int was_reset = 0;
468 	int reader_lock_obtained  = 0;
469 
470 	if (card == NULL)
471 		return SC_ERROR_INVALID_ARGUMENTS;
472 
473 	LOG_FUNC_CALLED(card->ctx);
474 
475 	r = sc_mutex_lock(card->ctx, card->mutex);
476 	if (r != SC_SUCCESS)
477 		return r;
478 	if (card->lock_count == 0) {
479 		if (card->reader->ops->lock != NULL) {
480 			r = card->reader->ops->lock(card->reader);
481 			while (r == SC_ERROR_CARD_RESET || r == SC_ERROR_READER_REATTACHED) {
482 				sc_invalidate_cache(card);
483 				if (was_reset++ > 4) /* TODO retry a few times */
484 					break;
485 				r = card->reader->ops->lock(card->reader);
486 			}
487 			if (r == 0)
488 				reader_lock_obtained = 1;
489 		}
490 		if (r == 0)
491 			card->cache.valid = 1;
492 	}
493 	if (r == 0)
494 		card->lock_count++;
495 
496 	if (r == 0 && was_reset > 0) {
497 #ifdef ENABLE_SM
498 		if (card->sm_ctx.ops.open)
499 			card->sm_ctx.ops.open(card);
500 #endif
501 	}
502 
503 	r2 = sc_mutex_unlock(card->ctx, card->mutex);
504 	if (r2 != SC_SUCCESS) {
505 		sc_log(card->ctx, "unable to release card->mutex lock");
506 		r = r != SC_SUCCESS ? r : r2;
507 	}
508 
509 	/* give card driver a chance to do something when reader lock first obtained */
510 	if (r == 0 && reader_lock_obtained == 1  && card->ops->card_reader_lock_obtained)
511 		r = card->ops->card_reader_lock_obtained(card, was_reset);
512 
513 	LOG_FUNC_RETURN(card->ctx, r);
514 }
515 
sc_unlock(sc_card_t * card)516 int sc_unlock(sc_card_t *card)
517 {
518 	int r, r2;
519 
520 	if (!card)
521 		return SC_ERROR_INVALID_ARGUMENTS;
522 
523 	LOG_FUNC_CALLED(card->ctx);
524 
525 	r = sc_mutex_lock(card->ctx, card->mutex);
526 	if (r != SC_SUCCESS)
527 		return r;
528 
529 	if (card->lock_count < 1) {
530 		return SC_ERROR_INVALID_ARGUMENTS;
531 	}
532 	if (--card->lock_count == 0) {
533 		if (card->flags & SC_CARD_FLAG_KEEP_ALIVE) {
534 			/* Multiple processes accessing the card will most likely render
535 			 * the card cache useless. To not have a bad cache, we explicitly
536 			 * invalidate it. */
537 			sc_invalidate_cache(card);
538 		}
539 		/* release reader lock */
540 		if (card->reader->ops->unlock != NULL)
541 			r = card->reader->ops->unlock(card->reader);
542 	}
543 	r2 = sc_mutex_unlock(card->ctx, card->mutex);
544 	if (r2 != SC_SUCCESS) {
545 		sc_log(card->ctx, "unable to release lock");
546 		r = (r == SC_SUCCESS) ? r2 : r;
547 	}
548 
549 	return r;
550 }
551 
sc_list_files(sc_card_t * card,u8 * buf,size_t buflen)552 int sc_list_files(sc_card_t *card, u8 *buf, size_t buflen)
553 {
554 	int r;
555 
556 	if (card == NULL) {
557 		return SC_ERROR_INVALID_ARGUMENTS;
558 	}
559 	LOG_FUNC_CALLED(card->ctx);
560 
561 	if (card->ops->list_files == NULL)
562 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
563 	r = card->ops->list_files(card, buf, buflen);
564 
565 	LOG_FUNC_RETURN(card->ctx, r);
566 }
567 
sc_create_file(sc_card_t * card,sc_file_t * file)568 int sc_create_file(sc_card_t *card, sc_file_t *file)
569 {
570 	int r;
571 	char pbuf[SC_MAX_PATH_STRING_SIZE];
572 	const sc_path_t *in_path;
573 
574 	if (card == NULL || file == NULL) {
575 		return SC_ERROR_INVALID_ARGUMENTS;
576 	}
577 
578 	in_path = &file->path;
579 	r = sc_path_print(pbuf, sizeof(pbuf), in_path);
580 	if (r != SC_SUCCESS)
581 		pbuf[0] = '\0';
582 
583 	sc_log(card->ctx,
584 	       "called; type=%d, path=%s, id=%04i, size=%"SC_FORMAT_LEN_SIZE_T"u",
585 	       in_path->type, pbuf, file->id, file->size);
586 	/* ISO 7816-4: "Number of data bytes in the file, including structural information if any"
587 	 * can not be bigger than two bytes */
588 	if (file->size > 0xFFFF)
589 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
590 
591 	if (card->ops->create_file == NULL)
592 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
593 
594 	r = card->ops->create_file(card, file);
595 	LOG_FUNC_RETURN(card->ctx, r);
596 }
597 
sc_delete_file(sc_card_t * card,const sc_path_t * path)598 int sc_delete_file(sc_card_t *card, const sc_path_t *path)
599 {
600 	int r;
601 	char pbuf[SC_MAX_PATH_STRING_SIZE];
602 
603 	if (card == NULL) {
604 		return SC_ERROR_INVALID_ARGUMENTS;
605 	}
606 
607 	r = sc_path_print(pbuf, sizeof(pbuf), path);
608 	if (r != SC_SUCCESS)
609 		pbuf[0] = '\0';
610 
611 	sc_log(card->ctx, "called; type=%d, path=%s", path->type, pbuf);
612 	if (card->ops->delete_file == NULL)
613 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
614 	r = card->ops->delete_file(card, path);
615 
616 	LOG_FUNC_RETURN(card->ctx, r);
617 }
618 
sc_read_binary(sc_card_t * card,unsigned int idx,unsigned char * buf,size_t count,unsigned long flags)619 int sc_read_binary(sc_card_t *card, unsigned int idx,
620 		   unsigned char *buf, size_t count, unsigned long flags)
621 {
622 	size_t max_le = sc_get_max_recv_size(card);
623 	size_t todo = count;
624 	int r;
625 
626 	if (card == NULL || card->ops == NULL || buf == NULL) {
627 		return SC_ERROR_INVALID_ARGUMENTS;
628 	}
629 	sc_log(card->ctx, "called; %"SC_FORMAT_LEN_SIZE_T"u bytes at index %d",
630 	       count, idx);
631 	if (count == 0)
632 		LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
633 
634 #ifdef ENABLE_SM
635 	if (card->sm_ctx.ops.read_binary)   {
636 		r = card->sm_ctx.ops.read_binary(card, idx, buf, count);
637 		if (r)
638 			LOG_FUNC_RETURN(card->ctx, r);
639 	}
640 #endif
641 
642 	if (card->ops->read_binary == NULL)
643 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
644 
645 	/* lock the card now to avoid deselection of the file */
646 	r = sc_lock(card);
647 	LOG_TEST_RET(card->ctx, r, "sc_lock() failed");
648 
649 	while (todo > 0) {
650 		size_t chunk = todo > max_le ? max_le : todo;
651 
652 		r = card->ops->read_binary(card, idx, buf, chunk, flags);
653 		if (r == 0 || r == SC_ERROR_FILE_END_REACHED)
654 			break;
655 		if ((idx > SIZE_MAX - (size_t) r)
656 				|| (size_t) r > todo) {
657 			/* `idx + r` or `todo - r` would overflow */
658 			r = SC_ERROR_OFFSET_TOO_LARGE;
659 		}
660 		if (r < 0) {
661 			sc_unlock(card);
662 			LOG_FUNC_RETURN(card->ctx, r);
663 		}
664 
665 		todo -= (size_t) r;
666 		buf  += (size_t) r;
667 		idx  += (size_t) r;
668 	}
669 
670 	sc_unlock(card);
671 
672 	LOG_FUNC_RETURN(card->ctx, count - todo);
673 }
674 
sc_write_binary(sc_card_t * card,unsigned int idx,const u8 * buf,size_t count,unsigned long flags)675 int sc_write_binary(sc_card_t *card, unsigned int idx,
676 		    const u8 *buf, size_t count, unsigned long flags)
677 {
678 	size_t max_lc = sc_get_max_send_size(card);
679 	size_t todo = count;
680 	int r;
681 
682 	if (card == NULL || card->ops == NULL || buf == NULL) {
683 		return SC_ERROR_INVALID_ARGUMENTS;
684 	}
685 	sc_log(card->ctx, "called; %"SC_FORMAT_LEN_SIZE_T"u bytes at index %d",
686 	       count, idx);
687 	if (count == 0)
688 		LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
689 
690 	if (card->ops->write_binary == NULL)
691 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
692 
693 	/* lock the card now to avoid deselection of the file */
694 	r = sc_lock(card);
695 	LOG_TEST_RET(card->ctx, r, "sc_lock() failed");
696 
697 	while (todo > 0) {
698 		size_t chunk = todo > max_lc ? max_lc : todo;
699 
700 		r = card->ops->write_binary(card, idx, buf, chunk, flags);
701 		if (r == 0 || r == SC_ERROR_FILE_END_REACHED)
702 			break;
703 		if ((idx > SIZE_MAX - (size_t) r)
704 				|| (size_t) r > todo) {
705 			/* `idx + r` or `todo - r` would overflow */
706 			r = SC_ERROR_OFFSET_TOO_LARGE;
707 		}
708 		if (r < 0) {
709 			sc_unlock(card);
710 			LOG_FUNC_RETURN(card->ctx, r);
711 		}
712 
713 		todo -= (size_t) r;
714 		buf  += (size_t) r;
715 		idx  += (size_t) r;
716 	}
717 
718 	sc_unlock(card);
719 
720 	LOG_FUNC_RETURN(card->ctx, count - todo);
721 }
722 
sc_update_binary(sc_card_t * card,unsigned int idx,const u8 * buf,size_t count,unsigned long flags)723 int sc_update_binary(sc_card_t *card, unsigned int idx,
724 		     const u8 *buf, size_t count, unsigned long flags)
725 {
726 	size_t max_lc = sc_get_max_send_size(card);
727 	size_t todo = count;
728 	int r;
729 
730 	if (card == NULL || card->ops == NULL || buf == NULL) {
731 		return SC_ERROR_INVALID_ARGUMENTS;
732 	}
733 	sc_log(card->ctx, "called; %"SC_FORMAT_LEN_SIZE_T"u bytes at index %d",
734 	       count, idx);
735 	if (count == 0)
736 		LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
737 
738 #ifdef ENABLE_SM
739 	if (card->sm_ctx.ops.update_binary)   {
740 		r = card->sm_ctx.ops.update_binary(card, idx, buf, count);
741 		if (r)
742 			LOG_FUNC_RETURN(card->ctx, r);
743 	}
744 #endif
745 
746 	if (card->ops->update_binary == NULL)
747 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
748 
749 	/* lock the card now to avoid deselection of the file */
750 	r = sc_lock(card);
751 	LOG_TEST_RET(card->ctx, r, "sc_lock() failed");
752 
753 	while (todo > 0) {
754 		size_t chunk = todo > max_lc ? max_lc : todo;
755 
756 		r = card->ops->update_binary(card, idx, buf, chunk, flags);
757 		if (r == 0 || r == SC_ERROR_FILE_END_REACHED)
758 			break;
759 		if ((idx > SIZE_MAX - (size_t) r)
760 				|| (size_t) r > todo) {
761 			/* `idx + r` or `todo - r` would overflow */
762 			r = SC_ERROR_OFFSET_TOO_LARGE;
763 		}
764 		if (r < 0) {
765 			sc_unlock(card);
766 			LOG_FUNC_RETURN(card->ctx, r);
767 		}
768 
769 		todo -= (size_t) r;
770 		buf  += (size_t) r;
771 		idx  += (size_t) r;
772 	}
773 
774 	sc_unlock(card);
775 
776 	LOG_FUNC_RETURN(card->ctx, count - todo);
777 }
778 
779 
sc_erase_binary(struct sc_card * card,unsigned int idx,size_t count,unsigned long flags)780 int sc_erase_binary(struct sc_card *card, unsigned int idx, size_t count,  unsigned long flags)
781 {
782 	int r;
783 	size_t todo = count;
784 
785 	if (card == NULL || card->ops == NULL) {
786 		return SC_ERROR_INVALID_ARGUMENTS;
787 	}
788 	sc_log(card->ctx,
789 	       "called; erase %"SC_FORMAT_LEN_SIZE_T"u bytes from offset %d",
790 	       count, idx);
791 	if (count == 0)
792 		LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
793 
794 	if (card->ops->erase_binary == NULL)
795 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
796 
797 	/* lock the card now to avoid deselection of the file */
798 	r = sc_lock(card);
799 	LOG_TEST_RET(card->ctx, r, "sc_lock() failed");
800 
801 	while (todo > 0) {
802 		r = card->ops->erase_binary(card, idx, todo, flags);
803 		if (r == 0 || r == SC_ERROR_FILE_END_REACHED)
804 			break;
805 		if ((idx > SIZE_MAX - (size_t) r)
806 				|| (size_t) r > todo) {
807 			/* `idx + r` or `todo - r` would overflow */
808 			r = SC_ERROR_OFFSET_TOO_LARGE;
809 		}
810 		if (r < 0) {
811 			sc_unlock(card);
812 			LOG_FUNC_RETURN(card->ctx, r);
813 		}
814 
815 		todo -= (size_t) r;
816 		idx  += (size_t) r;
817 	}
818 
819 	sc_unlock(card);
820 
821 	LOG_FUNC_RETURN(card->ctx, count - todo);
822 }
823 
824 
sc_select_file(sc_card_t * card,const sc_path_t * in_path,sc_file_t ** file)825 int sc_select_file(sc_card_t *card, const sc_path_t *in_path,  sc_file_t **file)
826 {
827 	int r;
828 	char pbuf[SC_MAX_PATH_STRING_SIZE];
829 
830 	if (card == NULL || in_path == NULL) {
831 		return SC_ERROR_INVALID_ARGUMENTS;
832 	}
833 
834 	r = sc_path_print(pbuf, sizeof(pbuf), in_path);
835 	if (r != SC_SUCCESS)
836 		pbuf[0] = '\0';
837 
838 	/* FIXME We should be a bit less strict and let the upper layers do
839 	 * the initialization (including reuse of existing file objects). We
840 	 * implemented this here because we are lazy. */
841 	if (file != NULL)
842 		*file = NULL;
843 
844 	sc_log(card->ctx, "called; type=%d, path=%s", in_path->type, pbuf);
845 	if (in_path->len > SC_MAX_PATH_SIZE)
846 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
847 
848 	if (in_path->type == SC_PATH_TYPE_PATH) {
849 		/* Perform a sanity check */
850 		size_t i;
851 
852 		if ((in_path->len & 1) != 0)
853 			LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
854 
855 		for (i = 0; i < in_path->len/2; i++) {
856 			u8 p1 = in_path->value[2*i],
857 			   p2 = in_path->value[2*i+1];
858 
859 			if ((p1 == 0x3F && p2 == 0x00) && i != 0)
860 				LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
861 		}
862 	}
863 	if (card->ops->select_file == NULL)
864 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
865 	r = card->ops->select_file(card, in_path, file);
866 	LOG_TEST_RET(card->ctx, r, "'SELECT' error");
867 
868 	if (file) {
869 		if (*file)
870 			/* Remember file path */
871 			(*file)->path = *in_path;
872 		else
873 			/* FIXME We should be a bit less strict and let the upper layers do
874 			 * the error checking. We implemented this here because we are
875 			 * lazy.  */
876 			r = SC_ERROR_INVALID_DATA;
877 	}
878 
879 	LOG_FUNC_RETURN(card->ctx, r);
880 }
881 
882 
sc_get_data(sc_card_t * card,unsigned int tag,u8 * buf,size_t len)883 int sc_get_data(sc_card_t *card, unsigned int tag, u8 *buf, size_t len)
884 {
885 	int	r;
886 
887 	sc_log(card->ctx, "called, tag=%04x", tag);
888 	if (card->ops->get_data == NULL)
889 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
890 	r = card->ops->get_data(card, tag, buf, len);
891 
892 	LOG_FUNC_RETURN(card->ctx, r);
893 }
894 
sc_put_data(sc_card_t * card,unsigned int tag,const u8 * buf,size_t len)895 int sc_put_data(sc_card_t *card, unsigned int tag, const u8 *buf, size_t len)
896 {
897 	int	r;
898 
899 	sc_log(card->ctx,"called, tag=%04x", tag);
900 
901 	if (card->ops->put_data == NULL)
902 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
903 	r = card->ops->put_data(card, tag, buf, len);
904 
905 	LOG_FUNC_RETURN(card->ctx, r);
906 }
907 
sc_get_challenge(sc_card_t * card,u8 * rnd,size_t len)908 int sc_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
909 {
910 	int r;
911 
912 	if (len == 0)
913 		return SC_SUCCESS;
914 
915 	if (card == NULL || rnd == NULL) {
916 		return SC_ERROR_INVALID_ARGUMENTS;
917 	}
918 
919 	LOG_FUNC_CALLED(card->ctx);
920 
921 	if (card->ops == NULL || card->ops->get_challenge == NULL)
922 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
923 
924 	r = sc_lock(card);
925 	if (r != SC_SUCCESS)
926 		LOG_FUNC_RETURN(card->ctx, r);
927 
928 	while (len > 0) {
929 		r = card->ops->get_challenge(card, rnd, len);
930 		if (r == 0)
931 			r = SC_ERROR_INVALID_DATA;
932 		if (r < 0) {
933 			sc_unlock(card);
934 			LOG_FUNC_RETURN(card->ctx, r);
935 		}
936 
937 		rnd += (size_t) r;
938 		len -= (size_t) r;
939 	}
940 
941 	sc_unlock(card);
942 
943 	LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
944 }
945 
sc_read_record(sc_card_t * card,unsigned int rec_nr,u8 * buf,size_t count,unsigned long flags)946 int sc_read_record(sc_card_t *card, unsigned int rec_nr, u8 *buf,
947 		   size_t count, unsigned long flags)
948 {
949 	int r;
950 
951 	if (card == NULL) {
952 		return SC_ERROR_INVALID_ARGUMENTS;
953 	}
954 	LOG_FUNC_CALLED(card->ctx);
955 
956 	if (card->ops->read_record == NULL)
957 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
958 
959 	r = card->ops->read_record(card, rec_nr, buf, count, flags);
960 	if (r == SC_SUCCESS) {
961 		r = count;
962 	}
963 
964 	LOG_FUNC_RETURN(card->ctx, r);
965 }
966 
sc_write_record(sc_card_t * card,unsigned int rec_nr,const u8 * buf,size_t count,unsigned long flags)967 int sc_write_record(sc_card_t *card, unsigned int rec_nr, const u8 * buf,
968 		    size_t count, unsigned long flags)
969 {
970 	int r;
971 
972 	if (card == NULL) {
973 		return SC_ERROR_INVALID_ARGUMENTS;
974 	}
975 	LOG_FUNC_CALLED(card->ctx);
976 
977 	if (card->ops->write_record == NULL)
978 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
979 
980 	r = card->ops->write_record(card, rec_nr, buf, count, flags);
981 	if (r == SC_SUCCESS) {
982 		r = count;
983 	}
984 
985 	LOG_FUNC_RETURN(card->ctx, r);
986 }
987 
sc_append_record(sc_card_t * card,const u8 * buf,size_t count,unsigned long flags)988 int sc_append_record(sc_card_t *card, const u8 * buf, size_t count,
989 		     unsigned long flags)
990 {
991 	int r;
992 
993 	if (card == NULL) {
994 		return SC_ERROR_INVALID_ARGUMENTS;
995 	}
996 	LOG_FUNC_CALLED(card->ctx);
997 
998 	if (card->ops->append_record == NULL)
999 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
1000 
1001 	r = card->ops->append_record(card, buf, count, flags);
1002 	if (r == SC_SUCCESS) {
1003 		r = count;
1004 	}
1005 
1006 	LOG_FUNC_RETURN(card->ctx, r);
1007 }
1008 
sc_update_record(sc_card_t * card,unsigned int rec_nr,const u8 * buf,size_t count,unsigned long flags)1009 int sc_update_record(sc_card_t *card, unsigned int rec_nr, const u8 * buf,
1010 		     size_t count, unsigned long flags)
1011 {
1012 	int r;
1013 
1014 	if (card == NULL) {
1015 		return SC_ERROR_INVALID_ARGUMENTS;
1016 	}
1017 	LOG_FUNC_CALLED(card->ctx);
1018 
1019 	if (card->ops->update_record == NULL)
1020 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
1021 
1022 	r = card->ops->update_record(card, rec_nr, buf, count, flags);
1023 	if (r == SC_SUCCESS) {
1024 		r = count;
1025 	}
1026 
1027 	LOG_FUNC_RETURN(card->ctx, r);
1028 }
1029 
sc_delete_record(sc_card_t * card,unsigned int rec_nr)1030 int sc_delete_record(sc_card_t *card, unsigned int rec_nr)
1031 {
1032 	int r;
1033 
1034 	if (card == NULL) {
1035 		return SC_ERROR_INVALID_ARGUMENTS;
1036 	}
1037 	LOG_FUNC_CALLED(card->ctx);
1038 
1039 	if (card->ops->delete_record == NULL)
1040 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
1041 
1042 	r = card->ops->delete_record(card, rec_nr);
1043 
1044 	LOG_FUNC_RETURN(card->ctx, r);
1045 }
1046 
1047 int
sc_card_ctl(sc_card_t * card,unsigned long cmd,void * args)1048 sc_card_ctl(sc_card_t *card, unsigned long cmd, void *args)
1049 {
1050 	int r = SC_ERROR_NOT_SUPPORTED;
1051 
1052 	if (card == NULL) {
1053 		return SC_ERROR_INVALID_ARGUMENTS;
1054 	}
1055 	LOG_FUNC_CALLED(card->ctx);
1056 
1057 	if (card->ops->card_ctl != NULL)
1058 		r = card->ops->card_ctl(card, cmd, args);
1059 
1060 	/* suppress "not supported" error messages */
1061 	if (r == SC_ERROR_NOT_SUPPORTED) {
1062 		sc_log(card->ctx, "card_ctl(%lu) not supported", cmd);
1063 		return r;
1064 	}
1065 	LOG_FUNC_RETURN(card->ctx, r);
1066 }
1067 
_sc_card_add_algorithm(sc_card_t * card,const sc_algorithm_info_t * info)1068 int _sc_card_add_algorithm(sc_card_t *card, const sc_algorithm_info_t *info)
1069 {
1070 	sc_algorithm_info_t *p;
1071 
1072 	if (info == NULL) {
1073 		return SC_ERROR_INVALID_ARGUMENTS;
1074 	}
1075 	p = (sc_algorithm_info_t *) realloc(card->algorithms, (card->algorithm_count + 1) * sizeof(*info));
1076 	if (!p) {
1077 		return SC_ERROR_OUT_OF_MEMORY;
1078 	}
1079 	card->algorithms = p;
1080 	p += card->algorithm_count;
1081 	card->algorithm_count++;
1082 	*p = *info;
1083 	return SC_SUCCESS;
1084 }
1085 
_sc_card_add_symmetric_alg(sc_card_t * card,unsigned int algorithm,unsigned int key_length,unsigned long flags)1086 int _sc_card_add_symmetric_alg(sc_card_t *card, unsigned int algorithm,
1087 			       unsigned int key_length, unsigned long flags)
1088 {
1089 	sc_algorithm_info_t info;
1090 
1091 	memset(&info, 0, sizeof(info));
1092 	info.algorithm = algorithm;
1093 	info.key_length = key_length;
1094 	info.flags = flags;
1095 
1096 	return _sc_card_add_algorithm(card, &info);
1097 }
1098 
1099 static int
_sc_card_add_ec_alg_int(sc_card_t * card,unsigned int key_length,unsigned long flags,unsigned long ext_flags,struct sc_object_id * curve_oid,int algorithm)1100 _sc_card_add_ec_alg_int(sc_card_t *card, unsigned int key_length,
1101 			unsigned long flags, unsigned long ext_flags,
1102 			struct sc_object_id *curve_oid,
1103 			int algorithm)
1104 {
1105 	sc_algorithm_info_t info;
1106 
1107 	memset(&info, 0, sizeof(info));
1108 	sc_init_oid(&info.u._ec.params.id);
1109 
1110 	info.algorithm = algorithm;
1111 	info.key_length = key_length;
1112 	info.flags = flags;
1113 
1114 	info.u._ec.ext_flags = ext_flags;
1115 	if (curve_oid)
1116 		info.u._ec.params.id = *curve_oid;
1117 
1118 	return _sc_card_add_algorithm(card, &info);
1119 }
1120 
_sc_card_add_ec_alg(sc_card_t * card,unsigned int key_length,unsigned long flags,unsigned long ext_flags,struct sc_object_id * curve_oid)1121 int  _sc_card_add_ec_alg(sc_card_t *card, unsigned int key_length,
1122 			unsigned long flags, unsigned long ext_flags,
1123 			struct sc_object_id *curve_oid)
1124 {
1125 	return _sc_card_add_ec_alg_int(card, key_length, flags, ext_flags,
1126 		curve_oid, SC_ALGORITHM_EC);
1127 }
1128 
_sc_card_add_eddsa_alg(sc_card_t * card,unsigned int key_length,unsigned long flags,unsigned long ext_flags,struct sc_object_id * curve_oid)1129 int  _sc_card_add_eddsa_alg(sc_card_t *card, unsigned int key_length,
1130 			unsigned long flags, unsigned long ext_flags,
1131 			struct sc_object_id *curve_oid)
1132 {
1133 	/* For simplicity, share the ec union with the curve information */
1134 	return _sc_card_add_ec_alg_int(card, key_length, flags, ext_flags,
1135 		curve_oid, SC_ALGORITHM_EDDSA);
1136 }
1137 
_sc_card_add_xeddsa_alg(sc_card_t * card,unsigned int key_length,unsigned long flags,unsigned long ext_flags,struct sc_object_id * curve_oid)1138 int  _sc_card_add_xeddsa_alg(sc_card_t *card, unsigned int key_length,
1139 			unsigned long flags, unsigned long ext_flags,
1140 			struct sc_object_id *curve_oid)
1141 {
1142 	/* For simplicity, share the ec union with the curve information */
1143 	return _sc_card_add_ec_alg_int(card, key_length, flags, ext_flags,
1144 		curve_oid, SC_ALGORITHM_XEDDSA);
1145 }
1146 
sc_card_find_alg(sc_card_t * card,unsigned int algorithm,unsigned int key_length,void * param)1147 sc_algorithm_info_t * sc_card_find_alg(sc_card_t *card,
1148 		unsigned int algorithm, unsigned int key_length, void *param)
1149 {
1150 	int i;
1151 
1152 	for (i = 0; i < card->algorithm_count; i++) {
1153 		sc_algorithm_info_t *info = &card->algorithms[i];
1154 
1155 		if (info->algorithm != algorithm)
1156 			continue;
1157 		if (param)   {
1158 			if (info->algorithm == SC_ALGORITHM_EC ||
1159 				info->algorithm == SC_ALGORITHM_EDDSA ||
1160 				info->algorithm == SC_ALGORITHM_XEDDSA)
1161 				if (sc_compare_oid((struct sc_object_id *)param, &info->u._ec.params.id))
1162 					return info;
1163 		}
1164 		if (info->key_length != key_length)
1165 			continue;
1166 		return info;
1167 	}
1168 	return NULL;
1169 }
1170 
sc_card_find_ec_alg(sc_card_t * card,unsigned int key_length,struct sc_object_id * curve_name)1171 sc_algorithm_info_t * sc_card_find_ec_alg(sc_card_t *card,
1172 		unsigned int key_length, struct sc_object_id *curve_name)
1173 {
1174 	return sc_card_find_alg(card, SC_ALGORITHM_EC, key_length, curve_name);
1175 }
1176 
sc_card_find_eddsa_alg(sc_card_t * card,unsigned int key_length,struct sc_object_id * curve_name)1177 sc_algorithm_info_t * sc_card_find_eddsa_alg(sc_card_t *card,
1178 		unsigned int key_length, struct sc_object_id *curve_name)
1179 {
1180 	return sc_card_find_alg(card, SC_ALGORITHM_EDDSA, key_length, curve_name);
1181 }
1182 
sc_card_find_xeddsa_alg(sc_card_t * card,unsigned int key_length,struct sc_object_id * curve_name)1183 sc_algorithm_info_t * sc_card_find_xeddsa_alg(sc_card_t *card,
1184 		unsigned int key_length, struct sc_object_id *curve_name)
1185 {
1186 	return sc_card_find_alg(card, SC_ALGORITHM_XEDDSA, key_length, curve_name);
1187 }
1188 
_sc_card_add_rsa_alg(sc_card_t * card,unsigned int key_length,unsigned long flags,unsigned long exponent)1189 int _sc_card_add_rsa_alg(sc_card_t *card, unsigned int key_length,
1190 			 unsigned long flags, unsigned long exponent)
1191 {
1192 	sc_algorithm_info_t info;
1193 
1194 	memset(&info, 0, sizeof(info));
1195 	info.algorithm = SC_ALGORITHM_RSA;
1196 	info.key_length = key_length;
1197 	info.flags = flags;
1198 	info.u._rsa.exponent = exponent;
1199 
1200 	return _sc_card_add_algorithm(card, &info);
1201 }
1202 
sc_card_find_rsa_alg(sc_card_t * card,unsigned int key_length)1203 sc_algorithm_info_t * sc_card_find_rsa_alg(sc_card_t *card,
1204 		unsigned int key_length)
1205 {
1206 	return sc_card_find_alg(card, SC_ALGORITHM_RSA, key_length, NULL);
1207 }
1208 
sc_card_find_gostr3410_alg(sc_card_t * card,unsigned int key_length)1209 sc_algorithm_info_t * sc_card_find_gostr3410_alg(sc_card_t *card,
1210 		unsigned int key_length)
1211 {
1212 	return sc_card_find_alg(card, SC_ALGORITHM_GOSTR3410, key_length, NULL);
1213 }
1214 
match_atr_table(sc_context_t * ctx,const struct sc_atr_table * table,struct sc_atr * atr)1215 static int match_atr_table(sc_context_t *ctx, const struct sc_atr_table *table, struct sc_atr *atr)
1216 {
1217 	u8 *card_atr_bin;
1218 	size_t card_atr_bin_len;
1219 	char card_atr_hex[3 * SC_MAX_ATR_SIZE];
1220 	size_t card_atr_hex_len;
1221 	unsigned int i = 0;
1222 
1223 	if (ctx == NULL || table == NULL || atr == NULL)
1224 		return -1;
1225 	card_atr_bin = atr->value;
1226 	card_atr_bin_len = atr->len;
1227 	sc_bin_to_hex(card_atr_bin, card_atr_bin_len, card_atr_hex, sizeof(card_atr_hex), ':');
1228 	card_atr_hex_len = strlen(card_atr_hex);
1229 
1230 	sc_debug(ctx, SC_LOG_DEBUG_MATCH, "ATR     : %s", card_atr_hex);
1231 
1232 	for (i = 0; table[i].atr != NULL; i++) {
1233 		const char *tatr = table[i].atr;
1234 		const char *matr = table[i].atrmask;
1235 		size_t tatr_len = strlen(tatr);
1236 		u8 mbin[SC_MAX_ATR_SIZE], tbin[SC_MAX_ATR_SIZE];
1237 		size_t mbin_len, tbin_len, s, matr_len;
1238 		size_t fix_hex_len = card_atr_hex_len;
1239 		size_t fix_bin_len = card_atr_bin_len;
1240 
1241 		sc_debug(ctx, SC_LOG_DEBUG_MATCH, "ATR try : %s", tatr);
1242 
1243 		if (tatr_len != fix_hex_len) {
1244 			sc_debug(ctx, SC_LOG_DEBUG_MATCH, "ignored - wrong length");
1245 			continue;
1246 		}
1247 		if (matr != NULL) {
1248 			sc_debug(ctx, SC_LOG_DEBUG_MATCH, "ATR mask: %s", matr);
1249 
1250 			matr_len = strlen(matr);
1251 			if (tatr_len != matr_len)
1252 				continue;
1253 			tbin_len = sizeof(tbin);
1254 			sc_hex_to_bin(tatr, tbin, &tbin_len);
1255 			mbin_len = sizeof(mbin);
1256 			sc_hex_to_bin(matr, mbin, &mbin_len);
1257 			if (mbin_len != fix_bin_len) {
1258 				sc_debug(ctx, SC_LOG_DEBUG_MATCH, "length of atr and atr mask do not match - ignored: %s - %s", tatr, matr);
1259 				continue;
1260 			}
1261 			for (s = 0; s < tbin_len; s++) {
1262 				/* reduce tatr with mask */
1263 				tbin[s] = (tbin[s] & mbin[s]);
1264 				/* create copy of card_atr_bin masked) */
1265 				mbin[s] = (card_atr_bin[s] & mbin[s]);
1266 			}
1267 			if (memcmp(tbin, mbin, tbin_len) != 0)
1268 				continue;
1269 		} else {
1270 			if (strncasecmp(tatr, card_atr_hex, tatr_len) != 0)
1271 				continue;
1272 		}
1273 		return i;
1274 	}
1275 	return -1;
1276 }
1277 
_sc_match_atr(sc_card_t * card,const struct sc_atr_table * table,int * type_out)1278 int _sc_match_atr(sc_card_t *card, const struct sc_atr_table *table, int *type_out)
1279 {
1280 	int res;
1281 
1282 	if (card == NULL)
1283 		return -1;
1284 	res = match_atr_table(card->ctx, table, &card->atr);
1285 	if (res < 0)
1286 		return res;
1287 	if (type_out != NULL)
1288 		*type_out = table[res].type;
1289 	return res;
1290 }
1291 
_sc_match_atr_block(sc_context_t * ctx,struct sc_card_driver * driver,struct sc_atr * atr)1292 scconf_block *_sc_match_atr_block(sc_context_t *ctx, struct sc_card_driver *driver, struct sc_atr *atr)
1293 {
1294 	struct sc_card_driver *drv;
1295 	struct sc_atr_table *table;
1296 	int res;
1297 
1298 	if (ctx == NULL)
1299 		return NULL;
1300 	if (driver) {
1301 		drv = driver;
1302 		table = drv->atr_map;
1303 		res = match_atr_table(ctx, table, atr);
1304 		if (res < 0)
1305 			return NULL;
1306 		return table[res].card_atr;
1307 	} else {
1308 		unsigned int i;
1309 
1310 		for (i = 0; ctx->card_drivers[i] != NULL; i++) {
1311 			drv = ctx->card_drivers[i];
1312 			table = drv->atr_map;
1313 			res = match_atr_table(ctx, table, atr);
1314 			if (res < 0)
1315 				continue;
1316 			return table[res].card_atr;
1317 		}
1318 	}
1319 	return NULL;
1320 }
1321 
_sc_add_atr(sc_context_t * ctx,struct sc_card_driver * driver,struct sc_atr_table * src)1322 int _sc_add_atr(sc_context_t *ctx, struct sc_card_driver *driver, struct sc_atr_table *src)
1323 {
1324 	struct sc_atr_table *map, *dst;
1325 
1326 	map = (struct sc_atr_table *) realloc(driver->atr_map,
1327 			(driver->natrs + 2) * sizeof(struct sc_atr_table));
1328 	if (!map)
1329 		return SC_ERROR_OUT_OF_MEMORY;
1330 	driver->atr_map = map;
1331 
1332 	dst = &driver->atr_map[driver->natrs++];
1333 	memset(dst, 0, sizeof(*dst));
1334 	memset(&driver->atr_map[driver->natrs], 0, sizeof(struct sc_atr_table));
1335 	dst->atr = strdup(src->atr);
1336 	if (!dst->atr)
1337 		return SC_ERROR_OUT_OF_MEMORY;
1338 
1339 	if (src->atrmask) {
1340 		dst->atrmask = strdup(src->atrmask);
1341 		if (!dst->atrmask)
1342 			return SC_ERROR_OUT_OF_MEMORY;
1343 	}
1344 	else {
1345 		dst->atrmask = NULL;
1346 	}
1347 
1348 	if (src->name) {
1349 		dst->name = strdup(src->name);
1350 		if (!dst->name)
1351 			return SC_ERROR_OUT_OF_MEMORY;
1352 	}
1353 	else {
1354 		dst->name = NULL;
1355 	}
1356 
1357 	dst->type = src->type;
1358 	dst->flags = src->flags;
1359 	dst->card_atr = src->card_atr;
1360 
1361 	return SC_SUCCESS;
1362 }
1363 
1364 
_sc_free_atr(sc_context_t * ctx,struct sc_card_driver * driver)1365 int _sc_free_atr(sc_context_t *ctx, struct sc_card_driver *driver)
1366 {
1367 	unsigned int i;
1368 
1369 	for (i = 0; i < driver->natrs; i++) {
1370 		struct sc_atr_table *src = &driver->atr_map[i];
1371 
1372 		if (src->atr)
1373 			free((void *)src->atr);
1374 		if (src->atrmask)
1375 			free((void *)src->atrmask);
1376 		if (src->name)
1377 			free((void *)src->name);
1378 		src->card_atr = NULL;
1379 		src = NULL;
1380 	}
1381 	if (driver->atr_map)
1382 		free(driver->atr_map);
1383 	driver->atr_map = NULL;
1384 	driver->natrs = 0;
1385 
1386 	return SC_SUCCESS;
1387 }
1388 
1389 
sc_get_conf_block(sc_context_t * ctx,const char * name1,const char * name2,int priority)1390 scconf_block *sc_get_conf_block(sc_context_t *ctx, const char *name1, const char *name2, int priority)
1391 {
1392 	int i;
1393 	scconf_block *conf_block = NULL;
1394 
1395 	for (i = 0; ctx->conf_blocks[i] != NULL; i++) {
1396 		scconf_block **blocks;
1397 
1398 		blocks = scconf_find_blocks(ctx->conf, ctx->conf_blocks[i], name1, name2);
1399 		if (blocks != NULL) {
1400 			conf_block = blocks[0];
1401 			free(blocks);
1402 		}
1403 		if (conf_block != NULL && priority)
1404 			break;
1405 	}
1406 	return conf_block;
1407 }
1408 
sc_invalidate_cache(struct sc_card * card)1409 void sc_invalidate_cache(struct sc_card *card)
1410 {
1411 	if (card) {
1412 		sc_file_free(card->cache.current_ef);
1413 		sc_file_free(card->cache.current_df);
1414 		memset(&card->cache, 0, sizeof(card->cache));
1415 		card->cache.valid = 0;
1416 	}
1417 }
1418 
sc_print_cache(struct sc_card * card)1419 void sc_print_cache(struct sc_card *card)
1420 {
1421 	struct sc_context *ctx = NULL;
1422 
1423 	if (card == NULL)
1424 		return;
1425 	ctx = card->ctx;
1426 
1427 	if (!card->cache.valid || (!card->cache.current_ef && !card->cache.current_df))   {
1428 		sc_log(ctx, "card cache invalid");
1429 		return;
1430 	}
1431 
1432 	if (card->cache.current_ef)
1433 		sc_log(ctx, "current_ef(type=%i) %s", card->cache.current_ef->path.type,
1434 				sc_print_path(&card->cache.current_ef->path));
1435 
1436 	if (card->cache.current_df)
1437 		sc_log(ctx,
1438 		       "current_df(type=%i, aid_len=%"SC_FORMAT_LEN_SIZE_T"u) %s",
1439 		       card->cache.current_df->path.type,
1440 		       card->cache.current_df->path.aid.len,
1441 		       sc_print_path(&card->cache.current_df->path));
1442 }
1443 
sc_copy_ec_params(struct sc_ec_parameters * dst,struct sc_ec_parameters * src)1444 int sc_copy_ec_params(struct sc_ec_parameters *dst, struct sc_ec_parameters *src)
1445 {
1446 	if (!dst || !src)
1447 		return SC_ERROR_INVALID_ARGUMENTS;
1448 
1449 	memset(dst, 0, sizeof(*dst));
1450 	if (src->named_curve)   {
1451 		dst->named_curve = strdup(src->named_curve);
1452 		if (!dst->named_curve)
1453 			return SC_ERROR_OUT_OF_MEMORY;
1454 	}
1455 	dst->id = src->id;
1456 	if (src->der.value && src->der.len)   {
1457 		dst->der.value = malloc(src->der.len);
1458 		if (!dst->der.value)
1459 			return SC_ERROR_OUT_OF_MEMORY;
1460 		memcpy(dst->der.value, src->der.value, src->der.len);
1461 		dst->der.len = src->der.len;
1462 	}
1463 	src->type = dst->type;
1464 	src->field_length = dst->field_length;
1465 
1466 	return SC_SUCCESS;
1467 }
1468 
1469 scconf_block *
sc_match_atr_block(sc_context_t * ctx,struct sc_card_driver * driver,struct sc_atr * atr)1470 sc_match_atr_block(sc_context_t *ctx, struct sc_card_driver *driver, struct sc_atr *atr)
1471 {
1472 	return _sc_match_atr_block(ctx, driver, atr);
1473 }
1474 
1475 #ifdef ENABLE_SM
1476 static int
sc_card_sm_unload(struct sc_card * card)1477 sc_card_sm_unload(struct sc_card *card)
1478 {
1479 	if (card->sm_ctx.module.ops.module_cleanup)
1480 		card->sm_ctx.module.ops.module_cleanup(card->ctx);
1481 
1482 	if (card->sm_ctx.module.handle)
1483 		sc_dlclose(card->sm_ctx.module.handle);
1484 	card->sm_ctx.module.handle = NULL;
1485 	return 0;
1486 }
1487 
1488 
1489 static int
sc_card_sm_load(struct sc_card * card,const char * module_path,const char * in_module)1490 sc_card_sm_load(struct sc_card *card, const char *module_path, const char *in_module)
1491 {
1492 	struct sc_context *ctx = NULL;
1493 	int rv = SC_ERROR_INTERNAL;
1494 	char *module = NULL;
1495 #ifdef _WIN32
1496 	char temp_path[PATH_MAX];
1497 	size_t temp_len;
1498 	const char path_delim = '\\';
1499 	char expanded_val[PATH_MAX];
1500 	DWORD expanded_len;
1501 #else
1502 	const char path_delim = '/';
1503 #endif
1504 
1505 	if (card == NULL) {
1506 		return SC_ERROR_INVALID_ARGUMENTS;
1507 	}
1508 	ctx = card->ctx;
1509 	LOG_FUNC_CALLED(ctx);
1510 	if (!in_module)
1511 		return sc_card_sm_unload(card);
1512 
1513 #ifdef _WIN32
1514 	if (!module_path || strlen(module_path) == 0)   {
1515 		temp_len = PATH_MAX-1;
1516 		rv = sc_ctx_win32_get_config_value(NULL, "SmDir", "Software\\OpenSC Project\\OpenSC",
1517 				temp_path, &temp_len);
1518 		if (rv == SC_SUCCESS) {
1519 			temp_path[temp_len] = '\0';
1520 			module_path = temp_path;
1521 		}
1522 	}
1523 	expanded_len = PATH_MAX;
1524 	expanded_len = ExpandEnvironmentStringsA(module_path, expanded_val, expanded_len);
1525 	if (0 < expanded_len && expanded_len < sizeof expanded_val)
1526 		module_path = expanded_val;
1527 #endif
1528 	sc_log(ctx, "SM module '%s' located in '%s'", in_module, module_path);
1529 	if (module_path && strlen(module_path) > 0)   {
1530 		int sz = strlen(in_module) + strlen(module_path) + 3;
1531 		module = malloc(sz);
1532 		if (module)
1533 			snprintf(module, sz, "%s%c%s", module_path, path_delim, in_module);
1534 	}
1535 	else   {
1536 		module = strdup(in_module);
1537 	}
1538 
1539 	if (!module)
1540 		return SC_ERROR_OUT_OF_MEMORY;
1541 
1542 	sc_log(ctx, "try to load SM module '%s'", module);
1543 	do  {
1544 		struct sm_module_operations *mod_ops = &card->sm_ctx.module.ops;
1545 		void *mod_handle;
1546 
1547 		card->sm_ctx.module.handle = sc_dlopen(module);
1548 		if (!card->sm_ctx.module.handle)   {
1549 			sc_log(ctx, "cannot open dynamic library '%s': %s", module, sc_dlerror());
1550 			break;
1551 		}
1552 		mod_handle = card->sm_ctx.module.handle;
1553 
1554 		mod_ops->initialize = sc_dlsym(mod_handle, "initialize");
1555 		if (!mod_ops->initialize)   {
1556 			sc_log(ctx, "SM handler 'initialize' not exported: %s", sc_dlerror());
1557 			break;
1558 		}
1559 
1560 		mod_ops->get_apdus  = sc_dlsym(mod_handle, "get_apdus");
1561 		if (!mod_ops->get_apdus)   {
1562 			sc_log(ctx, "SM handler 'get_apdus' not exported: %s", sc_dlerror());
1563 			break;
1564 		}
1565 
1566 		mod_ops->finalize  = sc_dlsym(mod_handle, "finalize");
1567 		if (!mod_ops->finalize)
1568 			sc_log(ctx, "SM handler 'finalize' not exported -- ignored");
1569 
1570 		mod_ops->module_init  = sc_dlsym(mod_handle, "module_init");
1571 		if (!mod_ops->module_init)
1572 			sc_log(ctx, "SM handler 'module_init' not exported -- ignored");
1573 
1574 		mod_ops->module_cleanup  = sc_dlsym(mod_handle, "module_cleanup");
1575 		if (!mod_ops->module_cleanup)
1576 			sc_log(ctx, "SM handler 'module_cleanup' not exported -- ignored");
1577 
1578 		mod_ops->test  = sc_dlsym(mod_handle, "test");
1579 		if (mod_ops->test)
1580 			sc_log(ctx, "SM handler 'test' not exported -- ignored");
1581 
1582 		rv = 0;
1583 		break;
1584 	} while(0);
1585 
1586 	if (rv)
1587 		sc_card_sm_unload(card);
1588 
1589 	card->sm_ctx.sm_mode = SM_MODE_ACL;
1590 	if (module)
1591 		free(module);
1592 
1593 	SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, rv);
1594 }
1595 
1596 
1597 /* get SM related configuration settings and initialize SM session, SM module, ... */
1598 static int
sc_card_sm_check(struct sc_card * card)1599 sc_card_sm_check(struct sc_card *card)
1600 {
1601 	const char *sm = NULL, *module_name = NULL, *module_path = NULL, *module_data = NULL, *sm_mode = NULL;
1602 	struct sc_context *ctx = card->ctx;
1603 	scconf_block *atrblock = NULL, *sm_conf_block = NULL;
1604 	int rv, ii;
1605 
1606 	LOG_FUNC_CALLED(ctx);
1607 
1608 	/* get the name of card specific SM configuration section */
1609 	atrblock = _sc_match_atr_block(ctx, card->driver, &card->atr);
1610 	if (atrblock == NULL)
1611 		LOG_FUNC_RETURN(ctx, SC_SUCCESS);
1612 	sm = scconf_get_str(atrblock, "secure_messaging", NULL);
1613 	if (!sm)
1614 		LOG_FUNC_RETURN(ctx, SC_SUCCESS);
1615 
1616 	/* get SM configuration section by the name */
1617 	sc_log(ctx, "secure_messaging configuration block '%s'", sm);
1618         for (ii = 0; ctx->conf_blocks[ii]; ii++) {
1619 		scconf_block **blocks;
1620 
1621 		blocks = scconf_find_blocks(ctx->conf, ctx->conf_blocks[ii], "secure_messaging", sm);
1622 		if (blocks) {
1623 			sm_conf_block = blocks[0];
1624 			free(blocks);
1625 		}
1626 		if (sm_conf_block != NULL)
1627 			break;
1628 	}
1629 
1630 	if (!sm_conf_block)
1631 		LOG_TEST_RET(ctx, SC_ERROR_INCONSISTENT_CONFIGURATION, "SM configuration block not preset");
1632 
1633 	/* check if an external SM module has to be used */
1634 	module_path = scconf_get_str(sm_conf_block, "module_path", DEFAULT_SM_MODULE_PATH);
1635 	module_name = scconf_get_str(sm_conf_block, "module_name", DEFAULT_SM_MODULE);
1636 	sc_log(ctx, "SM module '%s' in  '%s'", module_name, module_path);
1637 	if (!module_name)
1638 		LOG_TEST_RET(ctx, SC_ERROR_INCONSISTENT_CONFIGURATION, "Invalid SM configuration: module not defined");
1639 
1640 	rv = sc_card_sm_load(card, module_path, module_name);
1641 	LOG_TEST_RET(ctx, rv, "Failed to load SM module");
1642 
1643 	strlcpy(card->sm_ctx.module.filename, module_name, sizeof(card->sm_ctx.module.filename));
1644 	strlcpy(card->sm_ctx.config_section, sm, sizeof(card->sm_ctx.config_section));
1645 
1646 	/* allocate resources for the external SM module */
1647 	if (card->sm_ctx.module.ops.module_init)   {
1648 		module_data = scconf_get_str(sm_conf_block, "module_data", NULL);
1649 
1650 		rv = card->sm_ctx.module.ops.module_init(ctx, module_data);
1651 		LOG_TEST_RET(ctx, rv, "Cannot initialize SM module");
1652 	}
1653 
1654 	/* initialize SM session in the case of 'APDU TRANSMIT' SM mode */
1655 	sm_mode = scconf_get_str(sm_conf_block, "mode", NULL);
1656 	if (sm_mode && !strcasecmp("Transmit", sm_mode))   {
1657 		if (!card->sm_ctx.ops.open || !card->sm_ctx.ops.get_sm_apdu || !card->sm_ctx.ops.free_sm_apdu)
1658 			LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "'Transmit' SM asked but not supported by card driver");
1659 
1660 		card->sm_ctx.sm_mode = SM_MODE_TRANSMIT;
1661 		rv = card->sm_ctx.ops.open(card);
1662 		LOG_TEST_RET(ctx, rv, "Cannot initialize SM");
1663 	}
1664 
1665 	sc_log(ctx, "SM mode:%X", card->sm_ctx.sm_mode);
1666 	SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, rv);
1667 }
1668 #endif
1669