1 /* ccid-driver.c - USB ChipCardInterfaceDevices driver
2 * Copyright (C) 2003, 2004, 2005, 2006, 2007
3 * 2008, 2009, 2013 Free Software Foundation, Inc.
4 * Written by Werner Koch.
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <https://www.gnu.org/licenses/>.
21 * ALTERNATIVELY, this file may be distributed under the terms of the
22 * following license, in which case the provisions of this license are
23 * required INSTEAD OF the GNU General Public License. If you wish to
24 * allow use of your version of this file only under the terms of the
25 * GNU General Public License, and not to allow others to use your
26 * version of this file under the terms of the following license,
27 * indicate your decision by deleting this paragraph and the license
30 * Redistribution and use in source and binary forms, with or without
31 * modification, are permitted provided that the following conditions
33 * 1. Redistributions of source code must retain the above copyright
34 * notice, and the entire permission notice in its entirety,
35 * including the disclaimer of warranties.
36 * 2. Redistributions in binary form must reproduce the above copyright
37 * notice, this list of conditions and the following disclaimer in the
38 * documentation and/or other materials provided with the distribution.
39 * 3. The name of the author may not be used to endorse or promote
40 * products derived from this software without specific prior
43 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
44 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
45 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
46 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
47 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
48 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
49 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
51 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
52 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
53 * OF THE POSSIBILITY OF SUCH DAMAGE.
57 /* CCID (ChipCardInterfaceDevices) is a specification for accessing
58 smartcard via a reader connected to the USB.
60 This is a limited driver allowing to use some CCID drivers directly
61 without any other specila drivers. This is a fallback driver to be
62 used when nothing else works or the system should be kept minimal
63 for security reasons. It makes use of the libusb library to gain
64 portable access to USB.
66 This driver has been tested with the SCM SCR335 and SPR532
67 smartcard readers and requires that a reader implements APDU or
68 TPDU level exchange and does fully automatic initialization.
75 #if defined(HAVE_LIBUSB) || defined(TEST)
82 #include <sys/types.h>
95 #define CCID_DRIVER_INCLUDE_USB_IDS 1
96 #include "ccid-driver.h"
98 #define DRVNAME "ccid-driver: "
100 /* Max length of buffer with out CCID message header of 10-byte
101 Sending: 547 for RSA-4096 key import
102 APDU size = 540 (24+4+256+256)
103 commnd + lc + le = 4 + 3 + 0
104 Sending: write data object of cardholder certificate
106 commnd + lc + le = 4 + 3 + 0
107 Receiving: 2048 for cardholder certificate
109 #define CCID_MAX_BUF (2048+7+10)
111 /* CCID command timeout. OpenPGPcard v2.1 requires timeout of 13 seconds. */
112 #define CCID_CMD_TIMEOUT (13*1000)
114 /* Depending on how this source is used we either define our error
115 output to go to stderr or to the GnuPG based logging functions. We
116 use the latter when GNUPG_MAJOR_VERSION or GNUPG_SCD_MAIN_HEADER
118 #if defined(GNUPG_MAJOR_VERSION) || defined(GNUPG_SCD_MAIN_HEADER)
120 #if defined(GNUPG_SCD_MAIN_HEADER)
121 # include GNUPG_SCD_MAIN_HEADER
122 #elif GNUPG_MAJOR_VERSION == 1 /* GnuPG Version is < 1.9. */
123 # include "options.h"
126 # include "cardglue.h"
127 # else /* This is the modularized GnuPG 1.9 or later. */
128 # include "scdaemon.h"
132 # define DEBUGOUT(t) do { if (debug_level) \
133 log_debug (DRVNAME t); } while (0)
134 # define DEBUGOUT_1(t,a) do { if (debug_level) \
135 log_debug (DRVNAME t,(a)); } while (0)
136 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
137 log_debug (DRVNAME t,(a),(b)); } while (0)
138 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
139 log_debug (DRVNAME t,(a),(b),(c));} while (0)
140 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
141 log_debug (DRVNAME t,(a),(b),(c),(d));} while (0)
142 # define DEBUGOUT_CONT(t) do { if (debug_level) \
143 log_printf (t); } while (0)
144 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
145 log_printf (t,(a)); } while (0)
146 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
147 log_printf (t,(a),(b)); } while (0)
148 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
149 log_printf (t,(a),(b),(c)); } while (0)
150 # define DEBUGOUT_LF() do { if (debug_level) \
151 log_printf ("\n"); } while (0)
153 #else /* Other usage of this source - don't use gnupg specifics. */
155 # define DEBUGOUT(t) do { if (debug_level) \
156 fprintf (stderr, DRVNAME t); } while (0)
157 # define DEBUGOUT_1(t,a) do { if (debug_level) \
158 fprintf (stderr, DRVNAME t, (a)); } while (0)
159 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
160 fprintf (stderr, DRVNAME t, (a), (b)); } while (0)
161 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
162 fprintf (stderr, DRVNAME t, (a), (b), (c)); } while (0)
163 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
164 fprintf (stderr, DRVNAME t, (a), (b), (c), (d));} while(0)
165 # define DEBUGOUT_CONT(t) do { if (debug_level) \
166 fprintf (stderr, t); } while (0)
167 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
168 fprintf (stderr, t, (a)); } while (0)
169 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
170 fprintf (stderr, t, (a), (b)); } while (0)
171 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
172 fprintf (stderr, t, (a), (b), (c)); } while (0)
173 # define DEBUGOUT_LF() do { if (debug_level) \
174 putc ('\n', stderr); } while (0)
176 #endif /* This source not used by scdaemon. */
180 #define EAGAIN EWOULDBLOCK
186 RDR_to_PC_NotifySlotChange= 0x50,
187 RDR_to_PC_HardwareError = 0x51,
189 PC_to_RDR_SetParameters = 0x61,
190 PC_to_RDR_IccPowerOn = 0x62,
191 PC_to_RDR_IccPowerOff = 0x63,
192 PC_to_RDR_GetSlotStatus = 0x65,
193 PC_to_RDR_Secure = 0x69,
194 PC_to_RDR_T0APDU = 0x6a,
195 PC_to_RDR_Escape = 0x6b,
196 PC_to_RDR_GetParameters = 0x6c,
197 PC_to_RDR_ResetParameters = 0x6d,
198 PC_to_RDR_IccClock = 0x6e,
199 PC_to_RDR_XfrBlock = 0x6f,
200 PC_to_RDR_Mechanical = 0x71,
201 PC_to_RDR_Abort = 0x72,
202 PC_to_RDR_SetDataRate = 0x73,
204 RDR_to_PC_DataBlock = 0x80,
205 RDR_to_PC_SlotStatus = 0x81,
206 RDR_to_PC_Parameters = 0x82,
207 RDR_to_PC_Escape = 0x83,
208 RDR_to_PC_DataRate = 0x84
212 /* Two macro to detect whether a CCID command has failed and to get
213 the error code. These macros assume that we can access the
214 mandatory first 10 bytes of a CCID message in BUF. */
215 #define CCID_COMMAND_FAILED(buf) ((buf)[7] & 0x40)
216 #define CCID_ERROR_CODE(buf) (((unsigned char *)(buf))[8])
219 /* A list and a table with special transport descriptions. */
221 TRANSPORT_USB = 0, /* Standard USB transport. */
222 TRANSPORT_CM4040 = 1 /* As used by the Cardman 4040. */
227 char *name; /* Device name. */
231 { "/dev/cmx0", TRANSPORT_CM4040 },
232 { "/dev/cmx1", TRANSPORT_CM4040 },
237 /* Store information on the driver's state. A pointer to such a
238 structure is used as handle for most functions. */
241 libusb_device_handle *idev;
243 int dev_fd; /* -1 for USB transport or file descriptor of the
245 unsigned short id_vendor;
246 unsigned short id_product;
247 unsigned short bcd_device;
255 unsigned char nonnull_nad;
259 unsigned char apdu_level:2; /* Reader supports short APDU level
260 exchange. With a value of 2 short
261 and extended level is supported.*/
262 unsigned int auto_voltage:1;
263 unsigned int auto_param:1;
264 unsigned int auto_pps:1;
265 unsigned int auto_ifsd:1;
266 unsigned int powered_off:1;
267 unsigned int has_pinpad:2;
268 unsigned int enodev_seen:1;
270 time_t last_progress; /* Last time we sent progress line. */
272 /* The progress callback and its first arg as supplied to
273 ccid_set_progress_cb. */
274 void (*progress_cb)(void *, const char *, int, int, int);
275 void *progress_cb_arg;
279 static int initialized_usb; /* Tracks whether USB has been initialized. */
280 static int debug_level; /* Flag to control the debug output.
283 2 = Level 1 + T=1 protocol tracing
284 3 = Level 2 + USB/I/O tracing of SlotStatus.
288 static unsigned int compute_edc (const unsigned char *data, size_t datalen,
290 static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
292 static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
293 size_t *nread, int expected_type, int seqno, int timeout,
295 static int abort_cmd (ccid_driver_t handle, int seqno);
296 static int send_escape_cmd (ccid_driver_t handle, const unsigned char *data,
297 size_t datalen, unsigned char *result,
298 size_t resultmax, size_t *resultlen);
300 /* Convert a little endian stored 4 byte value into an unsigned
303 convert_le_u32 (const unsigned char *buf)
305 return buf[0] | (buf[1] << 8) | (buf[2] << 16) | ((unsigned int)buf[3] << 24);
309 /* Convert a little endian stored 2 byte value into an unsigned
312 convert_le_u16 (const unsigned char *buf)
314 return buf[0] | (buf[1] << 8);
318 set_msg_len (unsigned char *msg, unsigned int length)
321 msg[2] = length >> 8;
322 msg[3] = length >> 16;
323 msg[4] = length >> 24;
328 my_sleep (int seconds)
331 npth_sleep (seconds);
333 # ifdef HAVE_W32_SYSTEM
334 Sleep (seconds*1000);
342 print_progress (ccid_driver_t handle)
344 time_t ct = time (NULL);
346 /* We don't want to print progress lines too often. */
347 if (ct == handle->last_progress)
350 if (handle->progress_cb)
351 handle->progress_cb (handle->progress_cb_arg, "card_busy", 'w', 0, 0);
353 handle->last_progress = ct;
358 /* Pint an error message for a failed CCID command including a textual
359 error code. MSG shall be the CCID message at a minimum of 10 bytes. */
361 print_command_failed (const unsigned char *msg)
370 ec = CCID_ERROR_CODE (msg);
373 case 0x00: t = "Command not supported"; break;
375 case 0xE0: t = "Slot busy"; break;
376 case 0xEF: t = "PIN cancelled"; break;
377 case 0xF0: t = "PIN timeout"; break;
379 case 0xF2: t = "Automatic sequence ongoing"; break;
380 case 0xF3: t = "Deactivated Protocol"; break;
381 case 0xF4: t = "Procedure byte conflict"; break;
382 case 0xF5: t = "ICC class not supported"; break;
383 case 0xF6: t = "ICC protocol not supported"; break;
384 case 0xF7: t = "Bad checksum in ATR"; break;
385 case 0xF8: t = "Bad TS in ATR"; break;
387 case 0xFB: t = "An all inclusive hardware error occurred"; break;
388 case 0xFC: t = "Overrun error while talking to the ICC"; break;
389 case 0xFD: t = "Parity error while talking to the ICC"; break;
390 case 0xFE: t = "CCID timed out while talking to the ICC"; break;
391 case 0xFF: t = "Host aborted the current activity"; break;
394 if (ec > 0 && ec < 128)
395 sprintf (buffer, "Parameter error at offset %d", ec);
397 sprintf (buffer, "Error code %02X", ec);
401 DEBUGOUT_1 ("CCID command failed: %s\n", t);
406 print_pr_data (const unsigned char *data, size_t datalen, size_t off)
410 for (; off < datalen; off++)
412 if (!any || !(off % 16))
416 DEBUGOUT_1 (" [%04lu] ", (unsigned long) off);
418 DEBUGOUT_CONT_1 (" %02X", data[off]);
421 if (any && (off % 16))
427 print_p2r_header (const char *name, const unsigned char *msg, size_t msglen)
429 DEBUGOUT_1 ("%s:\n", name);
432 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
433 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
434 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
439 print_p2r_iccpoweron (const unsigned char *msg, size_t msglen)
441 print_p2r_header ("PC_to_RDR_IccPowerOn", msg, msglen);
444 DEBUGOUT_2 (" bPowerSelect ......: 0x%02x (%s)\n", msg[7],
446 msg[7] == 1? "5.0 V":
447 msg[7] == 2? "3.0 V":
448 msg[7] == 3? "1.8 V":"");
449 print_pr_data (msg, msglen, 8);
454 print_p2r_iccpoweroff (const unsigned char *msg, size_t msglen)
456 print_p2r_header ("PC_to_RDR_IccPowerOff", msg, msglen);
457 print_pr_data (msg, msglen, 7);
462 print_p2r_getslotstatus (const unsigned char *msg, size_t msglen)
464 print_p2r_header ("PC_to_RDR_GetSlotStatus", msg, msglen);
465 print_pr_data (msg, msglen, 7);
470 print_p2r_xfrblock (const unsigned char *msg, size_t msglen)
474 print_p2r_header ("PC_to_RDR_XfrBlock", msg, msglen);
477 DEBUGOUT_1 (" bBWI ..............: 0x%02x\n", msg[7]);
478 val = convert_le_u16 (msg+8);
479 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
480 val == 1? " (continued)":
481 val == 2? " (continues+ends)":
482 val == 3? " (continues+continued)":
483 val == 16? " (DataBlock-expected)":"");
484 print_pr_data (msg, msglen, 10);
489 print_p2r_getparameters (const unsigned char *msg, size_t msglen)
491 print_p2r_header ("PC_to_RDR_GetParameters", msg, msglen);
492 print_pr_data (msg, msglen, 7);
497 print_p2r_resetparameters (const unsigned char *msg, size_t msglen)
499 print_p2r_header ("PC_to_RDR_ResetParameters", msg, msglen);
500 print_pr_data (msg, msglen, 7);
505 print_p2r_setparameters (const unsigned char *msg, size_t msglen)
507 print_p2r_header ("PC_to_RDR_SetParameters", msg, msglen);
510 DEBUGOUT_1 (" bProtocolNum ......: 0x%02x\n", msg[7]);
511 print_pr_data (msg, msglen, 8);
516 print_p2r_escape (const unsigned char *msg, size_t msglen)
518 print_p2r_header ("PC_to_RDR_Escape", msg, msglen);
519 print_pr_data (msg, msglen, 7);
524 print_p2r_iccclock (const unsigned char *msg, size_t msglen)
526 print_p2r_header ("PC_to_RDR_IccClock", msg, msglen);
529 DEBUGOUT_1 (" bClockCommand .....: 0x%02x\n", msg[7]);
530 print_pr_data (msg, msglen, 8);
535 print_p2r_to0apdu (const unsigned char *msg, size_t msglen)
537 print_p2r_header ("PC_to_RDR_T0APDU", msg, msglen);
540 DEBUGOUT_1 (" bmChanges .........: 0x%02x\n", msg[7]);
541 DEBUGOUT_1 (" bClassGetResponse .: 0x%02x\n", msg[8]);
542 DEBUGOUT_1 (" bClassEnvelope ....: 0x%02x\n", msg[9]);
543 print_pr_data (msg, msglen, 10);
548 print_p2r_secure (const unsigned char *msg, size_t msglen)
552 print_p2r_header ("PC_to_RDR_Secure", msg, msglen);
555 DEBUGOUT_1 (" bBMI ..............: 0x%02x\n", msg[7]);
556 val = convert_le_u16 (msg+8);
557 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
558 val == 1? " (continued)":
559 val == 2? " (continues+ends)":
560 val == 3? " (continues+continued)":
561 val == 16? " (DataBlock-expected)":"");
562 print_pr_data (msg, msglen, 10);
567 print_p2r_mechanical (const unsigned char *msg, size_t msglen)
569 print_p2r_header ("PC_to_RDR_Mechanical", msg, msglen);
572 DEBUGOUT_1 (" bFunction .........: 0x%02x\n", msg[7]);
573 print_pr_data (msg, msglen, 8);
578 print_p2r_abort (const unsigned char *msg, size_t msglen)
580 print_p2r_header ("PC_to_RDR_Abort", msg, msglen);
581 print_pr_data (msg, msglen, 7);
586 print_p2r_setdatarate (const unsigned char *msg, size_t msglen)
588 print_p2r_header ("PC_to_RDR_SetDataRate", msg, msglen);
591 print_pr_data (msg, msglen, 7);
596 print_p2r_unknown (const unsigned char *msg, size_t msglen)
598 print_p2r_header ("Unknown PC_to_RDR command", msg, msglen);
601 print_pr_data (msg, msglen, 0);
606 print_r2p_header (const char *name, const unsigned char *msg, size_t msglen)
608 DEBUGOUT_1 ("%s:\n", name);
611 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
612 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
613 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
614 DEBUGOUT_1 (" bStatus ...........: %u\n", msg[7]);
616 DEBUGOUT_1 (" bError ............: %u\n", msg[8]);
621 print_r2p_datablock (const unsigned char *msg, size_t msglen)
623 print_r2p_header ("RDR_to_PC_DataBlock", msg, msglen);
627 DEBUGOUT_2 (" bChainParameter ...: 0x%02x%s\n", msg[9],
628 msg[9] == 1? " (continued)":
629 msg[9] == 2? " (continues+ends)":
630 msg[9] == 3? " (continues+continued)":
631 msg[9] == 16? " (XferBlock-expected)":"");
632 print_pr_data (msg, msglen, 10);
637 print_r2p_slotstatus (const unsigned char *msg, size_t msglen)
639 print_r2p_header ("RDR_to_PC_SlotStatus", msg, msglen);
642 DEBUGOUT_2 (" bClockStatus ......: 0x%02x%s\n", msg[9],
643 msg[9] == 0? " (running)":
644 msg[9] == 1? " (stopped-L)":
645 msg[9] == 2? " (stopped-H)":
646 msg[9] == 3? " (stopped)":"");
647 print_pr_data (msg, msglen, 10);
652 print_r2p_parameters (const unsigned char *msg, size_t msglen)
654 print_r2p_header ("RDR_to_PC_Parameters", msg, msglen);
658 DEBUGOUT_1 (" protocol ..........: T=%d\n", msg[9]);
659 if (msglen == 17 && msg[9] == 1)
662 DEBUGOUT_1 (" bmFindexDindex ....: %02X\n", msg[10]);
663 DEBUGOUT_1 (" bmTCCKST1 .........: %02X\n", msg[11]);
664 DEBUGOUT_1 (" bGuardTimeT1 ......: %02X\n", msg[12]);
665 DEBUGOUT_1 (" bmWaitingIntegersT1: %02X\n", msg[13]);
666 DEBUGOUT_1 (" bClockStop ........: %02X\n", msg[14]);
667 DEBUGOUT_1 (" bIFSC .............: %d\n", msg[15]);
668 DEBUGOUT_1 (" bNadValue .........: %d\n", msg[16]);
671 print_pr_data (msg, msglen, 10);
676 print_r2p_escape (const unsigned char *msg, size_t msglen)
678 print_r2p_header ("RDR_to_PC_Escape", msg, msglen);
681 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
682 print_pr_data (msg, msglen, 10);
687 print_r2p_datarate (const unsigned char *msg, size_t msglen)
689 print_r2p_header ("RDR_to_PC_DataRate", msg, msglen);
694 DEBUGOUT_1 (" dwClockFrequency ..: %u\n", convert_le_u32 (msg+10));
695 DEBUGOUT_1 (" dwDataRate ..... ..: %u\n", convert_le_u32 (msg+14));
696 print_pr_data (msg, msglen, 18);
699 print_pr_data (msg, msglen, 10);
704 print_r2p_unknown (const unsigned char *msg, size_t msglen)
706 print_r2p_header ("Unknown RDR_to_PC command", msg, msglen);
709 DEBUGOUT_1 (" bMessageType ......: %02X\n", msg[0]);
710 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
711 print_pr_data (msg, msglen, 10);
715 /* Given a handle used for special transport prepare it for use. In
716 particular setup all information in way that resembles what
717 parse_cccid_descriptor does. */
719 prepare_special_transport (ccid_driver_t handle)
721 assert (!handle->id_vendor);
723 handle->nonnull_nad = 0;
724 handle->auto_ifsd = 0;
725 handle->max_ifsd = 32;
726 handle->max_ccid_msglen = CCID_MAX_BUF;
727 handle->has_pinpad = 0;
728 handle->apdu_level = 0;
729 switch (handle->id_product)
731 case TRANSPORT_CM4040:
732 DEBUGOUT ("setting up transport for CardMan 4040\n");
733 handle->apdu_level = 1;
736 default: assert (!"transport not defined");
740 /* Parse a CCID descriptor, optionally print all available features
741 and test whether this reader is usable by this driver. Returns 0
744 Note, that this code is based on the one in lsusb.c of the
745 usb-utils package, I wrote on 2003-09-01. -wk. */
747 parse_ccid_descriptor (ccid_driver_t handle,
748 const unsigned char *buf, size_t buflen)
752 int have_t1 = 0, have_tpdu=0;
755 handle->nonnull_nad = 0;
756 handle->auto_ifsd = 0;
757 handle->max_ifsd = 32;
758 handle->has_pinpad = 0;
759 handle->apdu_level = 0;
760 handle->auto_voltage = 0;
761 handle->auto_param = 0;
762 handle->auto_pps = 0;
763 DEBUGOUT_3 ("idVendor: %04X idProduct: %04X bcdDevice: %04X\n",
764 handle->id_vendor, handle->id_product, handle->bcd_device);
765 if (buflen < 54 || buf[0] < 54)
767 DEBUGOUT ("CCID device descriptor is too short\n");
771 DEBUGOUT ("ChipCard Interface Descriptor:\n");
772 DEBUGOUT_1 (" bLength %5u\n", buf[0]);
773 DEBUGOUT_1 (" bDescriptorType %5u\n", buf[1]);
774 DEBUGOUT_2 (" bcdCCID %2x.%02x", buf[3], buf[2]);
775 if (buf[3] != 1 || buf[2] != 0)
776 DEBUGOUT_CONT(" (Warning: Only accurate for version 1.0)");
779 DEBUGOUT_1 (" nMaxSlotIndex %5u\n", buf[4]);
780 DEBUGOUT_2 (" bVoltageSupport %5u %s\n",
781 buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V"
782 : buf[5] == 3? "1.8V":"?"));
784 us = convert_le_u32 (buf+6);
785 DEBUGOUT_1 (" dwProtocols %5u ", us);
787 DEBUGOUT_CONT (" T=0");
790 DEBUGOUT_CONT (" T=1");
794 DEBUGOUT_CONT (" (Invalid values detected)");
797 us = convert_le_u32(buf+10);
798 DEBUGOUT_1 (" dwDefaultClock %5u\n", us);
799 us = convert_le_u32(buf+14);
800 DEBUGOUT_1 (" dwMaxiumumClock %5u\n", us);
801 DEBUGOUT_1 (" bNumClockSupported %5u\n", buf[18]);
802 us = convert_le_u32(buf+19);
803 DEBUGOUT_1 (" dwDataRate %7u bps\n", us);
804 us = convert_le_u32(buf+23);
805 DEBUGOUT_1 (" dwMaxDataRate %7u bps\n", us);
806 DEBUGOUT_1 (" bNumDataRatesSupp. %5u\n", buf[27]);
808 us = convert_le_u32(buf+28);
809 DEBUGOUT_1 (" dwMaxIFSD %5u\n", us);
810 handle->max_ifsd = us;
812 us = convert_le_u32(buf+32);
813 DEBUGOUT_1 (" dwSyncProtocols %08X ", us);
815 DEBUGOUT_CONT ( " 2-wire");
817 DEBUGOUT_CONT ( " 3-wire");
819 DEBUGOUT_CONT ( " I2C");
822 us = convert_le_u32(buf+36);
823 DEBUGOUT_1 (" dwMechanical %08X ", us);
825 DEBUGOUT_CONT (" accept");
827 DEBUGOUT_CONT (" eject");
829 DEBUGOUT_CONT (" capture");
831 DEBUGOUT_CONT (" lock");
834 us = convert_le_u32(buf+40);
835 DEBUGOUT_1 (" dwFeatures %08X\n", us);
838 DEBUGOUT (" Auto configuration based on ATR (assumes auto voltage)\n");
839 handle->auto_voltage = 1;
842 DEBUGOUT (" Auto activation on insert\n");
845 DEBUGOUT (" Auto voltage selection\n");
846 handle->auto_voltage = 1;
849 DEBUGOUT (" Auto clock change\n");
851 DEBUGOUT (" Auto baud rate change\n");
854 DEBUGOUT (" Auto parameter negotiation made by CCID\n");
855 handle->auto_param = 1;
857 else if ((us & 0x0080))
859 DEBUGOUT (" Auto PPS made by CCID\n");
860 handle->auto_pps = 1;
862 if ((us & (0x0040 | 0x0080)) == (0x0040 | 0x0080))
863 DEBUGOUT (" WARNING: conflicting negotiation features\n");
866 DEBUGOUT (" CCID can set ICC in clock stop mode\n");
869 DEBUGOUT (" NAD value other than 0x00 accepted\n");
870 handle->nonnull_nad = 1;
874 DEBUGOUT (" Auto IFSD exchange\n");
875 handle->auto_ifsd = 1;
878 if ((us & 0x00010000))
880 DEBUGOUT (" TPDU level exchange\n");
883 else if ((us & 0x00020000))
885 DEBUGOUT (" Short APDU level exchange\n");
886 handle->apdu_level = 1;
888 else if ((us & 0x00040000))
890 DEBUGOUT (" Short and extended APDU level exchange\n");
891 handle->apdu_level = 2;
893 else if ((us & 0x00070000))
894 DEBUGOUT (" WARNING: conflicting exchange levels\n");
896 us = convert_le_u32(buf+44);
897 DEBUGOUT_1 (" dwMaxCCIDMsgLen %5u\n", us);
898 handle->max_ccid_msglen = us;
900 DEBUGOUT ( " bClassGetResponse ");
902 DEBUGOUT_CONT ("echo\n");
904 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
906 DEBUGOUT ( " bClassEnvelope ");
908 DEBUGOUT_CONT ("echo\n");
910 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
912 DEBUGOUT ( " wlcdLayout ");
913 if (!buf[50] && !buf[51])
914 DEBUGOUT_CONT ("none\n");
916 DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]);
918 DEBUGOUT_1 (" bPINSupport %5u ", buf[52]);
921 DEBUGOUT_CONT ( " verification");
922 handle->has_pinpad |= 1;
926 DEBUGOUT_CONT ( " modification");
927 handle->has_pinpad |= 2;
931 DEBUGOUT_1 (" bMaxCCIDBusySlots %5u\n", buf[53]);
936 for (i=54; i < buf[0]-54; i++)
937 DEBUGOUT_CONT_1 (" %02X", buf[i]);
941 if (!have_t1 || !(have_tpdu || handle->apdu_level))
943 DEBUGOUT ("this drivers requires that the reader supports T=1, "
944 "TPDU or APDU level exchange - this is not available\n");
949 /* SCM drivers get stuck in their internal USB stack if they try to
950 send a frame of n*wMaxPacketSize back to us. Given that
951 wMaxPacketSize is 64 for these readers we set the IFSD to a value
953 64 - 10 CCID header - 4 T1frame - 2 reserved = 48
960 0x5117 - SCR 3320 USB ID-000 reader
961 seems to be very slow but enabling this workaround boosts the
962 performance to a a more or less acceptable level (tested by David).
965 if (handle->id_vendor == VENDOR_SCM
966 && handle->max_ifsd > 48
967 && ( (handle->id_product == SCM_SCR331 && handle->bcd_device < 0x0516)
968 ||(handle->id_product == SCM_SCR331DI && handle->bcd_device < 0x0620)
969 ||(handle->id_product == SCM_SCR335 && handle->bcd_device < 0x0514)
970 ||(handle->id_product == SCM_SPR532 && handle->bcd_device < 0x0504)
971 ||(handle->id_product == SCM_SCR3320 && handle->bcd_device < 0x0522)
974 DEBUGOUT ("enabling workaround for buggy SCM readers\n");
975 handle->max_ifsd = 48;
978 if (handle->id_vendor == VENDOR_GEMPC)
980 DEBUGOUT ("enabling product quirk: disable non-null NAD\n");
981 handle->nonnull_nad = 0;
989 get_escaped_usb_string (libusb_device_handle *idev, int idx,
990 const char *prefix, const char *suffix)
993 unsigned char buf[280];
1002 /* Fixme: The next line is for the current Valgrid without support
1004 memset (buf, 0, sizeof buf);
1006 /* First get the list of supported languages and use the first one.
1007 If we do don't find it we try to use English. Note that this is
1008 all in a 2 bute Unicode encoding using little endian. */
1009 rc = libusb_control_transfer (idev, LIBUSB_ENDPOINT_IN,
1010 LIBUSB_REQUEST_GET_DESCRIPTOR,
1011 (LIBUSB_DT_STRING << 8), 0,
1012 (char*)buf, sizeof buf, 1000 /* ms timeout */);
1014 langid = 0x0409; /* English. */
1016 langid = (buf[3] << 8) | buf[2];
1018 rc = libusb_control_transfer (idev, LIBUSB_ENDPOINT_IN,
1019 LIBUSB_REQUEST_GET_DESCRIPTOR,
1020 (LIBUSB_DT_STRING << 8) + idx, langid,
1021 (char*)buf, sizeof buf, 1000 /* ms timeout */);
1022 if (rc < 2 || buf[1] != LIBUSB_DT_STRING)
1023 return NULL; /* Error or not a string. */
1026 return NULL; /* Larger than our buffer. */
1028 for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2)
1031 n++; /* High byte set. */
1032 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
1038 result = malloc (strlen (prefix) + n + strlen (suffix) + 1);
1042 strcpy (result, prefix);
1043 n = strlen (prefix);
1044 for (s=buf+2, i=2; i+1 < len; i += 2, s += 2)
1047 result[n++] = '\xff'; /* High byte set. */
1048 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
1050 sprintf (result+n, "%%%02X", *s);
1056 strcpy (result+n, suffix);
1061 /* This function creates an reader id to be used to find the same
1062 physical reader after a reset. It returns an allocated and possibly
1063 percent escaped string or NULL if not enough memory is available. */
1065 make_reader_id (libusb_device_handle *idev,
1066 unsigned int vendor, unsigned int product,
1067 unsigned char serialno_index)
1072 sprintf (prefix, "%04X:%04X:", (vendor & 0xffff), (product & 0xffff));
1073 rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0");
1076 rid = malloc (strlen (prefix) + 3 + 1);
1079 strcpy (rid, prefix);
1080 strcat (rid, "X:0");
1086 /* Helper to find the endpoint from an interface descriptor. */
1088 find_endpoint (const struct libusb_interface_descriptor *ifcdesc, int mode)
1091 int want_bulk_in = 0;
1094 want_bulk_in = 0x80;
1095 for (no=0; no < ifcdesc->bNumEndpoints; no++)
1097 const struct libusb_endpoint_descriptor *ep = ifcdesc->endpoint + no;
1098 if (ep->bDescriptorType != LIBUSB_DT_ENDPOINT)
1101 && ((ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
1102 == LIBUSB_TRANSFER_TYPE_INTERRUPT)
1103 && (ep->bEndpointAddress & 0x80))
1104 return ep->bEndpointAddress;
1105 else if (((ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
1106 == LIBUSB_TRANSFER_TYPE_BULK)
1107 && (ep->bEndpointAddress & 0x80) == want_bulk_in)
1108 return ep->bEndpointAddress;
1115 /* Helper for scan_or_find_devices. This function returns true if a
1116 requested device has been found or the caller should stop scanning
1117 for other reasons. */
1119 scan_or_find_usb_device (int scan_mode,
1120 int *readerno, int *count, char **rid_list,
1121 const char *readerid,
1122 struct libusb_device *dev,
1124 struct libusb_device_descriptor *desc,
1125 libusb_device_handle **r_idev,
1126 unsigned char **ifcdesc_extra,
1127 size_t *ifcdesc_extra_len,
1128 int *interface_number,
1129 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr)
1134 const struct libusb_interface_descriptor *ifcdesc;
1136 libusb_device_handle *idev;
1139 err = libusb_get_device_descriptor (dev, desc);
1145 for (cfg_no=0; cfg_no < desc->bNumConfigurations; cfg_no++)
1147 struct libusb_config_descriptor *config;
1149 err = libusb_get_config_descriptor (dev, cfg_no, &config);
1152 if (err == LIBUSB_ERROR_NO_MEM)
1157 for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
1159 for (set_no=0; set_no < config->interface[ifc_no].num_altsetting;
1162 ifcdesc = (config->interface[ifc_no].altsetting + set_no);
1163 /* The second condition is for older SCM SPR 532 who did
1164 not know about the assigned CCID class. The third
1165 condition does the same for a Cherry SmartTerminal
1166 ST-2000. Instead of trying to interpret the strings
1167 we simply check the product ID. */
1168 if (ifcdesc && ifcdesc->extra
1169 && ((ifcdesc->bInterfaceClass == 11
1170 && ifcdesc->bInterfaceSubClass == 0
1171 && ifcdesc->bInterfaceProtocol == 0)
1172 || (ifcdesc->bInterfaceClass == 255
1173 && desc->idVendor == VENDOR_SCM
1174 && desc->idProduct == SCM_SPR532)
1175 || (ifcdesc->bInterfaceClass == 255
1176 && desc->idVendor == VENDOR_CHERRY
1177 && desc->idProduct == CHERRY_ST2000)))
1179 err = libusb_open (dev, &idev);
1182 DEBUGOUT_1 ("usb_open failed: %s\n",
1183 libusb_error_name (err));
1184 continue; /* with next setting. */
1187 rid = make_reader_id (idev,
1190 desc->iSerialNumber);
1197 /* We are collecting infos about all
1198 available CCID readers. Store them and
1200 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n",
1202 p = malloc ((*rid_list? strlen (*rid_list):0) + 1
1203 + strlen (rid) + 1);
1209 strcat (p, *rid_list);
1216 else /* Out of memory. */
1225 && !strcmp (readerid, rid)))
1227 /* We found the requested reader. */
1228 if (ifcdesc_extra && ifcdesc_extra_len)
1230 *ifcdesc_extra = malloc (ifcdesc
1232 if (!*ifcdesc_extra)
1234 libusb_close (idev);
1236 libusb_free_config_descriptor (config);
1237 return 1; /* Out of core. */
1239 memcpy (*ifcdesc_extra, ifcdesc->extra,
1240 ifcdesc->extra_length);
1241 *ifcdesc_extra_len = ifcdesc->extra_length;
1244 if (interface_number)
1245 *interface_number = (ifcdesc->bInterfaceNumber);
1248 *ep_bulk_out = find_endpoint (ifcdesc, 0);
1250 *ep_bulk_in = find_endpoint (ifcdesc, 1);
1252 *ep_intr = find_endpoint (ifcdesc, 2);
1263 libusb_free_config_descriptor (config);
1264 return 1; /* Found requested device. */
1268 /* This is not yet the reader we want.
1269 fixme: We should avoid the extra usb_open
1277 libusb_close (idev);
1279 libusb_free_config_descriptor (config);
1285 libusb_free_config_descriptor (config);
1291 /* Combination function to either scan all CCID devices or to find and
1292 open one specific device.
1294 The function returns 0 if a reader has been found or when a scan
1295 returned without error.
1297 With READERNO = -1 and READERID is NULL, scan mode is used and
1298 R_RID should be the address where to store the list of reader_ids
1299 we found. If on return this list is empty, no CCID device has been
1300 found; otherwise it points to an allocated linked list of reader
1301 IDs. Note that in this mode the function always returns NULL.
1303 With READERNO >= 0 or READERID is not NULL find mode is used. This
1304 uses the same algorithm as the scan mode but stops and returns at
1305 the entry number READERNO and return the handle for the the opened
1306 USB device. If R_RID is not NULL it will receive the reader ID of
1307 that device. If R_DEV is not NULL it will the device pointer of
1308 that device. If IFCDESC_EXTRA is NOT NULL it will receive a
1309 malloced copy of the interfaces "extra: data filed;
1310 IFCDESC_EXTRA_LEN receive the length of this field. If there is
1311 no reader with number READERNO or that reader is not usable by our
1312 implementation NULL will be returned. The caller must close a
1313 returned USB device handle and free (if not passed as NULL) the
1314 returned reader ID info as well as the IFCDESC_EXTRA. On error
1315 NULL will get stored at R_RID, R_DEV, IFCDESC_EXTRA and
1316 IFCDESC_EXTRA_LEN. With READERID being -1 the function stops if
1317 the READERID was found.
1319 If R_FD is not -1 on return the device is not using USB for
1320 transport but the device associated with that file descriptor. In
1321 this case INTERFACE will receive the transport type and the other
1322 USB specific return values are not used; the return value is
1325 Note that the first entry of the returned reader ID list in scan mode
1326 corresponds with a READERNO of 0 in find mode.
1329 scan_or_find_devices (int readerno, const char *readerid,
1331 struct libusb_device_descriptor *r_desc,
1332 unsigned char **ifcdesc_extra,
1333 size_t *ifcdesc_extra_len,
1334 int *interface_number,
1335 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr,
1336 libusb_device_handle **r_idev,
1339 char *rid_list = NULL;
1341 libusb_device **dev_list = NULL;
1343 libusb_device_handle *idev = NULL;
1344 int scan_mode = (readerno == -1 && !readerid);
1347 struct libusb_device_descriptor desc;
1349 /* Set return values to a default. */
1353 *ifcdesc_extra = NULL;
1354 if (ifcdesc_extra_len)
1355 *ifcdesc_extra_len = 0;
1356 if (interface_number)
1357 *interface_number = 0;
1363 /* See whether we want scan or find mode. */
1369 n = libusb_get_device_list (NULL, &dev_list);
1371 for (i = 0; i < n; i++)
1374 if (scan_or_find_usb_device (scan_mode, &readerno, &count, &rid_list,
1383 ep_bulk_out, ep_bulk_in, ep_intr))
1385 libusb_free_device_list (dev_list, 1);
1386 /* Found requested device or out of core. */
1390 return -1; /* error */
1394 memcpy (r_desc, &desc, sizeof (struct libusb_device_descriptor));
1399 libusb_free_device_list (dev_list, 1);
1401 /* Now check whether there are any devices with special transport types. */
1402 for (i=0; transports[i].name; i++)
1407 fd = open (transports[i].name, O_RDWR);
1408 if (fd == -1 && scan_mode && errno == EBUSY)
1410 /* Ignore this error in scan mode because it indicates that
1411 the device exists but is already open (most likely by us)
1412 and thus in general suitable as a reader. */
1416 DEBUGOUT_2 ("failed to open '%s': %s\n",
1417 transports[i].name, strerror (errno));
1421 rid = malloc (strlen (transports[i].name) + 30 + 10);
1427 return -1; /* Error. */
1429 sprintf (rid, "0000:%04X:%s:0", transports[i].type, transports[i].name);
1432 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n", count, rid);
1433 p = malloc ((rid_list? strlen (rid_list):0) + 1 + strlen (rid) + 1);
1440 return -1; /* Error. */
1445 strcat (p, rid_list);
1453 else if (!readerno ||
1454 (readerno < 0 && readerid && !strcmp (readerid, rid)))
1456 /* Found requested device. */
1457 if (interface_number)
1458 *interface_number = transports[i].type;
1465 return 0; /* Okay, found device */
1467 else /* This is not yet the reader we want. */
1487 /* Set the level of debugging to LEVEL and return the old level. -1
1488 just returns the old level. A level of 0 disables debugging, 1
1489 enables debugging, 2 enables additional tracing of the T=1
1490 protocol, 3 additionally enables debugging for GetSlotStatus, other
1491 values are not yet defined.
1493 Note that libusb may provide its own debugging feature which is
1494 enabled by setting the envvar USB_DEBUG. */
1496 ccid_set_debug_level (int level)
1498 int old = debug_level;
1500 debug_level = level;
1506 ccid_get_reader_list (void)
1510 if (!initialized_usb)
1513 initialized_usb = 1;
1516 if (scan_or_find_devices (-1, NULL, &reader_list, NULL, NULL, NULL, NULL,
1517 NULL, NULL, NULL, NULL, NULL))
1518 return NULL; /* Error. */
1523 /* Vendor specific custom initialization. */
1525 ccid_vendor_specific_init (ccid_driver_t handle)
1527 if (handle->id_vendor == VENDOR_VEGA && handle->id_product == VEGA_ALPHA)
1531 * Vega alpha has a feature to show retry counter on the pinpad
1532 * display. But it assumes that the card returns the value of
1533 * retry counter by VERIFY with empty data (return code of
1534 * 63Cx). Unfortunately, existing OpenPGP cards don't support
1535 * VERIFY command with empty data. This vendor specific command
1536 * sequence is to disable the feature.
1538 const unsigned char cmd[] = { '\xb5', '\x01', '\x00', '\x03', '\x00' };
1540 r = send_escape_cmd (handle, cmd, sizeof (cmd), NULL, 0, NULL);
1541 if (r != 0 && r != CCID_DRIVER_ERR_CARD_INACTIVE
1542 && r != CCID_DRIVER_ERR_NO_CARD)
1550 /* Open the reader with the internal number READERNO and return a
1551 pointer to be used as handle in HANDLE. Returns 0 on success. */
1553 ccid_open_reader (ccid_driver_t *handle, const char *readerid,
1554 const char **rdrname_p)
1557 libusb_device_handle *idev = NULL;
1560 unsigned char *ifcdesc_extra = NULL;
1561 size_t ifcdesc_extra_len;
1563 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1564 struct libusb_device_descriptor desc;
1568 if (!initialized_usb)
1571 initialized_usb = 1;
1574 /* See whether we want to use the reader ID string or a reader
1575 number. A readerno of -1 indicates that the reader ID string is
1577 if (readerid && strchr (readerid, ':'))
1578 readerno = -1; /* We want to use the readerid. */
1581 readerno = atoi (readerid);
1584 DEBUGOUT ("no CCID readers found\n");
1585 rc = CCID_DRIVER_ERR_NO_READER;
1590 readerno = 0; /* Default. */
1592 if (scan_or_find_devices (readerno, readerid, &rid, &desc,
1593 &ifcdesc_extra, &ifcdesc_extra_len,
1594 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1598 DEBUGOUT_1 ("no CCID reader with ID %s\n", readerid );
1600 DEBUGOUT_1 ("no CCID reader with number %d\n", readerno );
1601 rc = CCID_DRIVER_ERR_NO_READER;
1605 /* Okay, this is a CCID reader. */
1606 *handle = calloc (1, sizeof **handle);
1609 DEBUGOUT ("out of memory\n");
1610 rc = CCID_DRIVER_ERR_OUT_OF_CORE;
1613 (*handle)->rid = rid;
1614 if (idev) /* Regular USB transport. */
1616 (*handle)->idev = idev;
1617 (*handle)->dev_fd = -1;
1618 (*handle)->id_vendor = desc.idVendor;
1619 (*handle)->id_product = desc.idProduct;
1620 (*handle)->bcd_device = desc.bcdDevice;
1621 (*handle)->ifc_no = ifc_no;
1622 (*handle)->ep_bulk_out = ep_bulk_out;
1623 (*handle)->ep_bulk_in = ep_bulk_in;
1624 (*handle)->ep_intr = ep_intr;
1626 else if (dev_fd != -1) /* Device transport. */
1628 (*handle)->idev = NULL;
1629 (*handle)->dev_fd = dev_fd;
1630 (*handle)->id_vendor = 0; /* Magic vendor for special transport. */
1631 (*handle)->id_product = ifc_no; /* Transport type */
1632 prepare_special_transport (*handle);
1636 assert (!"no transport"); /* Bug. */
1639 DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n", readerno, rid );
1643 if (parse_ccid_descriptor (*handle, ifcdesc_extra, ifcdesc_extra_len))
1645 DEBUGOUT ("device not supported\n");
1646 rc = CCID_DRIVER_ERR_NO_READER;
1650 rc = libusb_claim_interface (idev, ifc_no);
1653 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1654 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1659 rc = ccid_vendor_specific_init (*handle);
1662 free (ifcdesc_extra);
1667 libusb_close (idev);
1675 *rdrname_p = (*handle)->rid;
1682 do_close_reader (ccid_driver_t handle)
1685 unsigned char msg[100];
1687 unsigned char seqno;
1689 if (!handle->powered_off)
1691 msg[0] = PC_to_RDR_IccPowerOff;
1692 msg[5] = 0; /* slot */
1693 msg[6] = seqno = handle->seqno++;
1694 msg[7] = 0; /* RFU */
1695 msg[8] = 0; /* RFU */
1696 msg[9] = 0; /* RFU */
1697 set_msg_len (msg, 0);
1700 rc = bulk_out (handle, msg, msglen, 0);
1702 bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1704 handle->powered_off = 1;
1708 libusb_release_interface (handle->idev, handle->ifc_no);
1709 libusb_close (handle->idev);
1710 handle->idev = NULL;
1712 if (handle->dev_fd != -1)
1714 close (handle->dev_fd);
1715 handle->dev_fd = -1;
1721 ccid_set_progress_cb (ccid_driver_t handle,
1722 void (*cb)(void *, const char *, int, int, int),
1725 if (!handle || !handle->rid)
1726 return CCID_DRIVER_ERR_INV_VALUE;
1728 handle->progress_cb = cb;
1729 handle->progress_cb_arg = cb_arg;
1734 /* Close the reader HANDLE. */
1736 ccid_close_reader (ccid_driver_t handle)
1738 if (!handle || (!handle->idev && handle->dev_fd == -1))
1741 do_close_reader (handle);
1748 /* Return False if a card is present and powered. */
1750 ccid_check_card_presence (ccid_driver_t handle)
1752 (void)handle; /* Not yet implemented. */
1757 /* Write NBYTES of BUF to file descriptor FD. */
1759 writen (int fd, const void *buf, size_t nbytes)
1761 size_t nleft = nbytes;
1766 nwritten = write (fd, buf, nleft);
1775 buf = (const char*)buf + nwritten;
1782 /* Write a MSG of length MSGLEN to the designated bulk out endpoint.
1783 Returns 0 on success. */
1785 bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
1790 /* No need to continue and clutter the log with USB write error
1791 messages after we got the first ENODEV. */
1792 if (handle->enodev_seen)
1793 return CCID_DRIVER_ERR_NO_READER;
1795 if (debug_level && (!no_debug || debug_level >= 3))
1797 switch (msglen? msg[0]:0)
1799 case PC_to_RDR_IccPowerOn:
1800 print_p2r_iccpoweron (msg, msglen);
1802 case PC_to_RDR_IccPowerOff:
1803 print_p2r_iccpoweroff (msg, msglen);
1805 case PC_to_RDR_GetSlotStatus:
1806 print_p2r_getslotstatus (msg, msglen);
1808 case PC_to_RDR_XfrBlock:
1809 print_p2r_xfrblock (msg, msglen);
1811 case PC_to_RDR_GetParameters:
1812 print_p2r_getparameters (msg, msglen);
1814 case PC_to_RDR_ResetParameters:
1815 print_p2r_resetparameters (msg, msglen);
1817 case PC_to_RDR_SetParameters:
1818 print_p2r_setparameters (msg, msglen);
1820 case PC_to_RDR_Escape:
1821 print_p2r_escape (msg, msglen);
1823 case PC_to_RDR_IccClock:
1824 print_p2r_iccclock (msg, msglen);
1826 case PC_to_RDR_T0APDU:
1827 print_p2r_to0apdu (msg, msglen);
1829 case PC_to_RDR_Secure:
1830 print_p2r_secure (msg, msglen);
1832 case PC_to_RDR_Mechanical:
1833 print_p2r_mechanical (msg, msglen);
1835 case PC_to_RDR_Abort:
1836 print_p2r_abort (msg, msglen);
1838 case PC_to_RDR_SetDataRate:
1839 print_p2r_setdatarate (msg, msglen);
1842 print_p2r_unknown (msg, msglen);
1851 rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_out,
1852 (char*)msg, msglen, &transferred,
1853 5000 /* ms timeout */);
1854 if (rc == 0 && transferred == msglen)
1859 DEBUGOUT_1 ("usb_bulk_write error: %s\n", libusb_error_name (rc));
1860 if (rc == LIBUSB_ERROR_NO_DEVICE)
1862 handle->enodev_seen = 1;
1863 return CCID_DRIVER_ERR_NO_READER;
1869 rc = writen (handle->dev_fd, msg, msglen);
1872 DEBUGOUT_2 ("writen to %d failed: %s\n",
1873 handle->dev_fd, strerror (errno));
1876 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1880 /* Read a maximum of LENGTH bytes from the bulk in endpoint into
1881 BUFFER and return the actual read number if bytes in NREAD. SEQNO
1882 is the sequence number used to send the request and EXPECTED_TYPE
1883 the type of message we expect. Does checks on the ccid
1884 header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to
1885 avoid debug messages in case of no error; this can be overriden
1886 with a glibal debug level of at least 3. Returns 0 on success. */
1888 bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
1889 size_t *nread, int expected_type, int seqno, int timeout,
1894 int eagain_retries = 0;
1896 /* Fixme: The next line for the current Valgrind without support
1898 memset (buffer, 0, length);
1902 rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_in,
1903 (char*)buffer, length, &msglen, timeout);
1906 DEBUGOUT_1 ("usb_bulk_read error: %s\n", libusb_error_name (rc));
1907 if (rc == LIBUSB_ERROR_NO_DEVICE)
1909 handle->enodev_seen = 1;
1910 return CCID_DRIVER_ERR_NO_READER;
1913 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1916 return CCID_DRIVER_ERR_INV_VALUE; /* Faulty libusb. */
1921 rc = read (handle->dev_fd, buffer, length);
1925 DEBUGOUT_2 ("read from %d failed: %s\n",
1926 handle->dev_fd, strerror (rc));
1927 if (rc == EAGAIN && eagain_retries++ < 5)
1932 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1934 *nread = msglen = rc;
1940 DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen);
1941 abort_cmd (handle, seqno);
1942 return CCID_DRIVER_ERR_INV_VALUE;
1946 DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]);
1947 return CCID_DRIVER_ERR_INV_VALUE;
1949 if (buffer[6] != seqno)
1951 DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n",
1953 /* Retry until we are synced again. */
1957 /* We need to handle the time extension request before we check that
1958 we got the expected message type. This is in particular required
1959 for the Cherry keyboard which sends a time extension request for
1961 if ( !(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80)
1963 /* Card present and active, time extension requested. */
1964 DEBUGOUT_2 ("time extension requested (%02X,%02X)\n",
1965 buffer[7], buffer[8]);
1969 if (buffer[0] != expected_type)
1971 DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]);
1972 abort_cmd (handle, seqno);
1973 return CCID_DRIVER_ERR_INV_VALUE;
1976 if (debug_level && (!no_debug || debug_level >= 3))
1980 case RDR_to_PC_DataBlock:
1981 print_r2p_datablock (buffer, msglen);
1983 case RDR_to_PC_SlotStatus:
1984 print_r2p_slotstatus (buffer, msglen);
1986 case RDR_to_PC_Parameters:
1987 print_r2p_parameters (buffer, msglen);
1989 case RDR_to_PC_Escape:
1990 print_r2p_escape (buffer, msglen);
1992 case RDR_to_PC_DataRate:
1993 print_r2p_datarate (buffer, msglen);
1996 print_r2p_unknown (buffer, msglen);
2000 if (CCID_COMMAND_FAILED (buffer))
2001 print_command_failed (buffer);
2003 /* Check whether a card is at all available. Note: If you add new
2004 error codes here, check whether they need to be ignored in
2006 switch ((buffer[7] & 0x03))
2008 case 0: /* no error */ break;
2009 case 1: return CCID_DRIVER_ERR_CARD_INACTIVE;
2010 case 2: return CCID_DRIVER_ERR_NO_CARD;
2011 case 3: /* RFU */ break;
2018 /* Send an abort sequence and wait until everything settled. */
2020 abort_cmd (ccid_driver_t handle, int seqno)
2024 unsigned char msg[100];
2029 /* I don't know how to send an abort to non-USB devices. */
2030 rc = CCID_DRIVER_ERR_NOT_SUPPORTED;
2034 DEBUGOUT_1 ("sending abort sequence for seqno %d\n", seqno);
2035 /* Send the abort command to the control pipe. Note that we don't
2036 need to keep track of sent abort commands because there should
2037 never be another thread using the same slot concurrently. */
2038 rc = libusb_control_transfer (handle->idev,
2039 0x21,/* bmRequestType: host-to-device,
2040 class specific, to interface. */
2042 (seqno << 8 | 0 /* slot */),
2045 1000 /* ms timeout */);
2048 DEBUGOUT_1 ("usb_control_msg error: %s\n", libusb_error_name (rc));
2049 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2052 /* Now send the abort command to the bulk out pipe using the same
2053 SEQNO and SLOT. Do this in a loop to so that all seqno are
2055 seqno--; /* Adjust for next increment. */
2061 msg[0] = PC_to_RDR_Abort;
2062 msg[5] = 0; /* slot */
2064 msg[7] = 0; /* RFU */
2065 msg[8] = 0; /* RFU */
2066 msg[9] = 0; /* RFU */
2068 set_msg_len (msg, 0);
2070 rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_out,
2071 (char*)msg, msglen, &transferred,
2072 5000 /* ms timeout */);
2073 if (rc == 0 && transferred == msglen)
2076 DEBUGOUT_1 ("usb_bulk_write error in abort_cmd: %s\n",
2077 libusb_error_name (rc));
2082 rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_in,
2083 (char*)msg, sizeof msg, &msglen,
2084 5000 /*ms timeout*/);
2087 DEBUGOUT_1 ("usb_bulk_read error in abort_cmd: %s\n",
2088 libusb_error_name (rc));
2089 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2094 DEBUGOUT_1 ("bulk-in msg in abort_cmd too short (%u)\n",
2095 (unsigned int)msglen);
2096 return CCID_DRIVER_ERR_INV_VALUE;
2100 DEBUGOUT_1 ("unexpected bulk-in slot (%d) in abort_cmd\n", msg[5]);
2101 return CCID_DRIVER_ERR_INV_VALUE;
2104 DEBUGOUT_3 ("status: %02X error: %02X octet[9]: %02X\n",
2105 msg[7], msg[8], msg[9]);
2106 if (CCID_COMMAND_FAILED (msg))
2107 print_command_failed (msg);
2109 while (msg[0] != RDR_to_PC_SlotStatus && msg[5] != 0 && msg[6] != seqno);
2111 handle->seqno = ((seqno + 1) & 0xff);
2112 DEBUGOUT ("sending abort sequence succeeded\n");
2118 /* Note that this function won't return the error codes NO_CARD or
2119 CARD_INACTIVE. IF RESULT is not NULL, the result from the
2120 operation will get returned in RESULT and its length in RESULTLEN.
2121 If the response is larger than RESULTMAX, an error is returned and
2122 the required buffer length returned in RESULTLEN. */
2124 send_escape_cmd (ccid_driver_t handle,
2125 const unsigned char *data, size_t datalen,
2126 unsigned char *result, size_t resultmax, size_t *resultlen)
2129 unsigned char msg[100];
2131 unsigned char seqno;
2136 if (datalen > sizeof msg - 10)
2137 return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large. */
2139 msg[0] = PC_to_RDR_Escape;
2140 msg[5] = 0; /* slot */
2141 msg[6] = seqno = handle->seqno++;
2142 msg[7] = 0; /* RFU */
2143 msg[8] = 0; /* RFU */
2144 msg[9] = 0; /* RFU */
2145 memcpy (msg+10, data, datalen);
2146 msglen = 10 + datalen;
2147 set_msg_len (msg, datalen);
2149 rc = bulk_out (handle, msg, msglen, 0);
2152 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape,
2157 /* We need to ignore certain errorcode here. */
2159 case CCID_DRIVER_ERR_CARD_INACTIVE:
2160 case CCID_DRIVER_ERR_NO_CARD:
2162 if (msglen > resultmax)
2163 rc = CCID_DRIVER_ERR_INV_VALUE; /* Response too large. */
2166 memcpy (result, msg, msglen);
2167 *resultlen = msglen;
2181 ccid_transceive_escape (ccid_driver_t handle,
2182 const unsigned char *data, size_t datalen,
2183 unsigned char *resp, size_t maxresplen, size_t *nresp)
2185 return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp);
2192 ccid_poll (ccid_driver_t handle)
2195 unsigned char msg[10];
2201 rc = libusb_bulk_transfer (handle->idev, handle->ep_intr,
2202 (char*)msg, sizeof msg, &msglen,
2203 0 /* ms timeout */ );
2204 if (rc == LIBUSB_ERROR_TIMEOUT)
2212 DEBUGOUT_1 ("usb_intr_read error: %s\n", libusb_error_name (rc));
2213 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2218 DEBUGOUT ("intr-in msg too short\n");
2219 return CCID_DRIVER_ERR_INV_VALUE;
2222 if (msg[0] == RDR_to_PC_NotifySlotChange)
2224 DEBUGOUT ("notify slot change:");
2225 for (i=1; i < msglen; i++)
2226 for (j=0; j < 4; j++)
2227 DEBUGOUT_CONT_3 (" %d:%c%c",
2229 (msg[i] & (1<<(j*2)))? 'p':'-',
2230 (msg[i] & (2<<(j*2)))? '*':' ');
2233 else if (msg[0] == RDR_to_PC_HardwareError)
2235 DEBUGOUT ("hardware error occurred\n");
2239 DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]);
2246 /* Note that this function won't return the error codes NO_CARD or
2249 ccid_slot_status (ccid_driver_t handle, int *statusbits)
2252 unsigned char msg[100];
2254 unsigned char seqno;
2258 msg[0] = PC_to_RDR_GetSlotStatus;
2259 msg[5] = 0; /* slot */
2260 msg[6] = seqno = handle->seqno++;
2261 msg[7] = 0; /* RFU */
2262 msg[8] = 0; /* RFU */
2263 msg[9] = 0; /* RFU */
2264 set_msg_len (msg, 0);
2266 rc = bulk_out (handle, msg, 10, 1);
2269 /* Note that we set the NO_DEBUG flag here, so that the logs won't
2270 get cluttered up by a ticker function checking for the slot
2271 status and debugging enabled. */
2272 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
2273 seqno, retries? 1000 : 200, 1);
2274 if (rc == CCID_DRIVER_ERR_CARD_IO_ERROR && retries < 3)
2278 DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n");
2279 libusb_clear_halt (handle->idev, handle->ep_bulk_in);
2280 libusb_clear_halt (handle->idev, handle->ep_bulk_out);
2283 DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n");
2287 if (rc && rc != CCID_DRIVER_ERR_NO_CARD
2288 && rc != CCID_DRIVER_ERR_CARD_INACTIVE)
2290 *statusbits = (msg[7] & 3);
2296 /* Parse ATR string (of ATRLEN) and update parameters at PARAM.
2297 Calling this routine, it should prepare default values at PARAM
2298 beforehand. This routine assumes that card is accessed by T=1
2299 protocol. It doesn't analyze historical bytes at all.
2301 Returns < 0 value on error:
2302 -1 for parse error or integrity check error
2303 -2 for card doesn't support T=1 protocol
2304 -3 for parameters are nod explicitly defined by ATR
2305 -4 for this driver doesn't support CRC
2307 Returns >= 0 on success:
2308 0 for card is negotiable mode
2309 1 for card is specific mode (and not negotiable)
2312 update_param_by_atr (unsigned char *param, unsigned char *atr, size_t atrlen)
2316 int historical_bytes_num, negotiable = 1;
2318 #define NEXTBYTE() do { i++; if (atrlen <= i) return -1; } while (0)
2323 param[1] |= 0x02; /* Convention is inverse. */
2327 historical_bytes_num = atr[i] & 0x0f;
2332 param[0] = atr[i]; /* TA1 - Fi & Di */
2337 NEXTBYTE (); /* TB1 - ignore */
2341 param[2] = atr[i]; /* TC1 - Guard Time */
2347 y = (atr[i] >> 4); /* TD1 */
2352 { /* TA2 - PPS mode */
2353 if ((atr[i] & 0x0f) != 1)
2354 return -2; /* Wrong card protocol (!= 1). */
2356 if ((atr[i] & 0x10) != 0x10)
2357 return -3; /* Transmission parameters are implicitly defined. */
2359 negotiable = 0; /* TA2 means specific mode. */
2364 NEXTBYTE (); /* TB2 - ignore */
2367 NEXTBYTE (); /* TC2 - ignore */
2371 y = (atr[i] >> 4); /* TD2 */
2383 param[5] = atr[i]; /* IFSC */
2385 /* XXX: check voltage? */
2386 param[4] = (atr[i] >> 6); /* ClockStop */
2394 param[3] = atr[i]; /* TBx - BWI & CWI */
2401 param[1] |= (atr[i] & 0x01); /* TCx - LRC/CRC */
2404 if (param[1] & 0x01)
2405 return -4; /* CRC not supported yet. */
2410 y = (atr[i] >> 4); /* TDx */
2419 i += historical_bytes_num - 1;
2441 /* Return the ATR of the card. This is not a cached value and thus an
2442 actual reset is done. */
2444 ccid_get_atr (ccid_driver_t handle,
2445 unsigned char *atr, size_t maxatrlen, size_t *atrlen)
2449 unsigned char msg[100];
2450 unsigned char *tpdu;
2451 size_t msglen, tpdulen;
2452 unsigned char seqno;
2457 unsigned char param[7] = { /* For Protocol T=1 */
2458 0x11, /* bmFindexDindex */
2459 0x10, /* bmTCCKST1 */
2460 0x00, /* bGuardTimeT1 */
2461 0x4d, /* bmWaitingIntegersT1 */
2462 0x00, /* bClockStop */
2464 0x00 /* bNadValue */
2467 /* First check whether a card is available. */
2468 rc = ccid_slot_status (handle, &statusbits);
2471 if (statusbits == 2)
2472 return CCID_DRIVER_ERR_NO_CARD;
2474 /* For an inactive and also for an active card, issue the PowerOn
2475 command to get the ATR. */
2477 msg[0] = PC_to_RDR_IccPowerOn;
2478 msg[5] = 0; /* slot */
2479 msg[6] = seqno = handle->seqno++;
2480 /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */
2481 msg[7] = handle->auto_voltage ? 0 : 1;
2482 msg[8] = 0; /* RFU */
2483 msg[9] = 0; /* RFU */
2484 set_msg_len (msg, 0);
2487 rc = bulk_out (handle, msg, msglen, 0);
2490 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2494 if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb
2495 && ((handle->id_vendor == VENDOR_CHERRY
2496 && handle->id_product == 0x0005)
2497 || (handle->id_vendor == VENDOR_GEMPC
2498 && handle->id_product == 0x4433)
2502 /* Try switching to ISO mode. */
2503 if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2,
2507 else if (CCID_COMMAND_FAILED (msg))
2508 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2511 handle->powered_off = 0;
2515 size_t n = msglen - 10;
2519 memcpy (atr, msg+10, n);
2523 param[6] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2524 rc = update_param_by_atr (param, msg+10, msglen - 10);
2527 DEBUGOUT_1 ("update_param_by_atr failed: %d\n", rc);
2528 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2533 if (handle->auto_param)
2535 msg[0] = PC_to_RDR_GetParameters;
2536 msg[5] = 0; /* slot */
2537 msg[6] = seqno = handle->seqno++;
2538 msg[7] = 0; /* RFU */
2539 msg[8] = 0; /* RFU */
2540 msg[9] = 0; /* RFU */
2541 set_msg_len (msg, 0);
2543 rc = bulk_out (handle, msg, msglen, 0);
2545 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2548 DEBUGOUT ("GetParameters failed\n");
2549 else if (msglen == 17 && msg[9] == 1)
2552 else if (handle->auto_pps)
2554 else if (rc == 1) /* It's negotiable, send PPS. */
2556 msg[0] = PC_to_RDR_XfrBlock;
2557 msg[5] = 0; /* slot */
2558 msg[6] = seqno = handle->seqno++;
2562 msg[10] = 0xff; /* PPSS */
2563 msg[11] = 0x11; /* PPS0: PPS1, Protocol T=1 */
2564 msg[12] = param[0]; /* PPS1: Fi / Di */
2565 msg[13] = 0xff ^ 0x11 ^ param[0]; /* PCK */
2566 set_msg_len (msg, 4);
2569 rc = bulk_out (handle, msg, msglen, 0);
2573 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2578 if (msglen != 10 + 4)
2580 DEBUGOUT_1 ("Setting PPS failed: %zu\n", msglen);
2581 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2584 if (msg[10] != 0xff || msg[11] != 0x11 || msg[12] != param[0])
2586 DEBUGOUT_1 ("Setting PPS failed: 0x%02x\n", param[0]);
2587 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2591 /* Setup parameters to select T=1. */
2592 msg[0] = PC_to_RDR_SetParameters;
2593 msg[5] = 0; /* slot */
2594 msg[6] = seqno = handle->seqno++;
2595 msg[7] = 1; /* Select T=1. */
2596 msg[8] = 0; /* RFU */
2597 msg[9] = 0; /* RFU */
2600 memcpy (&msg[10], param, 7);
2601 set_msg_len (msg, 7);
2604 rc = bulk_out (handle, msg, msglen, 0);
2607 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2610 DEBUGOUT ("SetParameters failed (ignored)\n");
2612 if (!rc && msglen > 15 && msg[15] >= 16 && msg[15] <= 254 )
2613 handle->ifsc = msg[15];
2615 handle->ifsc = 128; /* Something went wrong, assume 128 bytes. */
2617 if (handle->nonnull_nad && msglen > 16 && msg[16] == 0)
2619 DEBUGOUT ("Use Null-NAD, clearing handle->nonnull_nad.\n");
2620 handle->nonnull_nad = 0;
2626 /* Send an S-Block with our maximum IFSD to the CCID. */
2627 if (!handle->apdu_level && !handle->auto_ifsd)
2630 /* NAD: DAD=1, SAD=0 */
2631 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2632 tpdu[1] = (0xc0 | 0 | 1); /* S-block request: change IFSD */
2634 tpdu[3] = handle->max_ifsd? handle->max_ifsd : 32;
2636 edc = compute_edc (tpdu, tpdulen, use_crc);
2638 tpdu[tpdulen++] = (edc >> 8);
2639 tpdu[tpdulen++] = edc;
2641 msg[0] = PC_to_RDR_XfrBlock;
2642 msg[5] = 0; /* slot */
2643 msg[6] = seqno = handle->seqno++;
2645 msg[8] = 0; /* RFU */
2646 msg[9] = 0; /* RFU */
2647 set_msg_len (msg, tpdulen);
2648 msglen = 10 + tpdulen;
2650 if (debug_level > 1)
2651 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
2652 ((msg[11] & 0xc0) == 0x80)? 'R' :
2653 (msg[11] & 0x80)? 'S' : 'I',
2654 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2655 : !!(msg[11] & 0x40)),
2656 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2658 rc = bulk_out (handle, msg, msglen, 0);
2663 rc = bulk_in (handle, msg, sizeof msg, &msglen,
2664 RDR_to_PC_DataBlock, seqno, 5000, 0);
2669 tpdulen = msglen - 10;
2672 return CCID_DRIVER_ERR_ABORTED;
2674 if (debug_level > 1)
2675 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2676 ((msg[11] & 0xc0) == 0x80)? 'R' :
2677 (msg[11] & 0x80)? 'S' : 'I',
2678 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2679 : !!(msg[11] & 0x40)),
2680 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2681 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2683 if ((tpdu[1] & 0xe0) != 0xe0 || tpdu[2] != 1)
2685 DEBUGOUT ("invalid response for S-block (Change-IFSD)\n");
2688 DEBUGOUT_1 ("IFSD has been set to %d\n", tpdu[3]);
2698 compute_edc (const unsigned char *data, size_t datalen, int use_crc)
2702 return 0x42; /* Not yet implemented. */
2706 unsigned char crc = 0;
2708 for (; datalen; datalen--)
2715 /* Return true if APDU is an extended length one. */
2717 is_exlen_apdu (const unsigned char *apdu, size_t apdulen)
2719 if (apdulen < 7 || apdu[4])
2720 return 0; /* Too short or no Z byte. */
2725 /* Helper for ccid_transceive used for APDU level exchanges. */
2727 ccid_transceive_apdu_level (ccid_driver_t handle,
2728 const unsigned char *apdu_buf, size_t apdu_len,
2729 unsigned char *resp, size_t maxresplen,
2733 unsigned char msg[CCID_MAX_BUF];
2734 const unsigned char *apdu_p;
2735 size_t apdu_part_len;
2737 unsigned char seqno;
2739 unsigned char chain = 0;
2741 if (apdu_len == 0 || apdu_len > sizeof (msg) - 10)
2742 return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
2747 apdu_part_len = apdu_len;
2748 if (apdu_part_len > handle->max_ccid_msglen - 10)
2750 apdu_part_len = handle->max_ccid_msglen - 10;
2754 msg[0] = PC_to_RDR_XfrBlock;
2755 msg[5] = 0; /* slot */
2756 msg[6] = seqno = handle->seqno++;
2760 memcpy (msg+10, apdu_p, apdu_part_len);
2761 set_msg_len (msg, apdu_part_len);
2762 msglen = 10 + apdu_part_len;
2764 rc = bulk_out (handle, msg, msglen, 0);
2768 apdu_p += apdu_part_len;
2769 apdu_len -= apdu_part_len;
2771 rc = bulk_in (handle, msg, sizeof msg, &msglen,
2772 RDR_to_PC_DataBlock, seqno, CCID_CMD_TIMEOUT, 0);
2776 if (!(chain & 0x01))
2785 apdu_part_len = msglen - 10;
2786 if (resp && apdu_len + apdu_part_len <= maxresplen)
2787 memcpy (resp + apdu_len, msg+10, apdu_part_len);
2788 apdu_len += apdu_part_len;
2790 if (!(msg[9] & 0x01))
2793 msg[0] = PC_to_RDR_XfrBlock;
2794 msg[5] = 0; /* slot */
2795 msg[6] = seqno = handle->seqno++;
2797 msg[8] = 0x10; /* Request next data block */
2799 set_msg_len (msg, 0);
2802 rc = bulk_out (handle, msg, msglen, 0);
2806 rc = bulk_in (handle, msg, sizeof msg, &msglen,
2807 RDR_to_PC_DataBlock, seqno, CCID_CMD_TIMEOUT, 0);
2814 if (apdu_len > maxresplen)
2816 DEBUGOUT_2 ("provided buffer too short for received data "
2818 (unsigned int)apdu_len, (unsigned int)maxresplen);
2819 return CCID_DRIVER_ERR_INV_VALUE;
2831 Protocol T=1 overview
2835 1 byte Node Address (NAD)
2836 1 byte Protocol Control Byte (PCB)
2839 0-254 byte APDU or Control Information (INF)
2841 1 byte Error Detection Code (EDC)
2845 bit 4..6 Destination Node Address (DAD)
2847 bit 2..0 Source Node Address (SAD)
2849 If node adresses are not used, SAD and DAD should be set to 0 on
2850 the first block sent to the card. If they are used they should
2851 have different values (0 for one is okay); that first block sets up
2852 the addresses of the nodes.
2855 Information Block (I-Block):
2857 bit 6 Sequence number (yep, that is modulo 2)
2860 Received-Ready Block (R-Block):
2864 bit 4 Sequence number
2865 bit 3..0 0 = no error
2866 1 = EDC or parity error
2868 other values are reserved
2869 Supervisory Block (S-Block):
2872 bit 5 clear=request,set=response
2873 bit 4..0 0 = resyncronisation request
2874 1 = information field size request
2876 3 = extension of BWT request
2878 other values are reserved
2883 ccid_transceive (ccid_driver_t handle,
2884 const unsigned char *apdu_buf, size_t apdu_buflen,
2885 unsigned char *resp, size_t maxresplen, size_t *nresp)
2888 /* The size of the buffer used to be 10+259. For the via_escape
2889 hack we need one extra byte, thus 11+259. */
2890 unsigned char send_buffer[11+259], recv_buffer[11+259];
2891 const unsigned char *apdu;
2893 unsigned char *msg, *tpdu, *p;
2894 size_t msglen, tpdulen, last_tpdulen, n;
2895 unsigned char seqno;
2908 nresp = &dummy_nresp;
2911 /* Smarter readers allow sending APDUs directly; divert here. */
2912 if (handle->apdu_level)
2914 /* We employ a hack for Omnikey readers which are able to send
2915 TPDUs using an escape sequence. There is no documentation
2916 but the Windows driver does it this way. Tested using a
2917 CM6121. This method works also for the Cherry XX44
2918 keyboards; however there are problems with the
2919 ccid_tranceive_secure which leads to a loss of sync on the
2920 CCID level. If Cherry wants to make their keyboard work
2921 again, they should hand over some docs. */
2922 if ((handle->id_vendor == VENDOR_OMNIKEY
2923 || (!handle->idev && handle->id_product == TRANSPORT_CM4040))
2924 && handle->apdu_level < 2
2925 && is_exlen_apdu (apdu_buf, apdu_buflen))
2928 return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen,
2929 resp, maxresplen, nresp);
2932 /* The other readers we support require sending TPDUs. */
2934 tpdulen = 0; /* Avoid compiler warning about no initialization. */
2936 hdrlen = via_escape? 11 : 10;
2938 /* NAD: DAD=1, SAD=0 */
2939 nad_byte = handle->nonnull_nad? ((1 << 4) | 0): 0;
2943 last_tpdulen = 0; /* Avoid gcc warning (controlled by RESYNCING). */
2951 apdulen = apdu_buflen;
2954 /* Construct an I-Block. */
2955 tpdu = msg + hdrlen;
2957 tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */
2958 if (apdulen > handle->ifsc )
2960 apdulen = handle->ifsc;
2961 apdu_buf += handle->ifsc;
2962 apdu_buflen -= handle->ifsc;
2963 tpdu[1] |= (1 << 5); /* Set more bit. */
2966 memcpy (tpdu+3, apdu, apdulen);
2967 tpdulen = 3 + apdulen;
2968 edc = compute_edc (tpdu, tpdulen, use_crc);
2970 tpdu[tpdulen++] = (edc >> 8);
2971 tpdu[tpdulen++] = edc;
2976 msg[0] = PC_to_RDR_Escape;
2977 msg[5] = 0; /* slot */
2978 msg[6] = seqno = handle->seqno++;
2979 msg[7] = 0; /* RFU */
2980 msg[8] = 0; /* RFU */
2981 msg[9] = 0; /* RFU */
2982 msg[10] = 0x1a; /* Omnikey command to send a TPDU. */
2983 set_msg_len (msg, 1 + tpdulen);
2987 msg[0] = PC_to_RDR_XfrBlock;
2988 msg[5] = 0; /* slot */
2989 msg[6] = seqno = handle->seqno++;
2990 msg[7] = 4; /* bBWI */
2991 msg[8] = 0; /* RFU */
2992 msg[9] = 0; /* RFU */
2993 set_msg_len (msg, tpdulen);
2995 msglen = hdrlen + tpdulen;
2997 last_tpdulen = tpdulen;
3000 if (debug_level > 1)
3001 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
3002 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
3003 (msg[pcboff] & 0x80)? 'S' : 'I',
3004 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
3005 : !!(msg[pcboff] & 0x40)),
3006 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
3009 rc = bulk_out (handle, msg, msglen, 0);
3014 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3015 via_escape? RDR_to_PC_Escape : RDR_to_PC_DataBlock,
3016 seqno, CCID_CMD_TIMEOUT, 0);
3020 tpdu = msg + hdrlen;
3021 tpdulen = msglen - hdrlen;
3026 libusb_clear_halt (handle->idev, handle->ep_bulk_in);
3027 return CCID_DRIVER_ERR_ABORTED;
3030 if (debug_level > 1)
3031 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3032 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
3033 (msg[pcboff] & 0x80)? 'S' : 'I',
3034 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
3035 : !!(msg[pcboff] & 0x40)),
3036 ((msg[pcboff] & 0xc0) == 0x80)? (msg[pcboff] & 0x0f) : 0,
3037 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
3040 if (!(tpdu[1] & 0x80))
3041 { /* This is an I-block. */
3044 { /* last block sent was successful. */
3049 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3050 { /* Response does not match our sequence number. */
3052 tpdu = msg + hdrlen;
3054 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */
3057 edc = compute_edc (tpdu, tpdulen, use_crc);
3059 tpdu[tpdulen++] = (edc >> 8);
3060 tpdu[tpdulen++] = edc;
3067 p = tpdu + 3; /* Skip the prologue field. */
3068 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3069 /* fixme: verify the checksum. */
3074 DEBUGOUT_2 ("provided buffer too short for received data "
3076 (unsigned int)n, (unsigned int)maxresplen);
3077 return CCID_DRIVER_ERR_INV_VALUE;
3080 memcpy (resp, p, n);
3086 if (!(tpdu[1] & 0x20))
3087 return 0; /* No chaining requested - ready. */
3090 tpdu = msg + hdrlen;
3092 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */
3095 edc = compute_edc (tpdu, tpdulen, use_crc);
3097 tpdu[tpdulen++] = (edc >> 8);
3098 tpdu[tpdulen++] = edc;
3100 else if ((tpdu[1] & 0xc0) == 0x80)
3101 { /* This is a R-block. */
3102 if ( (tpdu[1] & 0x0f))
3105 if (via_escape && retries == 1 && (msg[pcboff] & 0x0f))
3107 /* Error probably due to switching to TPDU. Send a
3108 resync request. We use the recv_buffer so that
3109 we don't corrupt the send_buffer. */
3111 tpdu = msg + hdrlen;
3113 tpdu[1] = 0xc0; /* S-block resync request. */
3116 edc = compute_edc (tpdu, tpdulen, use_crc);
3118 tpdu[tpdulen++] = (edc >> 8);
3119 tpdu[tpdulen++] = edc;
3121 DEBUGOUT ("T=1: requesting resync\n");
3123 else if (retries > 3)
3125 DEBUGOUT ("T=1: 3 failed retries\n");
3126 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3130 /* Error: repeat last block */
3132 tpdulen = last_tpdulen;
3135 else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns)
3136 { /* Response does not match our sequence number. */
3137 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3138 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3141 { /* Send next chunk. */
3149 DEBUGOUT ("unexpected ACK R-block received\n");
3150 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3154 { /* This is a S-block. */
3156 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d\n",
3157 (tpdu[1] & 0x20)? "response": "request",
3159 if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 1 && tpdu[2] == 1)
3161 /* Information field size request. */
3162 unsigned char ifsc = tpdu[3];
3164 if (ifsc < 16 || ifsc > 254)
3165 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3168 tpdu = msg + hdrlen;
3170 tpdu[1] = (0xc0 | 0x20 | 1); /* S-block response */
3174 edc = compute_edc (tpdu, tpdulen, use_crc);
3176 tpdu[tpdulen++] = (edc >> 8);
3177 tpdu[tpdulen++] = edc;
3178 DEBUGOUT_1 ("T=1: requesting an ifsc=%d\n", ifsc);
3180 else if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2])
3182 /* Wait time extension request. */
3183 unsigned char bwi = tpdu[3];
3185 tpdu = msg + hdrlen;
3187 tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */
3191 edc = compute_edc (tpdu, tpdulen, use_crc);
3193 tpdu[tpdulen++] = (edc >> 8);
3194 tpdu[tpdulen++] = edc;
3195 DEBUGOUT_1 ("T=1: waittime extension of bwi=%d\n", bwi);
3196 print_progress (handle);
3198 else if ( (tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 0 && !tpdu[2])
3200 DEBUGOUT ("T=1: resync ack from reader\n");
3201 /* Repeat previous block. */
3203 tpdulen = last_tpdulen;
3206 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3208 } /* end T=1 protocol loop. */
3214 /* Send the CCID Secure command to the reader. APDU_BUF should
3215 contain the APDU template. PIN_MODE defines how the pin gets
3218 1 := The PIN is ASCII encoded and of variable length. The
3219 length of the PIN entered will be put into Lc by the reader.
3220 The APDU should me made up of 4 bytes without Lc.
3222 PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0
3223 may be used t enable reasonable defaults.
3225 When called with RESP and NRESP set to NULL, the function will
3226 merely check whether the reader supports the secure command for the
3227 given APDU and PIN_MODE. */
3229 ccid_transceive_secure (ccid_driver_t handle,
3230 const unsigned char *apdu_buf, size_t apdu_buflen,
3232 unsigned char *resp, size_t maxresplen, size_t *nresp)
3235 unsigned char send_buffer[10+259], recv_buffer[10+259];
3236 unsigned char *msg, *tpdu, *p;
3237 size_t msglen, tpdulen, n;
3238 unsigned char seqno;
3241 int cherry_mode = 0;
3243 int enable_varlen = 0;
3245 testmode = !resp && !nresp;
3248 nresp = &dummy_nresp;
3251 if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1))
3253 else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2))
3256 return CCID_DRIVER_ERR_NO_PINPAD;
3258 if (!pininfo->minlen)
3259 pininfo->minlen = 1;
3260 if (!pininfo->maxlen)
3261 pininfo->maxlen = 15;
3263 /* Note that the 25 is the maximum value the SPR532 allows. */
3264 if (pininfo->minlen < 1 || pininfo->minlen > 25
3265 || pininfo->maxlen < 1 || pininfo->maxlen > 25
3266 || pininfo->minlen > pininfo->maxlen)
3267 return CCID_DRIVER_ERR_INV_VALUE;
3269 /* We have only tested a few readers so better don't risk anything
3270 and do not allow the use with other readers. */
3271 switch (handle->id_vendor)
3273 case VENDOR_SCM: /* Tested with SPR 532. */
3274 case VENDOR_KAAN: /* Tested with KAAN Advanced (1.02). */
3275 case VENDOR_FSIJ: /* Tested with Gnuk (0.21). */
3276 pininfo->maxlen = 25;
3279 case VENDOR_REINER:/* Tested with cyberJack go */
3280 case VENDOR_VASCO: /* Tested with DIGIPASS 920 */
3284 pininfo->maxlen = 15;
3286 /* The CHERRY XX44 keyboard echos an asterisk for each entered
3287 character on the keyboard channel. We use a special variant
3288 of PC_to_RDR_Secure which directs these characters to the
3289 smart card's bulk-in channel. We also need to append a zero
3290 Lc byte to the APDU. It seems that it will be replaced with
3291 the actual length instead of being appended before the APDU
3292 is send to the card. */
3294 if (handle->id_product != CHERRY_ST2000)
3298 if ((handle->id_vendor == VENDOR_GEMPC &&
3299 handle->id_product == GEMPC_PINPAD)
3300 || (handle->id_vendor == VENDOR_VEGA &&
3301 handle->id_product == VEGA_ALPHA))
3304 pininfo->minlen = 4;
3305 pininfo->maxlen = 8;
3308 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3312 pininfo->fixedlen = 0;
3315 return 0; /* Success */
3317 if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
3318 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3321 if (handle->id_vendor == VENDOR_SCM)
3323 DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n");
3324 rc = send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3,
3330 msg[0] = cherry_mode? 0x89 : PC_to_RDR_Secure;
3331 msg[5] = 0; /* slot */
3332 msg[6] = seqno = handle->seqno++;
3333 msg[7] = 0; /* bBWI */
3334 msg[8] = 0; /* RFU */
3335 msg[9] = 0; /* RFU */
3336 msg[10] = apdu_buf[1] == 0x20 ? 0 : 1;
3337 /* Perform PIN verification or PIN modification. */
3338 msg[11] = 0; /* Timeout in seconds. */
3339 msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
3340 if (handle->id_vendor == VENDOR_SCM)
3342 /* For the SPR532 the next 2 bytes need to be zero. We do this
3343 for all SCM products. Kudos to Martin Paljak for this
3345 msg[13] = msg[14] = 0;
3349 msg[13] = pininfo->fixedlen; /* bmPINBlockString:
3350 0 bits of pin length to insert.
3351 PIN block size by fixedlen. */
3352 msg[14] = 0x00; /* bmPINLengthFormat:
3353 Units are bytes, position is 0. */
3357 if (apdu_buf[1] == 0x24)
3359 msg[msglen++] = 0; /* bInsertionOffsetOld */
3360 msg[msglen++] = pininfo->fixedlen; /* bInsertionOffsetNew */
3363 /* The following is a little endian word. */
3364 msg[msglen++] = pininfo->maxlen; /* wPINMaxExtraDigit-Maximum. */
3365 msg[msglen++] = pininfo->minlen; /* wPINMaxExtraDigit-Minimum. */
3367 if (apdu_buf[1] == 0x24)
3368 msg[msglen++] = apdu_buf[2] == 0 ? 0x03 : 0x01;
3370 * 0x00: new PIN once
3371 * 0x01: new PIN twice (confirmation)
3372 * 0x02: old PIN and new PIN once
3373 * 0x03: old PIN and new PIN twice (confirmation)
3376 msg[msglen] = 0x02; /* bEntryValidationCondition:
3377 Validation key pressed */
3378 if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
3379 msg[msglen] |= 0x01; /* Max size reached. */
3382 if (apdu_buf[1] == 0x20)
3383 msg[msglen++] = 0x01; /* bNumberMessage. */
3385 msg[msglen++] = 0x03; /* bNumberMessage. */
3387 msg[msglen++] = 0x09; /* wLangId-Low: English FIXME: use the first entry. */
3388 msg[msglen++] = 0x04; /* wLangId-High. */
3390 if (apdu_buf[1] == 0x20)
3391 msg[msglen++] = 0; /* bMsgIndex. */
3394 msg[msglen++] = 0; /* bMsgIndex1. */
3395 msg[msglen++] = 1; /* bMsgIndex2. */
3396 msg[msglen++] = 2; /* bMsgIndex3. */
3400 n = pininfo->fixedlen;
3401 if (apdu_buf[1] == 0x24)
3402 n += pininfo->fixedlen;
3404 /* bTeoProlog follows: */
3405 msg[msglen++] = handle->nonnull_nad? ((1 << 4) | 0): 0;
3406 msg[msglen++] = ((handle->t1_ns & 1) << 6); /* I-block */
3408 msg[msglen++] = n + 5; /* apdulen should be filled for fixed length. */
3410 msg[msglen++] = 0; /* The apdulen will be filled in by the reader. */
3412 msg[msglen++] = apdu_buf[0]; /* CLA */
3413 msg[msglen++] = apdu_buf[1]; /* INS */
3414 msg[msglen++] = apdu_buf[2]; /* P1 */
3415 msg[msglen++] = apdu_buf[3]; /* P2 */
3418 else if (pininfo->fixedlen != 0)
3421 memset (&msg[msglen], 0xff, n);
3424 /* An EDC is not required. */
3425 set_msg_len (msg, msglen - 10);
3427 rc = bulk_out (handle, msg, msglen, 0);
3432 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3433 RDR_to_PC_DataBlock, seqno, 30000, 0);
3438 tpdulen = msglen - 10;
3440 if (handle->apdu_level)
3444 if (tpdulen > maxresplen)
3446 DEBUGOUT_2 ("provided buffer too short for received data "
3448 (unsigned int)tpdulen, (unsigned int)maxresplen);
3449 return CCID_DRIVER_ERR_INV_VALUE;
3452 memcpy (resp, tpdu, tpdulen);
3460 libusb_clear_halt (handle->idev, handle->ep_bulk_in);
3461 return CCID_DRIVER_ERR_ABORTED;
3463 if (debug_level > 1)
3464 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3465 ((msg[11] & 0xc0) == 0x80)? 'R' :
3466 (msg[11] & 0x80)? 'S' : 'I',
3467 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
3468 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
3469 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
3471 if (!(tpdu[1] & 0x80))
3472 { /* This is an I-block. */
3473 /* Last block sent was successful. */
3476 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3477 { /* Response does not match our sequence number. */
3478 DEBUGOUT ("I-block with wrong seqno received\n");
3479 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3484 p = tpdu + 3; /* Skip the prologue field. */
3485 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3486 /* fixme: verify the checksum. */
3491 DEBUGOUT_2 ("provided buffer too short for received data "
3493 (unsigned int)n, (unsigned int)maxresplen);
3494 return CCID_DRIVER_ERR_INV_VALUE;
3497 memcpy (resp, p, n);
3503 if (!(tpdu[1] & 0x20))
3504 return 0; /* No chaining requested - ready. */
3506 DEBUGOUT ("chaining requested but not supported for Secure operation\n");
3507 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3509 else if ((tpdu[1] & 0xc0) == 0x80)
3510 { /* This is a R-block. */
3511 if ( (tpdu[1] & 0x0f))
3512 { /* Error: repeat last block */
3513 DEBUGOUT ("No retries supported for Secure operation\n");
3514 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3516 else if (!!(tpdu[1] & 0x10) == handle->t1_ns)
3517 { /* Response does not match our sequence number. */
3518 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3519 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3522 { /* Send next chunk. */
3523 DEBUGOUT ("chaining not supported on Secure operation\n");
3524 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3528 { /* This is a S-block. */
3529 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d for Secure operation\n",
3530 (tpdu[1] & 0x20)? "response": "request",
3532 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3545 print_error (int err)
3552 case 0: p = "success";
3553 case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break;
3554 case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break;
3555 case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break;
3556 case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break;
3557 case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break;
3558 case CCID_DRIVER_ERR_BUSY: p = "busy"; break;
3559 case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break;
3560 case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break;
3561 case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break;
3562 case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break;
3563 case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break;
3564 case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break;
3565 default: sprintf (buf, "0x%05x", err); p = buf; break;
3567 fprintf (stderr, "operation failed: %s\n", p);
3572 print_data (const unsigned char *data, size_t length)
3576 fprintf (stderr, "operation status: %02X%02X\n",
3577 data[length-2], data[length-1]);
3582 fputs (" returned data:", stderr);
3583 for (; length; length--, data++)
3584 fprintf (stderr, " %02X", *data);
3585 putc ('\n', stderr);
3590 print_result (int rc, const unsigned char *data, size_t length)
3595 print_data (data, length);
3599 main (int argc, char **argv)
3604 unsigned char result[512];
3607 int verify_123456 = 0;
3619 if ( !strcmp (*argv, "--list"))
3622 p = ccid_get_reader_list ();
3629 else if ( !strcmp (*argv, "--debug"))
3631 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
3634 else if ( !strcmp (*argv, "--no-poll"))
3639 else if ( !strcmp (*argv, "--no-pinpad"))
3644 else if ( !strcmp (*argv, "--verify-123456"))
3653 rc = ccid_open_reader (&ccid, argc? *argv:NULL, NULL);
3659 fputs ("getting ATR ...\n", stderr);
3660 rc = ccid_get_atr (ccid, NULL, 0, NULL);
3669 fputs ("getting slot status ...\n", stderr);
3670 rc = ccid_slot_status (ccid, &slotstat);
3680 fputs ("selecting application OpenPGP ....\n", stderr);
3682 static unsigned char apdu[] = {
3683 0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01};
3684 rc = ccid_transceive (ccid,
3686 result, sizeof result, &resultlen);
3687 print_result (rc, result, resultlen);
3694 fputs ("getting OpenPGP DO 0x65 ....\n", stderr);
3696 static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 };
3697 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3698 result, sizeof result, &resultlen);
3699 print_result (rc, result, resultlen);
3708 static unsigned char apdu[] = { 0, 0x20, 0, 0x81 };
3711 if (ccid_transceive_secure (ccid,
3715 fputs ("can't verify using a PIN-Pad reader\n", stderr);
3718 fputs ("verifying CHV1 using the PINPad ....\n", stderr);
3720 rc = ccid_transceive_secure (ccid,
3723 result, sizeof result, &resultlen);
3724 print_result (rc, result, resultlen);
3729 if (verify_123456 && !did_verify)
3731 fputs ("verifying that CHV1 is 123456....\n", stderr);
3733 static unsigned char apdu[] = {0, 0x20, 0, 0x81,
3734 6, '1','2','3','4','5','6'};
3735 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3736 result, sizeof result, &resultlen);
3737 print_result (rc, result, resultlen);
3743 fputs ("getting OpenPGP DO 0x5E ....\n", stderr);
3745 static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 };
3746 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3747 result, sizeof result, &resultlen);
3748 print_result (rc, result, resultlen);
3752 ccid_close_reader (ccid);
3759 * compile-command: "gcc -DTEST -Wall -I/usr/local/include -lusb -g ccid-driver.c"
3763 #endif /*HAVE_LIBUSB*/