Coverage Report

Created: 2026-10-28 06:53

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