1 /*
2  * apdu.c: basic APDU handling functions
3  *
4  * Copyright (C) 2005 Nils Larsch <nils@larsch.net>
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 <stdio.h>
26 #include <stdlib.h>
27 #include <assert.h>
28 #include <string.h>
29 
30 #include "internal.h"
31 #include "asn1.h"
32 
33 /*********************************************************************/
34 /*   low level APDU handling functions                               */
35 /*********************************************************************/
36 
37 /** Calculates the length of the encoded APDU in octets.
38  *  @param  apdu   the APDU
39  *  @param  proto  the desired protocol
40  *  @return length of the encoded APDU
41  */
sc_apdu_get_length(const sc_apdu_t * apdu,unsigned int proto)42 size_t sc_apdu_get_length(const sc_apdu_t *apdu, unsigned int proto)
43 {
44 	size_t ret = 4;
45 
46 	switch (apdu->cse) {
47 	case SC_APDU_CASE_1:
48 		if (proto == SC_PROTO_T0)
49 			ret++;
50 		break;
51 	case SC_APDU_CASE_2_SHORT:
52 		ret++;
53 		break;
54 	case SC_APDU_CASE_2_EXT:
55 		ret += (proto == SC_PROTO_T0 ? 1 : 3);
56 		break;
57 	case SC_APDU_CASE_3_SHORT:
58 		ret += 1 + apdu->lc;
59 		break;
60 	case SC_APDU_CASE_3_EXT:
61 		ret += apdu->lc + (proto == SC_PROTO_T0 ? 1 : 3);
62 		break;
63 	case SC_APDU_CASE_4_SHORT:
64 		ret += apdu->lc + (proto != SC_PROTO_T0 ? 2 : 1);
65 		break;
66 	case SC_APDU_CASE_4_EXT:
67 		ret += apdu->lc + (proto == SC_PROTO_T0 ? 1 : 5);
68 		break;
69 	default:
70 		return 0;
71 	}
72 	return ret;
73 }
74 
75 /** Encodes a APDU as an octet string
76  *  @param  ctx     sc_context_t object (used for logging)
77  *  @param  apdu    APDU to be encoded as an octet string
78  *  @param  proto   protocol version to be used
79  *  @param  out     output buffer of size outlen.
80  *  @param  outlen  size of the output buffer
81  *  @return SC_SUCCESS on success and an error code otherwise
82  */
sc_apdu2bytes(sc_context_t * ctx,const sc_apdu_t * apdu,unsigned int proto,u8 * out,size_t outlen)83 int sc_apdu2bytes(sc_context_t *ctx, const sc_apdu_t *apdu,
84 	unsigned int proto, u8 *out, size_t outlen)
85 {
86 	u8     *p = out;
87 
88 	size_t len = sc_apdu_get_length(apdu, proto);
89 
90 	if (out == NULL || outlen < len)
91 		return SC_ERROR_INVALID_ARGUMENTS;
92 	/* CLA, INS, P1 and P2 */
93 	*p++ = apdu->cla;
94 	*p++ = apdu->ins;
95 	*p++ = apdu->p1;
96 	*p++ = apdu->p2;
97 	/* case depend part */
98 	switch (apdu->cse) {
99 	case SC_APDU_CASE_1:
100 		/* T0 needs an additional 0x00 byte */
101 		if (proto == SC_PROTO_T0)
102 			*p = (u8)0x00;
103 		break;
104 	case SC_APDU_CASE_2_SHORT:
105 		*p = (u8)apdu->le;
106 		break;
107 	case SC_APDU_CASE_2_EXT:
108 		if (proto == SC_PROTO_T0)
109 			/* T0 extended APDUs look just like short APDUs */
110 			*p = (u8)apdu->le;
111 		else {
112 			/* in case of T1 always use 3 bytes for length */
113 			*p++ = (u8)0x00;
114 			*p++ = (u8)(apdu->le >> 8);
115 			*p = (u8)apdu->le;
116 		}
117 		break;
118 	case SC_APDU_CASE_3_SHORT:
119 		*p++ = (u8)apdu->lc;
120 		memcpy(p, apdu->data, apdu->lc);
121 		break;
122 	case SC_APDU_CASE_3_EXT:
123 		if (proto == SC_PROTO_T0) {
124 			/* in case of T0 the command is transmitted in chunks
125 			 * < 255 using the ENVELOPE command ... */
126 			if (apdu->lc > 255) {
127 				/* ... so if Lc is greater than 255 bytes
128 				 * an error has occurred on a higher level */
129 				sc_log(ctx, "invalid Lc length for CASE 3 extended APDU (need ENVELOPE)");
130 				return SC_ERROR_INVALID_ARGUMENTS;
131 			}
132 		}
133 		else {
134 			/* in case of T1 always use 3 bytes for length */
135 			*p++ = (u8)0x00;
136 			*p++ = (u8)(apdu->lc >> 8);
137 			*p++ = (u8)apdu->lc;
138 		}
139 		memcpy(p, apdu->data, apdu->lc);
140 		break;
141 	case SC_APDU_CASE_4_SHORT:
142 		*p++ = (u8)apdu->lc;
143 		memcpy(p, apdu->data, apdu->lc);
144 		p += apdu->lc;
145 		/* in case of T0 no Le byte is added */
146 		if (proto != SC_PROTO_T0)
147 			*p = (u8)apdu->le;
148 		break;
149 	case SC_APDU_CASE_4_EXT:
150 		if (proto == SC_PROTO_T0) {
151 			/* again a T0 extended case 4 APDU looks just
152 			 * like a short APDU, the additional data is
153 			 * transferred using ENVELOPE and GET RESPONSE */
154 			*p++ = (u8)apdu->lc;
155 			memcpy(p, apdu->data, apdu->lc);
156 		}
157 		else {
158 			*p++ = (u8)0x00;
159 			*p++ = (u8)(apdu->lc >> 8);
160 			*p++ = (u8)apdu->lc;
161 			memcpy(p, apdu->data, apdu->lc);
162 			p += apdu->lc;
163 			/* only 2 bytes are use to specify the length of the
164 			 * expected data */
165 			*p++ = (u8)(apdu->le >> 8);
166 			*p = (u8)apdu->le;
167 		}
168 		break;
169 	}
170 
171 	return SC_SUCCESS;
172 }
173 
sc_apdu_get_octets(sc_context_t * ctx,const sc_apdu_t * apdu,u8 ** buf,size_t * len,unsigned int proto)174 int sc_apdu_get_octets(sc_context_t *ctx, const sc_apdu_t *apdu, u8 **buf,
175 	size_t *len, unsigned int proto)
176 {
177 	size_t	nlen;
178 	u8	*nbuf;
179 
180 	if (apdu == NULL || buf == NULL || len == NULL)
181 		return SC_ERROR_INVALID_ARGUMENTS;
182 
183 	/* get the estimated length of encoded APDU */
184 	nlen = sc_apdu_get_length(apdu, proto);
185 	if (nlen == 0)
186 		return SC_ERROR_INTERNAL;
187 	nbuf = malloc(nlen);
188 	if (nbuf == NULL)
189 		return SC_ERROR_OUT_OF_MEMORY;
190 	/* encode the APDU in the buffer */
191 	if (sc_apdu2bytes(ctx, apdu, proto, nbuf, nlen) != SC_SUCCESS) {
192 		free(nbuf);
193 		return SC_ERROR_INTERNAL;
194 	}
195 	*buf = nbuf;
196 	*len = nlen;
197 
198 	return SC_SUCCESS;
199 }
200 
sc_apdu_set_resp(sc_context_t * ctx,sc_apdu_t * apdu,const u8 * buf,size_t len)201 int sc_apdu_set_resp(sc_context_t *ctx, sc_apdu_t *apdu, const u8 *buf,
202 	size_t len)
203 {
204 	if (len < 2) {
205 		/* no SW1 SW2 ... something went terrible wrong */
206 		sc_log(ctx, "invalid response: SW1 SW2 missing");
207 		return SC_ERROR_INTERNAL;
208 	}
209 	/* set the SW1 and SW2 status bytes (the last two bytes of
210 	 * the response */
211 	apdu->sw1 = (unsigned int)buf[len - 2];
212 	apdu->sw2 = (unsigned int)buf[len - 1];
213 	len -= 2;
214 	/* set output length and copy the returned data if necessary */
215 	if (len <= apdu->resplen)
216 		apdu->resplen = len;
217 
218 	if (apdu->resplen != 0)
219 		memcpy(apdu->resp, buf, apdu->resplen);
220 
221 	return SC_SUCCESS;
222 }
223 
224 
225 /*********************************************************************/
226 /*   higher level APDU transfer handling functions                   */
227 /*********************************************************************/
228 /*   +------------------+
229  *   | sc_transmit_apdu |
230  *   +------------------+
231  *         |  |  |
232  *         |  |  |     detect APDU cse               +--------------------+
233  *         |  |  +---------------------------------> | sc_detect_apdu_cse |
234  *         |  |                                      +--------------------+
235  *         |  |        check consistency of APDU     +--------------------+
236  *         |  +------------------------------------> | sc_check_apdu      |
237  *         |                                         +--------------------+
238  *         |           send single APDU              +--------------------+
239  *         +---------------------------------------> | sc_transmit        |
240  *                        ^                          +--------------------+
241  *                        |                               |
242  *                        |  re-transmit if wrong length  |
243  *                        |       or GET RESPONSE         |
244  *                        +-------------------------------+
245  *                                                        |
246  *                                                        v
247  *                                               card->reader->ops->transmit
248  */
249 
250 /** basic consistency check of the sc_apdu_t object
251  *  @param  ctx   sc_context_t object for error messages
252  *  @param  apdu  sc_apdu_t object to check
253  *  @return SC_SUCCESS on success and an error code otherwise
254  */
255 int
sc_check_apdu(sc_card_t * card,const sc_apdu_t * apdu)256 sc_check_apdu(sc_card_t *card, const sc_apdu_t *apdu)
257 {
258 	if ((apdu->cse & ~SC_APDU_SHORT_MASK) == 0) {
259 		/* length check for short APDU */
260 		if (apdu->le > 256 || (apdu->lc > 255 && (apdu->flags & SC_APDU_FLAGS_CHAINING) == 0))   {
261 			sc_log(card->ctx, "failed length check for short APDU");
262 			goto error;
263 		}
264 	}
265 	else if ((apdu->cse & SC_APDU_EXT) != 0) {
266 		/* check if the card supports extended APDUs */
267 		if ((card->caps & SC_CARD_CAP_APDU_EXT) == 0) {
268 			sc_log(card->ctx, "card doesn't support extended APDUs");
269 			goto error;
270 		}
271 		/* length check for extended APDU */
272 		if (apdu->le > 65536 || apdu->lc > 65535)   {
273 			sc_log(card->ctx, "failed length check for extended APDU");
274 			goto error;
275 		}
276 	}
277 	else   {
278 		goto error;
279 	}
280 
281 	switch (apdu->cse & SC_APDU_SHORT_MASK) {
282 	case SC_APDU_CASE_1:
283 		/* no data is sent or received */
284 		if (apdu->datalen != 0 || apdu->lc != 0 || apdu->le != 0)
285 			goto error;
286 		break;
287 	case SC_APDU_CASE_2_SHORT:
288 		/* no data is sent */
289 		if (apdu->datalen != 0 || apdu->lc != 0)
290 			goto error;
291 		/* data is expected       */
292 		if (apdu->resplen == 0 || apdu->resp == NULL)
293 			goto error;
294 		break;
295 	case SC_APDU_CASE_3_SHORT:
296 		/* data is sent */
297 		if (apdu->datalen == 0 || apdu->data == NULL || apdu->lc == 0)
298 			goto error;
299 		/* no data is expected    */
300 		if (apdu->le != 0)
301 			goto error;
302 		/* inconsistent datalen   */
303 		if (apdu->datalen != apdu->lc)
304 			goto error;
305 		break;
306 	case SC_APDU_CASE_4_SHORT:
307 		/* data is sent */
308 		if (apdu->datalen == 0 || apdu->data == NULL || apdu->lc == 0)
309 			goto error;
310 		/* data is expected       */
311 		if (apdu->resplen == 0 || apdu->resp == NULL)
312 			goto error;
313 		/* inconsistent datalen   */
314 		if (apdu->datalen != apdu->lc)
315 			goto error;
316 		break;
317 	default:
318 		sc_log(card->ctx, "Invalid APDU case %d", apdu->cse);
319 		return SC_ERROR_INVALID_ARGUMENTS;
320 	}
321 	return SC_SUCCESS;
322 error:
323 	sc_log(card->ctx, "Invalid Case %d %s APDU:\n"
324 		"cse=%02x cla=%02x ins=%02x p1=%02x p2=%02x lc=%lu le=%lu\n"
325 		"resp=%p resplen=%lu data=%p datalen=%lu",
326 		apdu->cse & SC_APDU_SHORT_MASK,
327 		(apdu->cse & SC_APDU_EXT) != 0 ? "extended" : "short",
328 		apdu->cse, apdu->cla, apdu->ins, apdu->p1, apdu->p2,
329 		(unsigned long) apdu->lc, (unsigned long) apdu->le,
330 		apdu->resp, (unsigned long) apdu->resplen,
331 		apdu->data, (unsigned long) apdu->datalen);
332 	return SC_ERROR_INVALID_ARGUMENTS;
333 }
334 
335 /** Tries to determine the APDU type (short or extended) of the supplied
336  *  APDU if one of the SC_APDU_CASE_? types is used.
337  *  @param  apdu  APDU object
338  */
339 static void
sc_detect_apdu_cse(const sc_card_t * card,sc_apdu_t * apdu)340 sc_detect_apdu_cse(const sc_card_t *card, sc_apdu_t *apdu)
341 {
342 	if (apdu->cse == SC_APDU_CASE_2 || apdu->cse == SC_APDU_CASE_3 ||
343 	    apdu->cse == SC_APDU_CASE_4) {
344 		int btype = apdu->cse & SC_APDU_SHORT_MASK;
345 		/* if either Lc or Le is bigger than the maximum for
346 		 * short APDUs and the card supports extended APDUs
347 		 * use extended APDUs (unless Lc is greater than
348 		 * 255 and command chaining is activated) */
349 		if ((apdu->le > 256 || (apdu->lc > 255 && (apdu->flags & SC_APDU_FLAGS_CHAINING) == 0)) &&
350 		    (card->caps & SC_CARD_CAP_APDU_EXT) != 0)
351 			btype |= SC_APDU_EXT;
352 		apdu->cse = btype;
353 	}
354 }
355 
356 
357 static int
sc_single_transmit(struct sc_card * card,struct sc_apdu * apdu)358 sc_single_transmit(struct sc_card *card, struct sc_apdu *apdu)
359 {
360 	struct sc_context *ctx  = card->ctx;
361 	int rv;
362 
363 	LOG_FUNC_CALLED(ctx);
364 	if (card->reader->ops->transmit == NULL)
365 		LOG_TEST_RET(card->ctx, SC_ERROR_NOT_SUPPORTED, "cannot transmit APDU");
366 
367 	sc_log(ctx,
368 	       "CLA:%X, INS:%X, P1:%X, P2:%X, data(%"SC_FORMAT_LEN_SIZE_T"u) %p",
369 	       apdu->cla, apdu->ins, apdu->p1, apdu->p2, apdu->datalen,
370 	       apdu->data);
371 #ifdef ENABLE_SM
372 	if (card->sm_ctx.sm_mode == SM_MODE_TRANSMIT
373 		   	&& (apdu->flags & SC_APDU_FLAGS_NO_SM) == 0) {
374 		LOG_FUNC_RETURN(ctx, sc_sm_single_transmit(card, apdu));
375 	}
376 #endif
377 
378 	/* send APDU to the reader driver */
379 	rv = card->reader->ops->transmit(card->reader, apdu);
380 	LOG_TEST_RET(ctx, rv, "unable to transmit APDU");
381 
382 	LOG_FUNC_RETURN(ctx, rv);
383 }
384 
385 
386 static int
sc_set_le_and_transmit(struct sc_card * card,struct sc_apdu * apdu,size_t olen)387 sc_set_le_and_transmit(struct sc_card *card, struct sc_apdu *apdu, size_t olen)
388 {
389 	struct sc_context *ctx  = card->ctx;
390 	size_t nlen = apdu->sw2 ? (size_t)apdu->sw2 : 256;
391 	int rv;
392 
393 	LOG_FUNC_CALLED(ctx);
394 	/* we cannot re-transmit the APDU with the demanded Le value
395 	 * as the buffer is too small => error */
396 	if (olen < nlen)
397 		LOG_TEST_RET(ctx, SC_ERROR_WRONG_LENGTH, "wrong length: required length exceeds resplen");
398 
399 	/* don't try again if it doesn't work this time */
400 	apdu->flags  |= SC_APDU_FLAGS_NO_RETRY_WL;
401 	/* set the new expected length */
402 	apdu->resplen = olen;
403 	apdu->le      = nlen;
404 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
405 	/* Belpic V1 applets have a problem: if the card sends a 6C XX (only XX bytes available),
406 	 * and we resend the command too soon (i.e. the reader is too fast), the card doesn't respond.
407 	 * So we build in a delay. */
408 	if (card->type == SC_CARD_TYPE_BELPIC_EID)
409 		msleep(40);
410 #endif
411 
412 	/* re-transmit the APDU with new Le length */
413 	rv = sc_single_transmit(card, apdu);
414 	LOG_TEST_RET(ctx, rv, "cannot re-transmit APDU");
415 
416 	LOG_FUNC_RETURN(ctx, rv);
417 }
418 
419 
420 static int
sc_get_response(struct sc_card * card,struct sc_apdu * apdu,size_t olen)421 sc_get_response(struct sc_card *card, struct sc_apdu *apdu, size_t olen)
422 {
423 	struct sc_context *ctx  = card->ctx;
424 	size_t le, minlen, buflen;
425 	unsigned char *buf;
426 	int rv;
427 
428 	LOG_FUNC_CALLED(ctx);
429 	if (apdu->le == 0) {
430 		/* no data is requested => change return value to 0x9000 and ignore the remaining data */
431 		apdu->sw1 = 0x90;
432 		apdu->sw2 = 0x00;
433 		return SC_SUCCESS;
434 	}
435 
436 	/* this should _never_ happen */
437 	if (!card->ops->get_response)
438 		LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "no GET RESPONSE command");
439 
440 	/* call GET RESPONSE until we have read all data requested or until the card returns 0x9000,
441 	 * whatever happens first. */
442 
443 	/* if there are already data in response append a new data to the end of the buffer */
444 	buf = apdu->resp + apdu->resplen;
445 
446 	/* read as much data as fits in apdu->resp (i.e. min(apdu->resplen, amount of data available)). */
447 	buflen = olen - apdu->resplen;
448 
449 	/* 0x6100 means at least 256 more bytes to read */
450 	le = apdu->sw2 != 0 ? (size_t)apdu->sw2 : 256;
451 	/* we try to read at least as much as bytes as promised in the response bytes */
452 	minlen = le;
453 
454 	do {
455 		unsigned char resp[256];
456 		size_t resp_len = le;
457 
458 		/* call GET RESPONSE to get more date from the card;
459 		 * note: GET RESPONSE returns the left amount of data (== SW2) */
460 		memset(resp, 0, sizeof(resp));
461 		rv = card->ops->get_response(card, &resp_len, resp);
462 		if (rv < 0)   {
463 #ifdef ENABLE_SM
464 			if (resp_len)   {
465 				sc_log_hex(ctx, "SM response data", resp, resp_len);
466 				sc_sm_update_apdu_response(card, resp, resp_len, rv, apdu);
467 			}
468 #endif
469 			LOG_TEST_RET(ctx, rv, "GET RESPONSE error");
470 		}
471 
472 		le = resp_len;
473 		/* copy as much as will fit in requested buffer */
474 		if (buflen < le)
475 			le = buflen;
476 
477 		memcpy(buf, resp, le);
478 		buf    += le;
479 		buflen -= le;
480 
481 		/* we have all the data the caller requested even if the card has more data */
482 		if (buflen == 0)
483 			break;
484 
485 		minlen -= le;
486 		if (rv != 0)
487 			le = minlen = (size_t)rv;
488 		else
489 			/* if the card has returned 0x9000 but we still expect data ask for more
490 			 * until we have read enough bytes */
491 			le = minlen;
492 	} while (rv != 0 && minlen != 0);
493 
494 	/* we've read all data, let's return 0x9000 */
495 	apdu->resplen = buf - apdu->resp;
496 	apdu->sw1 = 0x90;
497 	apdu->sw2 = 0x00;
498 
499 	LOG_FUNC_RETURN(ctx, SC_SUCCESS);
500 }
501 
502 
503 /** Sends a single APDU to the card reader and calls GET RESPONSE to get the return data if necessary.
504  *  @param  card  sc_card_t object for the smartcard
505  *  @param  apdu  APDU to be sent
506  *  @return SC_SUCCESS on success and an error value otherwise
507  */
508 static int
sc_transmit(sc_card_t * card,sc_apdu_t * apdu)509 sc_transmit(sc_card_t *card, sc_apdu_t *apdu)
510 {
511 	struct sc_context *ctx  = card->ctx;
512 	size_t       olen  = apdu->resplen;
513 	int          r;
514 
515 	LOG_FUNC_CALLED(ctx);
516 
517 	r = sc_single_transmit(card, apdu);
518 	LOG_TEST_RET(ctx, r, "transmit APDU failed");
519 
520 	/* ok, the APDU was successfully transmitted. Now we have two special cases:
521 	 * 1. the card returned 0x6Cxx: in this case APDU will be re-transmitted with Le set to SW2
522 	 * (possible only if response buffer size is larger than new Le = SW2)
523 	 */
524 	if (apdu->sw1 == 0x6C && (apdu->flags & SC_APDU_FLAGS_NO_RETRY_WL) == 0)
525 		r = sc_set_le_and_transmit(card, apdu, olen);
526 	LOG_TEST_RET(ctx, r, "cannot re-transmit APDU ");
527 
528 	/* 2. the card returned 0x61xx: more data can be read from the card
529 	 *    using the GET RESPONSE command (mostly used in the T0 protocol).
530 	 *    Unless the SC_APDU_FLAGS_NO_GET_RESP is set we try to read as
531 	 *    much data as possible using GET RESPONSE.
532 	 */
533 	if (apdu->sw1 == 0x61 && (apdu->flags & SC_APDU_FLAGS_NO_GET_RESP) == 0)
534 		r = sc_get_response(card, apdu, olen);
535 	LOG_TEST_RET(ctx, r, "cannot get all data with 'GET RESPONSE'");
536 
537 	LOG_FUNC_RETURN(ctx, SC_SUCCESS);
538 }
539 
540 
sc_transmit_apdu(sc_card_t * card,sc_apdu_t * apdu)541 int sc_transmit_apdu(sc_card_t *card, sc_apdu_t *apdu)
542 {
543 	int r = SC_SUCCESS;
544 
545 	if (card == NULL || apdu == NULL)
546 		return SC_ERROR_INVALID_ARGUMENTS;
547 
548 	LOG_FUNC_CALLED(card->ctx);
549 
550 	/* determine the APDU type if necessary, i.e. to use
551 	 * short or extended APDUs  */
552 	sc_detect_apdu_cse(card, apdu);
553 	/* basic APDU consistency check */
554 	r = sc_check_apdu(card, apdu);
555 	if (r != SC_SUCCESS)
556 		return SC_ERROR_INVALID_ARGUMENTS;
557 
558 	r = sc_lock(card);	/* acquire card lock*/
559 	if (r != SC_SUCCESS) {
560 		sc_log(card->ctx, "unable to acquire lock");
561 		return r;
562 	}
563 
564 	if ((apdu->flags & SC_APDU_FLAGS_CHAINING) != 0) {
565 		/* divide et impera: transmit APDU in chunks with Lc <= max_send_size
566 		 * bytes using command chaining */
567 		size_t    len  = apdu->datalen;
568 		const u8  *buf = apdu->data;
569 		size_t    max_send_size = sc_get_max_send_size(card);
570 
571 		while (len != 0) {
572 			size_t    plen;
573 			sc_apdu_t tapdu;
574 			int       last = 0;
575 
576 			tapdu = *apdu;
577 			/* clear chaining flag */
578 			tapdu.flags &= ~SC_APDU_FLAGS_CHAINING;
579 			if (len > max_send_size) {
580 				/* adjust APDU case: in case of CASE 4 APDU
581 				 * the intermediate APDU are of CASE 3 */
582 				if ((tapdu.cse & SC_APDU_SHORT_MASK) == SC_APDU_CASE_4_SHORT)
583 					tapdu.cse--;
584 				/* XXX: the chunk size must be adjusted when
585 				 *      secure messaging is used */
586 				plen          = max_send_size;
587 				tapdu.cla    |= 0x10;
588 				tapdu.le      = 0;
589 				/* the intermediate APDU don't expect data */
590 				tapdu.lc      = 0;
591 				tapdu.resplen = 0;
592 				tapdu.resp    = NULL;
593 			} else {
594 				plen = len;
595 				last = 1;
596 			}
597 			tapdu.data    = buf;
598 			tapdu.datalen = tapdu.lc = plen;
599 
600 			r = sc_check_apdu(card, &tapdu);
601 			if (r != SC_SUCCESS) {
602 				sc_log(card->ctx, "inconsistent APDU while chaining");
603 				break;
604 			}
605 
606 			r = sc_transmit(card, &tapdu);
607 			if (r != SC_SUCCESS)
608 				break;
609 			if (last != 0) {
610 				/* in case of the last APDU set the SW1
611 				 * and SW2 bytes in the original APDU */
612 				apdu->sw1 = tapdu.sw1;
613 				apdu->sw2 = tapdu.sw2;
614 				apdu->resplen = tapdu.resplen;
615 			} else {
616 				/* otherwise check the status bytes */
617 				r = sc_check_sw(card, tapdu.sw1, tapdu.sw2);
618 				if (r != SC_SUCCESS)
619 					break;
620 			}
621 			len -= plen;
622 			buf += plen;
623 		}
624 	} else {
625 		/* transmit single APDU */
626 		r = sc_transmit(card, apdu);
627 	}
628 
629 	if (r == SC_ERROR_CARD_RESET || r == SC_ERROR_READER_REATTACHED) {
630 		sc_invalidate_cache(card);
631 		/* give card driver a chance to react on resets */
632 		if (card->ops->card_reader_lock_obtained)
633 			card->ops->card_reader_lock_obtained(card, 1);
634 	}
635 
636 	/* all done => release lock */
637 	if (sc_unlock(card) != SC_SUCCESS)
638 		sc_log(card->ctx, "sc_unlock failed");
639 
640 	return r;
641 }
642 
643 
644 int
sc_bytes2apdu(sc_context_t * ctx,const u8 * buf,size_t len,sc_apdu_t * apdu)645 sc_bytes2apdu(sc_context_t *ctx, const u8 *buf, size_t len, sc_apdu_t *apdu)
646 {
647 	const unsigned char *p;
648 	size_t len0;
649 
650 	if (!buf || !apdu)
651 		return SC_ERROR_INVALID_ARGUMENTS;
652 
653 	len0 = len;
654 	if (len < 4) {
655 		sc_log(ctx, "APDU too short (must be at least 4 bytes)");
656 		return SC_ERROR_INVALID_DATA;
657 	}
658 
659 	memset(apdu, 0, sizeof *apdu);
660 	p = buf;
661 	apdu->cla = *p++;
662 	apdu->ins = *p++;
663 	apdu->p1 = *p++;
664 	apdu->p2 = *p++;
665 	len -= 4;
666 
667 	if (!len) {
668 		apdu->cse = SC_APDU_CASE_1;
669 		sc_log(ctx,
670 		       "CASE_1 APDU: %"SC_FORMAT_LEN_SIZE_T"u bytes:\tins=%02x p1=%02x p2=%02x lc=%04"SC_FORMAT_LEN_SIZE_T"x le=%04"SC_FORMAT_LEN_SIZE_T"x",
671 		       len0, apdu->ins, apdu->p1, apdu->p2, apdu->lc, apdu->le);
672 		return SC_SUCCESS;
673 	}
674 
675 	if (*p == 0 && len >= 3) {
676 		/* ...must be an extended APDU */
677 		p++;
678 		if (len == 3) {
679 			apdu->le = (*p++)<<8;
680 			apdu->le += *p++;
681 			if (apdu->le == 0)
682 				apdu->le = 0xffff+1;
683 			len -= 3;
684 			apdu->cse = SC_APDU_CASE_2_EXT;
685 		}
686 		else {
687 			/* len > 3 */
688 			apdu->lc = (*p++)<<8;
689 			apdu->lc += *p++;
690 			len -= 3;
691 			if (len < apdu->lc) {
692 				sc_log(ctx,
693 				       "APDU too short (need %"SC_FORMAT_LEN_SIZE_T"u more bytes)",
694 				       apdu->lc - len);
695 				return SC_ERROR_INVALID_DATA;
696 			}
697 			apdu->data = p;
698 			apdu->datalen = apdu->lc;
699 			len -= apdu->lc;
700 			p += apdu->lc;
701 			if (!len) {
702 				apdu->cse = SC_APDU_CASE_3_EXT;
703 			}
704 			else {
705 				/* at this point the apdu has a Lc, so Le is on 2 bytes */
706 				if (len < 2) {
707 					sc_debug(ctx, SC_LOG_DEBUG_VERBOSE, "APDU too short (need 2 more bytes)\n");
708 					return SC_ERROR_INVALID_DATA;
709 				}
710 				apdu->le = (*p++)<<8;
711 				apdu->le += *p++;
712 				if (apdu->le == 0)
713 					apdu->le = 0xffff+1;
714 				len -= 2;
715 				apdu->cse = SC_APDU_CASE_4_EXT;
716 			}
717 		}
718 	}
719 	else {
720 		/* ...must be a short APDU */
721 		if (len == 1) {
722 			apdu->le = *p++;
723 			if (apdu->le == 0)
724 				apdu->le = 0xff+1;
725 			len--;
726 			apdu->cse = SC_APDU_CASE_2_SHORT;
727 		}
728 		else {
729 			apdu->lc = *p++;
730 			len--;
731 			if (len < apdu->lc) {
732 				sc_log(ctx,
733 				       "APDU too short (need %"SC_FORMAT_LEN_SIZE_T"u more bytes)",
734 				       apdu->lc - len);
735 				return SC_ERROR_INVALID_DATA;
736 			}
737 			apdu->data = p;
738 			apdu->datalen = apdu->lc;
739 			len -= apdu->lc;
740 			p += apdu->lc;
741 			if (!len) {
742 				apdu->cse = SC_APDU_CASE_3_SHORT;
743 			}
744 			else {
745 				apdu->le = *p++;
746 				if (apdu->le == 0)
747 					apdu->le = 0xff+1;
748 				len--;
749 				apdu->cse = SC_APDU_CASE_4_SHORT;
750 			}
751 		}
752 	}
753 	if (len) {
754 		sc_log(ctx, "APDU too long (%lu bytes extra)",(unsigned long) len);
755 		return SC_ERROR_INVALID_DATA;
756 	}
757 
758 	sc_log(ctx,
759 	       "Case %d %s APDU, %"SC_FORMAT_LEN_SIZE_T"u bytes:\tins=%02x p1=%02x p2=%02x lc=%04"SC_FORMAT_LEN_SIZE_T"x le=%04"SC_FORMAT_LEN_SIZE_T"x",
760 	       apdu->cse & SC_APDU_SHORT_MASK,
761 	       (apdu->cse & SC_APDU_EXT) != 0 ? "extended" : "short",
762 	       len0, apdu->ins, apdu->p1, apdu->p2, apdu->lc,
763 	       apdu->le);
764 
765 	return SC_SUCCESS;
766 }
767