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;
242 int dev_fd; /* -1 for USB transport or file descriptor of the
245 unsigned short id_vendor;
246 unsigned short id_product;
254 unsigned char nonnull_nad;
258 unsigned char apdu_level:2; /* Reader supports short APDU level
259 exchange. With a value of 2 short
260 and extended level is supported.*/
261 unsigned int auto_voltage:1;
262 unsigned int auto_param:1;
263 unsigned int auto_pps:1;
264 unsigned int auto_ifsd:1;
265 unsigned int powered_off:1;
266 unsigned int has_pinpad:2;
267 unsigned int enodev_seen:1;
269 time_t last_progress; /* Last time we sent progress line. */
271 /* The progress callback and its first arg as supplied to
272 ccid_set_progress_cb. */
273 void (*progress_cb)(void *, const char *, int, int, int);
274 void *progress_cb_arg;
278 static int initialized_usb; /* Tracks whether USB has been initialized. */
279 static int debug_level; /* Flag to control the debug output.
282 2 = Level 1 + T=1 protocol tracing
283 3 = Level 2 + USB/I/O tracing of SlotStatus.
287 static unsigned int compute_edc (const unsigned char *data, size_t datalen,
289 static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
291 static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
292 size_t *nread, int expected_type, int seqno, int timeout,
294 static int abort_cmd (ccid_driver_t handle, int seqno);
295 static int send_escape_cmd (ccid_driver_t handle, const unsigned char *data,
296 size_t datalen, unsigned char *result,
297 size_t resultmax, size_t *resultlen);
299 /* Convert a little endian stored 4 byte value into an unsigned
302 convert_le_u32 (const unsigned char *buf)
304 return buf[0] | (buf[1] << 8) | (buf[2] << 16) | ((unsigned int)buf[3] << 24);
308 /* Convert a little endian stored 2 byte value into an unsigned
311 convert_le_u16 (const unsigned char *buf)
313 return buf[0] | (buf[1] << 8);
317 set_msg_len (unsigned char *msg, unsigned int length)
320 msg[2] = length >> 8;
321 msg[3] = length >> 16;
322 msg[4] = length >> 24;
327 my_sleep (int seconds)
330 npth_sleep (seconds);
332 # ifdef HAVE_W32_SYSTEM
333 Sleep (seconds*1000);
341 print_progress (ccid_driver_t handle)
343 time_t ct = time (NULL);
345 /* We don't want to print progress lines too often. */
346 if (ct == handle->last_progress)
349 if (handle->progress_cb)
350 handle->progress_cb (handle->progress_cb_arg, "card_busy", 'w', 0, 0);
352 handle->last_progress = ct;
357 /* Pint an error message for a failed CCID command including a textual
358 error code. MSG shall be the CCID message at a minimum of 10 bytes. */
360 print_command_failed (const unsigned char *msg)
369 ec = CCID_ERROR_CODE (msg);
372 case 0x00: t = "Command not supported"; break;
374 case 0xE0: t = "Slot busy"; break;
375 case 0xEF: t = "PIN cancelled"; break;
376 case 0xF0: t = "PIN timeout"; break;
378 case 0xF2: t = "Automatic sequence ongoing"; break;
379 case 0xF3: t = "Deactivated Protocol"; break;
380 case 0xF4: t = "Procedure byte conflict"; break;
381 case 0xF5: t = "ICC class not supported"; break;
382 case 0xF6: t = "ICC protocol not supported"; break;
383 case 0xF7: t = "Bad checksum in ATR"; break;
384 case 0xF8: t = "Bad TS in ATR"; break;
386 case 0xFB: t = "An all inclusive hardware error occurred"; break;
387 case 0xFC: t = "Overrun error while talking to the ICC"; break;
388 case 0xFD: t = "Parity error while talking to the ICC"; break;
389 case 0xFE: t = "CCID timed out while talking to the ICC"; break;
390 case 0xFF: t = "Host aborted the current activity"; break;
393 if (ec > 0 && ec < 128)
394 sprintf (buffer, "Parameter error at offset %d", ec);
396 sprintf (buffer, "Error code %02X", ec);
400 DEBUGOUT_1 ("CCID command failed: %s\n", t);
405 print_pr_data (const unsigned char *data, size_t datalen, size_t off)
409 for (; off < datalen; off++)
411 if (!any || !(off % 16))
415 DEBUGOUT_1 (" [%04lu] ", (unsigned long) off);
417 DEBUGOUT_CONT_1 (" %02X", data[off]);
420 if (any && (off % 16))
426 print_p2r_header (const char *name, const unsigned char *msg, size_t msglen)
428 DEBUGOUT_1 ("%s:\n", name);
431 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
432 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
433 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
438 print_p2r_iccpoweron (const unsigned char *msg, size_t msglen)
440 print_p2r_header ("PC_to_RDR_IccPowerOn", msg, msglen);
443 DEBUGOUT_2 (" bPowerSelect ......: 0x%02x (%s)\n", msg[7],
445 msg[7] == 1? "5.0 V":
446 msg[7] == 2? "3.0 V":
447 msg[7] == 3? "1.8 V":"");
448 print_pr_data (msg, msglen, 8);
453 print_p2r_iccpoweroff (const unsigned char *msg, size_t msglen)
455 print_p2r_header ("PC_to_RDR_IccPowerOff", msg, msglen);
456 print_pr_data (msg, msglen, 7);
461 print_p2r_getslotstatus (const unsigned char *msg, size_t msglen)
463 print_p2r_header ("PC_to_RDR_GetSlotStatus", msg, msglen);
464 print_pr_data (msg, msglen, 7);
469 print_p2r_xfrblock (const unsigned char *msg, size_t msglen)
473 print_p2r_header ("PC_to_RDR_XfrBlock", msg, msglen);
476 DEBUGOUT_1 (" bBWI ..............: 0x%02x\n", msg[7]);
477 val = convert_le_u16 (msg+8);
478 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
479 val == 1? " (continued)":
480 val == 2? " (continues+ends)":
481 val == 3? " (continues+continued)":
482 val == 16? " (DataBlock-expected)":"");
483 print_pr_data (msg, msglen, 10);
488 print_p2r_getparameters (const unsigned char *msg, size_t msglen)
490 print_p2r_header ("PC_to_RDR_GetParameters", msg, msglen);
491 print_pr_data (msg, msglen, 7);
496 print_p2r_resetparameters (const unsigned char *msg, size_t msglen)
498 print_p2r_header ("PC_to_RDR_ResetParameters", msg, msglen);
499 print_pr_data (msg, msglen, 7);
504 print_p2r_setparameters (const unsigned char *msg, size_t msglen)
506 print_p2r_header ("PC_to_RDR_SetParameters", msg, msglen);
509 DEBUGOUT_1 (" bProtocolNum ......: 0x%02x\n", msg[7]);
510 print_pr_data (msg, msglen, 8);
515 print_p2r_escape (const unsigned char *msg, size_t msglen)
517 print_p2r_header ("PC_to_RDR_Escape", msg, msglen);
518 print_pr_data (msg, msglen, 7);
523 print_p2r_iccclock (const unsigned char *msg, size_t msglen)
525 print_p2r_header ("PC_to_RDR_IccClock", msg, msglen);
528 DEBUGOUT_1 (" bClockCommand .....: 0x%02x\n", msg[7]);
529 print_pr_data (msg, msglen, 8);
534 print_p2r_to0apdu (const unsigned char *msg, size_t msglen)
536 print_p2r_header ("PC_to_RDR_T0APDU", msg, msglen);
539 DEBUGOUT_1 (" bmChanges .........: 0x%02x\n", msg[7]);
540 DEBUGOUT_1 (" bClassGetResponse .: 0x%02x\n", msg[8]);
541 DEBUGOUT_1 (" bClassEnvelope ....: 0x%02x\n", msg[9]);
542 print_pr_data (msg, msglen, 10);
547 print_p2r_secure (const unsigned char *msg, size_t msglen)
551 print_p2r_header ("PC_to_RDR_Secure", msg, msglen);
554 DEBUGOUT_1 (" bBMI ..............: 0x%02x\n", msg[7]);
555 val = convert_le_u16 (msg+8);
556 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
557 val == 1? " (continued)":
558 val == 2? " (continues+ends)":
559 val == 3? " (continues+continued)":
560 val == 16? " (DataBlock-expected)":"");
561 print_pr_data (msg, msglen, 10);
566 print_p2r_mechanical (const unsigned char *msg, size_t msglen)
568 print_p2r_header ("PC_to_RDR_Mechanical", msg, msglen);
571 DEBUGOUT_1 (" bFunction .........: 0x%02x\n", msg[7]);
572 print_pr_data (msg, msglen, 8);
577 print_p2r_abort (const unsigned char *msg, size_t msglen)
579 print_p2r_header ("PC_to_RDR_Abort", msg, msglen);
580 print_pr_data (msg, msglen, 7);
585 print_p2r_setdatarate (const unsigned char *msg, size_t msglen)
587 print_p2r_header ("PC_to_RDR_SetDataRate", msg, msglen);
590 print_pr_data (msg, msglen, 7);
595 print_p2r_unknown (const unsigned char *msg, size_t msglen)
597 print_p2r_header ("Unknown PC_to_RDR command", msg, msglen);
600 print_pr_data (msg, msglen, 0);
605 print_r2p_header (const char *name, const unsigned char *msg, size_t msglen)
607 DEBUGOUT_1 ("%s:\n", name);
610 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
611 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
612 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
613 DEBUGOUT_1 (" bStatus ...........: %u\n", msg[7]);
615 DEBUGOUT_1 (" bError ............: %u\n", msg[8]);
620 print_r2p_datablock (const unsigned char *msg, size_t msglen)
622 print_r2p_header ("RDR_to_PC_DataBlock", msg, msglen);
626 DEBUGOUT_2 (" bChainParameter ...: 0x%02x%s\n", msg[9],
627 msg[9] == 1? " (continued)":
628 msg[9] == 2? " (continues+ends)":
629 msg[9] == 3? " (continues+continued)":
630 msg[9] == 16? " (XferBlock-expected)":"");
631 print_pr_data (msg, msglen, 10);
636 print_r2p_slotstatus (const unsigned char *msg, size_t msglen)
638 print_r2p_header ("RDR_to_PC_SlotStatus", msg, msglen);
641 DEBUGOUT_2 (" bClockStatus ......: 0x%02x%s\n", msg[9],
642 msg[9] == 0? " (running)":
643 msg[9] == 1? " (stopped-L)":
644 msg[9] == 2? " (stopped-H)":
645 msg[9] == 3? " (stopped)":"");
646 print_pr_data (msg, msglen, 10);
651 print_r2p_parameters (const unsigned char *msg, size_t msglen)
653 print_r2p_header ("RDR_to_PC_Parameters", msg, msglen);
657 DEBUGOUT_1 (" protocol ..........: T=%d\n", msg[9]);
658 if (msglen == 17 && msg[9] == 1)
661 DEBUGOUT_1 (" bmFindexDindex ....: %02X\n", msg[10]);
662 DEBUGOUT_1 (" bmTCCKST1 .........: %02X\n", msg[11]);
663 DEBUGOUT_1 (" bGuardTimeT1 ......: %02X\n", msg[12]);
664 DEBUGOUT_1 (" bmWaitingIntegersT1: %02X\n", msg[13]);
665 DEBUGOUT_1 (" bClockStop ........: %02X\n", msg[14]);
666 DEBUGOUT_1 (" bIFSC .............: %d\n", msg[15]);
667 DEBUGOUT_1 (" bNadValue .........: %d\n", msg[16]);
670 print_pr_data (msg, msglen, 10);
675 print_r2p_escape (const unsigned char *msg, size_t msglen)
677 print_r2p_header ("RDR_to_PC_Escape", msg, msglen);
680 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
681 print_pr_data (msg, msglen, 10);
686 print_r2p_datarate (const unsigned char *msg, size_t msglen)
688 print_r2p_header ("RDR_to_PC_DataRate", msg, msglen);
693 DEBUGOUT_1 (" dwClockFrequency ..: %u\n", convert_le_u32 (msg+10));
694 DEBUGOUT_1 (" dwDataRate ..... ..: %u\n", convert_le_u32 (msg+14));
695 print_pr_data (msg, msglen, 18);
698 print_pr_data (msg, msglen, 10);
703 print_r2p_unknown (const unsigned char *msg, size_t msglen)
705 print_r2p_header ("Unknown RDR_to_PC command", msg, msglen);
708 DEBUGOUT_1 (" bMessageType ......: %02X\n", msg[0]);
709 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
710 print_pr_data (msg, msglen, 10);
714 /* Given a handle used for special transport prepare it for use. In
715 particular setup all information in way that resembles what
716 parse_cccid_descriptor does. */
718 prepare_special_transport (ccid_driver_t handle)
720 assert (!handle->id_vendor);
722 handle->nonnull_nad = 0;
723 handle->auto_ifsd = 0;
724 handle->max_ifsd = 32;
725 handle->max_ccid_msglen = CCID_MAX_BUF;
726 handle->has_pinpad = 0;
727 handle->apdu_level = 0;
728 switch (handle->id_product)
730 case TRANSPORT_CM4040:
731 DEBUGOUT ("setting up transport for CardMan 4040\n");
732 handle->apdu_level = 1;
735 default: assert (!"transport not defined");
739 /* Parse a CCID descriptor, optionally print all available features
740 and test whether this reader is usable by this driver. Returns 0
743 Note, that this code is based on the one in lsusb.c of the
744 usb-utils package, I wrote on 2003-09-01. -wk. */
746 parse_ccid_descriptor (ccid_driver_t handle, unsigned short bcd_device,
747 const unsigned char *buf, size_t buflen)
751 int have_t1 = 0, have_tpdu=0;
753 handle->nonnull_nad = 0;
754 handle->auto_ifsd = 0;
755 handle->max_ifsd = 32;
756 handle->has_pinpad = 0;
757 handle->apdu_level = 0;
758 handle->auto_voltage = 0;
759 handle->auto_param = 0;
760 handle->auto_pps = 0;
761 DEBUGOUT_3 ("idVendor: %04X idProduct: %04X bcdDevice: %04X\n",
762 handle->id_vendor, handle->id_product, bcd_device);
763 if (buflen < 54 || buf[0] < 54)
765 DEBUGOUT ("CCID device descriptor is too short\n");
769 DEBUGOUT ("ChipCard Interface Descriptor:\n");
770 DEBUGOUT_1 (" bLength %5u\n", buf[0]);
771 DEBUGOUT_1 (" bDescriptorType %5u\n", buf[1]);
772 DEBUGOUT_2 (" bcdCCID %2x.%02x", buf[3], buf[2]);
773 if (buf[3] != 1 || buf[2] != 0)
774 DEBUGOUT_CONT(" (Warning: Only accurate for version 1.0)");
777 DEBUGOUT_1 (" nMaxSlotIndex %5u\n", buf[4]);
778 DEBUGOUT_2 (" bVoltageSupport %5u %s\n",
779 buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V"
780 : buf[5] == 3? "1.8V":"?"));
782 us = convert_le_u32 (buf+6);
783 DEBUGOUT_1 (" dwProtocols %5u ", us);
785 DEBUGOUT_CONT (" T=0");
788 DEBUGOUT_CONT (" T=1");
792 DEBUGOUT_CONT (" (Invalid values detected)");
795 us = convert_le_u32(buf+10);
796 DEBUGOUT_1 (" dwDefaultClock %5u\n", us);
797 us = convert_le_u32(buf+14);
798 DEBUGOUT_1 (" dwMaxiumumClock %5u\n", us);
799 DEBUGOUT_1 (" bNumClockSupported %5u\n", buf[18]);
800 us = convert_le_u32(buf+19);
801 DEBUGOUT_1 (" dwDataRate %7u bps\n", us);
802 us = convert_le_u32(buf+23);
803 DEBUGOUT_1 (" dwMaxDataRate %7u bps\n", us);
804 DEBUGOUT_1 (" bNumDataRatesSupp. %5u\n", buf[27]);
806 us = convert_le_u32(buf+28);
807 DEBUGOUT_1 (" dwMaxIFSD %5u\n", us);
808 handle->max_ifsd = us;
810 us = convert_le_u32(buf+32);
811 DEBUGOUT_1 (" dwSyncProtocols %08X ", us);
813 DEBUGOUT_CONT ( " 2-wire");
815 DEBUGOUT_CONT ( " 3-wire");
817 DEBUGOUT_CONT ( " I2C");
820 us = convert_le_u32(buf+36);
821 DEBUGOUT_1 (" dwMechanical %08X ", us);
823 DEBUGOUT_CONT (" accept");
825 DEBUGOUT_CONT (" eject");
827 DEBUGOUT_CONT (" capture");
829 DEBUGOUT_CONT (" lock");
832 us = convert_le_u32(buf+40);
833 DEBUGOUT_1 (" dwFeatures %08X\n", us);
836 DEBUGOUT (" Auto configuration based on ATR (assumes auto voltage)\n");
837 handle->auto_voltage = 1;
840 DEBUGOUT (" Auto activation on insert\n");
843 DEBUGOUT (" Auto voltage selection\n");
844 handle->auto_voltage = 1;
847 DEBUGOUT (" Auto clock change\n");
849 DEBUGOUT (" Auto baud rate change\n");
852 DEBUGOUT (" Auto parameter negotiation made by CCID\n");
853 handle->auto_param = 1;
855 else if ((us & 0x0080))
857 DEBUGOUT (" Auto PPS made by CCID\n");
858 handle->auto_pps = 1;
860 if ((us & (0x0040 | 0x0080)) == (0x0040 | 0x0080))
861 DEBUGOUT (" WARNING: conflicting negotiation features\n");
864 DEBUGOUT (" CCID can set ICC in clock stop mode\n");
867 DEBUGOUT (" NAD value other than 0x00 accepted\n");
868 handle->nonnull_nad = 1;
872 DEBUGOUT (" Auto IFSD exchange\n");
873 handle->auto_ifsd = 1;
876 if ((us & 0x00010000))
878 DEBUGOUT (" TPDU level exchange\n");
881 else if ((us & 0x00020000))
883 DEBUGOUT (" Short APDU level exchange\n");
884 handle->apdu_level = 1;
886 else if ((us & 0x00040000))
888 DEBUGOUT (" Short and extended APDU level exchange\n");
889 handle->apdu_level = 2;
891 else if ((us & 0x00070000))
892 DEBUGOUT (" WARNING: conflicting exchange levels\n");
894 us = convert_le_u32(buf+44);
895 DEBUGOUT_1 (" dwMaxCCIDMsgLen %5u\n", us);
896 handle->max_ccid_msglen = us;
898 DEBUGOUT ( " bClassGetResponse ");
900 DEBUGOUT_CONT ("echo\n");
902 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
904 DEBUGOUT ( " bClassEnvelope ");
906 DEBUGOUT_CONT ("echo\n");
908 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
910 DEBUGOUT ( " wlcdLayout ");
911 if (!buf[50] && !buf[51])
912 DEBUGOUT_CONT ("none\n");
914 DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]);
916 DEBUGOUT_1 (" bPINSupport %5u ", buf[52]);
919 DEBUGOUT_CONT ( " verification");
920 handle->has_pinpad |= 1;
924 DEBUGOUT_CONT ( " modification");
925 handle->has_pinpad |= 2;
929 DEBUGOUT_1 (" bMaxCCIDBusySlots %5u\n", buf[53]);
934 for (i=54; i < buf[0]-54; i++)
935 DEBUGOUT_CONT_1 (" %02X", buf[i]);
939 if (!have_t1 || !(have_tpdu || handle->apdu_level))
941 DEBUGOUT ("this drivers requires that the reader supports T=1, "
942 "TPDU or APDU level exchange - this is not available\n");
947 /* SCM drivers get stuck in their internal USB stack if they try to
948 send a frame of n*wMaxPacketSize back to us. Given that
949 wMaxPacketSize is 64 for these readers we set the IFSD to a value
951 64 - 10 CCID header - 4 T1frame - 2 reserved = 48
958 0x5117 - SCR 3320 USB ID-000 reader
959 seems to be very slow but enabling this workaround boosts the
960 performance to a a more or less acceptable level (tested by David).
963 if (handle->id_vendor == VENDOR_SCM
964 && handle->max_ifsd > 48
965 && ( (handle->id_product == SCM_SCR331 && bcd_device < 0x0516)
966 ||(handle->id_product == SCM_SCR331DI && bcd_device < 0x0620)
967 ||(handle->id_product == SCM_SCR335 && bcd_device < 0x0514)
968 ||(handle->id_product == SCM_SPR532 && bcd_device < 0x0504)
969 ||(handle->id_product == SCM_SCR3320 && bcd_device < 0x0522)
972 DEBUGOUT ("enabling workaround for buggy SCM readers\n");
973 handle->max_ifsd = 48;
976 if (handle->id_vendor == VENDOR_GEMPC)
978 DEBUGOUT ("enabling product quirk: disable non-null NAD\n");
979 handle->nonnull_nad = 0;
987 get_escaped_usb_string (libusb_device_handle *idev, int idx,
988 const char *prefix, const char *suffix)
991 unsigned char buf[280];
1000 /* Fixme: The next line is for the current Valgrid without support
1002 memset (buf, 0, sizeof buf);
1004 /* First get the list of supported languages and use the first one.
1005 If we do don't find it we try to use English. Note that this is
1006 all in a 2 bute Unicode encoding using little endian. */
1007 rc = libusb_control_transfer (idev, LIBUSB_ENDPOINT_IN,
1008 LIBUSB_REQUEST_GET_DESCRIPTOR,
1009 (LIBUSB_DT_STRING << 8), 0,
1010 (char*)buf, sizeof buf, 1000 /* ms timeout */);
1012 langid = 0x0409; /* English. */
1014 langid = (buf[3] << 8) | buf[2];
1016 rc = libusb_control_transfer (idev, LIBUSB_ENDPOINT_IN,
1017 LIBUSB_REQUEST_GET_DESCRIPTOR,
1018 (LIBUSB_DT_STRING << 8) + idx, langid,
1019 (char*)buf, sizeof buf, 1000 /* ms timeout */);
1020 if (rc < 2 || buf[1] != LIBUSB_DT_STRING)
1021 return NULL; /* Error or not a string. */
1024 return NULL; /* Larger than our buffer. */
1026 for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2)
1029 n++; /* High byte set. */
1030 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
1036 result = malloc (strlen (prefix) + n + strlen (suffix) + 1);
1040 strcpy (result, prefix);
1041 n = strlen (prefix);
1042 for (s=buf+2, i=2; i+1 < len; i += 2, s += 2)
1045 result[n++] = '\xff'; /* High byte set. */
1046 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
1048 sprintf (result+n, "%%%02X", *s);
1054 strcpy (result+n, suffix);
1059 /* This function creates an reader id to be used to find the same
1060 physical reader after a reset. It returns an allocated and possibly
1061 percent escaped string or NULL if not enough memory is available. */
1063 make_reader_id (libusb_device_handle *idev,
1064 unsigned int vendor, unsigned int product,
1065 unsigned char serialno_index)
1070 sprintf (prefix, "%04X:%04X:", (vendor & 0xffff), (product & 0xffff));
1071 rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0");
1074 rid = malloc (strlen (prefix) + 3 + 1);
1077 strcpy (rid, prefix);
1078 strcat (rid, "X:0");
1084 /* Helper to find the endpoint from an interface descriptor. */
1086 find_endpoint (const struct libusb_interface_descriptor *ifcdesc, int mode)
1089 int want_bulk_in = 0;
1092 want_bulk_in = 0x80;
1093 for (no=0; no < ifcdesc->bNumEndpoints; no++)
1095 const struct libusb_endpoint_descriptor *ep = ifcdesc->endpoint + no;
1096 if (ep->bDescriptorType != LIBUSB_DT_ENDPOINT)
1099 && ((ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
1100 == LIBUSB_TRANSFER_TYPE_INTERRUPT)
1101 && (ep->bEndpointAddress & 0x80))
1102 return ep->bEndpointAddress;
1103 else if ((mode == 0 || mode == 1)
1104 && ((ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
1105 == LIBUSB_TRANSFER_TYPE_BULK)
1106 && (ep->bEndpointAddress & 0x80) == want_bulk_in)
1107 return ep->bEndpointAddress;
1114 /* Helper for scan_or_find_devices. This function returns true if a
1115 requested device has been found or the caller should stop scanning
1116 for other reasons. */
1118 scan_or_find_usb_device (int scan_mode,
1119 int readerno, int *count, char **rid_list,
1120 const char *readerid,
1121 struct libusb_device *dev,
1123 struct libusb_device_descriptor *desc,
1124 libusb_device_handle **r_idev,
1125 unsigned char **ifcdesc_extra,
1126 size_t *ifcdesc_extra_len,
1127 int *interface_number, int *setting_number,
1128 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr)
1132 const struct libusb_interface_descriptor *ifcdesc;
1134 libusb_device_handle *idev = NULL;
1136 struct libusb_config_descriptor *config;
1138 err = libusb_get_device_descriptor (dev, desc);
1144 err = libusb_get_active_config_descriptor (dev, &config);
1148 for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
1149 for (set_no=0; set_no < config->interface[ifc_no].num_altsetting; set_no++)
1151 ifcdesc = (config->interface[ifc_no].altsetting + set_no);
1152 /* The second condition is for older SCM SPR 532 who did
1153 not know about the assigned CCID class. The third
1154 condition does the same for a Cherry SmartTerminal
1155 ST-2000. Instead of trying to interpret the strings
1156 we simply check the product ID. */
1157 if (ifcdesc && ifcdesc->extra
1158 && ((ifcdesc->bInterfaceClass == 11
1159 && ifcdesc->bInterfaceSubClass == 0
1160 && ifcdesc->bInterfaceProtocol == 0)
1161 || (ifcdesc->bInterfaceClass == 255
1162 && desc->idVendor == VENDOR_SCM
1163 && desc->idProduct == SCM_SPR532)
1164 || (ifcdesc->bInterfaceClass == 255
1165 && desc->idVendor == VENDOR_CHERRY
1166 && desc->idProduct == CHERRY_ST2000)))
1169 if (!scan_mode && ((readerno > 0 && readerno != *count - 1)))
1172 err = libusb_open (dev, &idev);
1175 DEBUGOUT_1 ("usb_open failed: %s\n", libusb_error_name (err));
1176 continue; /* with next setting. */
1179 rid = make_reader_id (idev, desc->idVendor, desc->idProduct,
1180 desc->iSerialNumber);
1183 libusb_free_config_descriptor (config);
1187 if (!scan_mode && readerno == -1 && readerid
1188 && strncmp (rid, readerid, strlen (readerid)))
1195 /* We are collecting infos about all
1196 available CCID readers. Store them and
1198 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n", *count, rid);
1199 p = malloc ((*rid_list? strlen (*rid_list):0) + 1
1200 + strlen (rid) + 1);
1206 strcat (p, *rid_list);
1213 else /* Out of memory. */
1215 libusb_free_config_descriptor (config);
1222 /* We found the requested reader. */
1223 if (ifcdesc_extra && ifcdesc_extra_len)
1225 *ifcdesc_extra = malloc (ifcdesc->extra_length);
1226 if (!*ifcdesc_extra)
1228 libusb_close (idev);
1230 libusb_free_config_descriptor (config);
1231 return 1; /* Out of core. */
1233 memcpy (*ifcdesc_extra, ifcdesc->extra,
1234 ifcdesc->extra_length);
1235 *ifcdesc_extra_len = ifcdesc->extra_length;
1238 if (interface_number)
1239 *interface_number = ifc_no;
1242 *setting_number = set_no;
1245 *ep_bulk_out = find_endpoint (ifcdesc, 0);
1247 *ep_bulk_in = find_endpoint (ifcdesc, 1);
1249 *ep_intr = find_endpoint (ifcdesc, 2);
1260 libusb_free_config_descriptor (config);
1261 return 1; /* Found requested device. */
1265 libusb_close (idev);
1270 libusb_free_config_descriptor (config);
1275 /* Combination function to either scan all CCID devices or to find and
1276 open one specific device.
1278 The function returns 0 if a reader has been found or when a scan
1279 returned without error.
1281 With READERNO = -1 and READERID is NULL, scan mode is used and
1282 R_RID should be the address where to store the list of reader_ids
1283 we found. If on return this list is empty, no CCID device has been
1284 found; otherwise it points to an allocated linked list of reader
1285 IDs. Note that in this mode the function always returns NULL.
1287 With READERNO >= 0 or READERID is not NULL find mode is used. This
1288 uses the same algorithm as the scan mode but stops and returns at
1289 the entry number READERNO and return the handle for the the opened
1290 USB device. If R_RID is not NULL it will receive the reader ID of
1291 that device. If R_DEV is not NULL it will the device pointer of
1292 that device. If IFCDESC_EXTRA is NOT NULL it will receive a
1293 malloced copy of the interfaces "extra: data filed;
1294 IFCDESC_EXTRA_LEN receive the length of this field. If there is
1295 no reader with number READERNO or that reader is not usable by our
1296 implementation NULL will be returned. The caller must close a
1297 returned USB device handle and free (if not passed as NULL) the
1298 returned reader ID info as well as the IFCDESC_EXTRA. On error
1299 NULL will get stored at R_RID, R_DEV, IFCDESC_EXTRA and
1300 IFCDESC_EXTRA_LEN. With READERID being -1 the function stops if
1301 the READERID was found.
1303 If R_FD is not -1 on return the device is not using USB for
1304 transport but the device associated with that file descriptor. In
1305 this case INTERFACE will receive the transport type and the other
1306 USB specific return values are not used; the return value is
1309 Note that the first entry of the returned reader ID list in scan mode
1310 corresponds with a READERNO of 0 in find mode.
1313 scan_or_find_devices (int readerno, const char *readerid,
1315 struct libusb_device_descriptor *r_desc,
1316 unsigned char **ifcdesc_extra,
1317 size_t *ifcdesc_extra_len,
1318 int *interface_number, int *setting_number,
1319 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr,
1320 libusb_device_handle **r_idev,
1323 char *rid_list = NULL;
1325 libusb_device **dev_list = NULL;
1327 libusb_device_handle *idev = NULL;
1328 int scan_mode = (readerno == -1 && !readerid);
1331 struct libusb_device_descriptor desc;
1333 /* Set return values to a default. */
1337 *ifcdesc_extra = NULL;
1338 if (ifcdesc_extra_len)
1339 *ifcdesc_extra_len = 0;
1340 if (interface_number)
1341 *interface_number = 0;
1343 *setting_number = 0;
1349 /* See whether we want scan or find mode. */
1355 n = libusb_get_device_list (NULL, &dev_list);
1357 for (i = 0; i < n; i++)
1360 if (scan_or_find_usb_device (scan_mode, readerno, &count, &rid_list,
1368 interface_number, setting_number,
1369 ep_bulk_out, ep_bulk_in, ep_intr))
1371 libusb_free_device_list (dev_list, 1);
1372 /* Found requested device or out of core. */
1376 return -1; /* error */
1380 memcpy (r_desc, &desc, sizeof (struct libusb_device_descriptor));
1385 libusb_free_device_list (dev_list, 1);
1387 /* Now check whether there are any devices with special transport types. */
1388 for (i=0; transports[i].name; i++)
1393 fd = open (transports[i].name, O_RDWR);
1394 if (fd == -1 && scan_mode && errno == EBUSY)
1396 /* Ignore this error in scan mode because it indicates that
1397 the device exists but is already open (most likely by us)
1398 and thus in general suitable as a reader. */
1402 DEBUGOUT_2 ("failed to open '%s': %s\n",
1403 transports[i].name, strerror (errno));
1407 rid = malloc (strlen (transports[i].name) + 30 + 10);
1413 return -1; /* Error. */
1415 sprintf (rid, "0000:%04X:%s:0", transports[i].type, transports[i].name);
1418 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n", count, rid);
1419 p = malloc ((rid_list? strlen (rid_list):0) + 1 + strlen (rid) + 1);
1426 return -1; /* Error. */
1431 strcat (p, rid_list);
1439 else if (!readerno ||
1440 (readerno < 0 && readerid && !strcmp (readerid, rid)))
1442 /* Found requested device. */
1443 if (interface_number)
1444 *interface_number = transports[i].type;
1451 return 0; /* Okay, found device */
1453 else /* This is not yet the reader we want. */
1473 /* Set the level of debugging to LEVEL and return the old level. -1
1474 just returns the old level. A level of 0 disables debugging, 1
1475 enables debugging, 2 enables additional tracing of the T=1
1476 protocol, 3 additionally enables debugging for GetSlotStatus, other
1477 values are not yet defined.
1479 Note that libusb may provide its own debugging feature which is
1480 enabled by setting the envvar USB_DEBUG. */
1482 ccid_set_debug_level (int level)
1484 int old = debug_level;
1486 debug_level = level;
1492 ccid_get_reader_list (void)
1496 if (!initialized_usb)
1499 initialized_usb = 1;
1502 if (scan_or_find_devices (-1, NULL, &reader_list, NULL, NULL, NULL, NULL,
1503 NULL, NULL, NULL, NULL, NULL, NULL))
1504 return NULL; /* Error. */
1509 /* Vendor specific custom initialization. */
1511 ccid_vendor_specific_init (ccid_driver_t handle)
1513 if (handle->id_vendor == VENDOR_VEGA && handle->id_product == VEGA_ALPHA)
1517 * Vega alpha has a feature to show retry counter on the pinpad
1518 * display. But it assumes that the card returns the value of
1519 * retry counter by VERIFY with empty data (return code of
1520 * 63Cx). Unfortunately, existing OpenPGP cards don't support
1521 * VERIFY command with empty data. This vendor specific command
1522 * sequence is to disable the feature.
1524 const unsigned char cmd[] = { '\xb5', '\x01', '\x00', '\x03', '\x00' };
1526 r = send_escape_cmd (handle, cmd, sizeof (cmd), NULL, 0, NULL);
1527 if (r != 0 && r != CCID_DRIVER_ERR_CARD_INACTIVE
1528 && r != CCID_DRIVER_ERR_NO_CARD)
1536 #define MAX_DEVICE 4 /* See MAX_READER in apdu.c. */
1538 struct ccid_dev_table {
1539 int n; /* Index to ccid_usb_dev_list */
1541 int interface_number;
1543 unsigned char *ifcdesc_extra;
1547 size_t ifcdesc_extra_len;
1550 static libusb_device **ccid_usb_dev_list;
1551 static struct ccid_dev_table ccid_dev_table[MAX_DEVICE];
1554 ccid_dev_scan (int *idx_max_p, struct ccid_dev_table **t_p)
1564 if (!initialized_usb)
1567 initialized_usb = 1;
1570 n = libusb_get_device_list (NULL, &ccid_usb_dev_list);
1571 for (i = 0; i < n; i++)
1573 struct libusb_config_descriptor *config;
1574 struct libusb_device_descriptor desc;
1576 dev = ccid_usb_dev_list[i];
1578 if (libusb_get_device_descriptor (dev, &desc))
1581 if (libusb_get_active_config_descriptor (dev, &config))
1584 for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
1585 for (set_no=0; set_no < config->interface[ifc_no].num_altsetting;
1588 const struct libusb_interface_descriptor *ifcdesc;
1590 ifcdesc = &config->interface[ifc_no].altsetting[set_no];
1591 /* The second condition is for older SCM SPR 532 who did
1592 not know about the assigned CCID class. The third
1593 condition does the same for a Cherry SmartTerminal
1594 ST-2000. Instead of trying to interpret the strings
1595 we simply check the product ID. */
1596 if (ifcdesc && ifcdesc->extra
1597 && ((ifcdesc->bInterfaceClass == 11
1598 && ifcdesc->bInterfaceSubClass == 0
1599 && ifcdesc->bInterfaceProtocol == 0)
1600 || (ifcdesc->bInterfaceClass == 255
1601 && desc.idVendor == VENDOR_SCM
1602 && desc.idProduct == SCM_SPR532)
1603 || (ifcdesc->bInterfaceClass == 255
1604 && desc.idVendor == VENDOR_CHERRY
1605 && desc.idProduct == CHERRY_ST2000)))
1607 /* Found a reader. */
1608 unsigned char *ifcdesc_extra;
1610 ifcdesc_extra = malloc (ifcdesc->extra_length);
1613 err = gpg_error_from_syserror ();
1614 libusb_free_config_descriptor (config);
1617 memcpy (ifcdesc_extra, ifcdesc->extra, ifcdesc->extra_length);
1619 ccid_dev_table[idx].transport = TRANSPORT_USB;
1620 ccid_dev_table[idx].n = i;
1621 ccid_dev_table[idx].interface_number = ifc_no;
1622 ccid_dev_table[idx].setting_number = set_no;
1623 ccid_dev_table[idx].ifcdesc_extra = ifcdesc_extra;
1624 ccid_dev_table[idx].ifcdesc_extra_len = ifcdesc->extra_length;
1625 ccid_dev_table[idx].ep_bulk_out = find_endpoint (ifcdesc, 0);
1626 ccid_dev_table[idx].ep_bulk_in = find_endpoint (ifcdesc, 1);
1627 ccid_dev_table[idx].ep_intr = find_endpoint (ifcdesc, 2);
1630 if (idx >= MAX_DEVICE)
1632 libusb_free_config_descriptor (config);
1639 libusb_free_config_descriptor (config);
1642 /* Now check whether there are any devices with special transport types. */
1643 for (i=0; transports[i].name; i++)
1645 if (access (transports[i].name, (R_OK|W_OK)) == 0)
1647 /* Found a device. */
1648 DEBUGOUT_1 ("Found CCID reader %d\n", idx);
1650 ccid_dev_table[idx].transport = TRANSPORT_CM4040;
1651 ccid_dev_table[idx].n = i;
1652 ccid_dev_table[idx].interface_number = 0;
1653 ccid_dev_table[idx].setting_number = 0;
1654 ccid_dev_table[idx].ifcdesc_extra = NULL;
1655 ccid_dev_table[idx].ifcdesc_extra_len = 0;
1656 ccid_dev_table[idx].ep_bulk_out = 0;
1657 ccid_dev_table[idx].ep_bulk_in = 0;
1658 ccid_dev_table[idx].ep_intr = 0;
1661 if (idx >= MAX_DEVICE)
1672 for (i = 0; i < idx; i++)
1674 free (ccid_dev_table[idx].ifcdesc_extra);
1675 ccid_dev_table[idx].transport = 0;
1676 ccid_dev_table[idx].n = 0;
1677 ccid_dev_table[idx].interface_number = 0;
1678 ccid_dev_table[idx].setting_number = 0;
1679 ccid_dev_table[idx].ifcdesc_extra = NULL;
1680 ccid_dev_table[idx].ifcdesc_extra_len = 0;
1681 ccid_dev_table[idx].ep_bulk_out = 0;
1682 ccid_dev_table[idx].ep_bulk_in = 0;
1683 ccid_dev_table[idx].ep_intr = 0;
1685 libusb_free_device_list (ccid_usb_dev_list, 1);
1686 ccid_usb_dev_list = NULL;
1692 *t_p = ccid_dev_table;
1701 ccid_dev_scan_finish (struct ccid_dev_table *tbl, int max)
1705 for (i = 0; i < max; i++)
1707 free (tbl[i].ifcdesc_extra);
1708 tbl[i].transport = 0;
1710 tbl[i].interface_number = 0;
1711 tbl[i].setting_number = 0;
1712 tbl[i].ifcdesc_extra = NULL;
1713 tbl[i].ifcdesc_extra_len = 0;
1714 tbl[i].ep_bulk_out = 0;
1715 tbl[i].ep_bulk_in = 0;
1718 libusb_free_device_list (ccid_usb_dev_list, 1);
1719 ccid_usb_dev_list = NULL;
1723 ccid_get_BAI (int idx, struct ccid_dev_table *tbl)
1726 int bus, addr, intf;
1729 if (tbl[idx].transport == TRANSPORT_USB)
1734 dev = ccid_usb_dev_list[n];
1736 bus = libusb_get_bus_number (dev);
1737 addr = libusb_get_device_address (dev);
1738 intf = tbl[idx].interface_number;
1739 bai = (bus << 16) | (addr << 8) | intf;
1744 bai = 0xFFFF0000 | n;
1751 ccid_compare_BAI (ccid_driver_t handle, unsigned int bai)
1753 return handle->bai == bai;
1757 ccid_open_usb_reader (const char *spec_reader_name,
1758 int idx, struct ccid_dev_table *ccid_table,
1759 ccid_driver_t *handle, char **rdrname_p)
1762 libusb_device_handle *idev = NULL;
1766 struct libusb_device_descriptor desc;
1771 n = ccid_table[idx].n;
1772 ifc_no = ccid_table[idx].interface_number;
1773 set_no = ccid_table[idx].setting_number;
1775 dev = ccid_usb_dev_list[n];
1776 bus = libusb_get_bus_number (dev);
1777 addr = libusb_get_device_address (dev);
1778 bai = (bus << 16) | (addr << 8) | ifc_no;
1780 rc = libusb_open (dev, &idev);
1783 DEBUGOUT_1 ("usb_open failed: %s\n", libusb_error_name (rc));
1789 rc = libusb_get_device_descriptor (dev, &desc);
1792 libusb_close (idev);
1798 rid = make_reader_id (idev, desc.idVendor, desc.idProduct,
1799 desc.iSerialNumber);
1801 /* Check to see if reader name matches the spec. */
1802 if (spec_reader_name
1803 && strncmp (rid, spec_reader_name, strlen (spec_reader_name)))
1805 DEBUGOUT ("device not matched\n");
1806 rc = CCID_DRIVER_ERR_NO_READER;
1810 (*handle)->id_vendor = desc.idVendor;
1811 (*handle)->id_product = desc.idProduct;
1812 (*handle)->idev = idev;
1813 (*handle)->dev_fd = -1;
1814 (*handle)->bai = bai;
1815 (*handle)->ifc_no = ifc_no;
1816 (*handle)->ep_bulk_out = ccid_table[idx].ep_bulk_out;
1817 (*handle)->ep_bulk_in = ccid_table[idx].ep_bulk_in;
1818 (*handle)->ep_intr = ccid_table[idx].ep_intr;
1820 DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n", idx, rid);
1822 if (parse_ccid_descriptor (*handle, desc.bcdDevice,
1823 ccid_table[idx].ifcdesc_extra,
1824 ccid_table[idx].ifcdesc_extra_len))
1826 DEBUGOUT ("device not supported\n");
1827 rc = CCID_DRIVER_ERR_NO_READER;
1831 rc = libusb_claim_interface (idev, ifc_no);
1834 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1835 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1841 rc = libusb_set_interface_alt_setting (idev, ifc_no, set_no);
1844 DEBUGOUT_1 ("usb_set_interface_alt_setting failed: %d\n", rc);
1845 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1850 rc = ccid_vendor_specific_init (*handle);
1856 libusb_close (idev);
1871 /* Open the reader with the internal number READERNO and return a
1872 pointer to be used as handle in HANDLE. Returns 0 on success. */
1874 ccid_open_reader (const char *spec_reader_name,
1875 int idx, struct ccid_dev_table *ccid_table,
1876 ccid_driver_t *handle, char **rdrname_p)
1882 *handle = calloc (1, sizeof **handle);
1885 DEBUGOUT ("out of memory\n");
1886 return CCID_DRIVER_ERR_OUT_OF_CORE;
1889 if (ccid_table[idx].transport == TRANSPORT_USB)
1890 return ccid_open_usb_reader (spec_reader_name, idx, ccid_table,
1893 /* Special transport support. */
1895 n = ccid_table[idx].n;
1896 fd = open (transports[n].name, O_RDWR);
1899 DEBUGOUT_2 ("failed to open '%s': %s\n",
1900 transports[n].name, strerror (errno));
1906 rid = malloc (strlen (transports[n].name) + 30 + 10);
1912 return -1; /* Error. */
1915 sprintf (rid, "0000:%04X:%s:0", transports[n].type, transports[n].name);
1917 /* Check to see if reader name matches the spec. */
1918 if (spec_reader_name
1919 && strncmp (rid, spec_reader_name, strlen (spec_reader_name)))
1921 DEBUGOUT ("device not matched\n");
1929 (*handle)->id_vendor = 0;
1930 (*handle)->id_product = transports[n].type;
1931 (*handle)->idev = NULL;
1932 (*handle)->dev_fd = fd;
1933 (*handle)->bai = 0xFFFF0000 | n;
1934 prepare_special_transport (*handle);
1945 do_close_reader (ccid_driver_t handle)
1948 unsigned char msg[100];
1950 unsigned char seqno;
1952 if (!handle->powered_off)
1954 msg[0] = PC_to_RDR_IccPowerOff;
1955 msg[5] = 0; /* slot */
1956 msg[6] = seqno = handle->seqno++;
1957 msg[7] = 0; /* RFU */
1958 msg[8] = 0; /* RFU */
1959 msg[9] = 0; /* RFU */
1960 set_msg_len (msg, 0);
1963 rc = bulk_out (handle, msg, msglen, 0);
1965 bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1967 handle->powered_off = 1;
1971 libusb_release_interface (handle->idev, handle->ifc_no);
1972 libusb_close (handle->idev);
1973 handle->idev = NULL;
1975 if (handle->dev_fd != -1)
1977 close (handle->dev_fd);
1978 handle->dev_fd = -1;
1984 ccid_set_progress_cb (ccid_driver_t handle,
1985 void (*cb)(void *, const char *, int, int, int),
1989 return CCID_DRIVER_ERR_INV_VALUE;
1991 handle->progress_cb = cb;
1992 handle->progress_cb_arg = cb_arg;
1997 /* Close the reader HANDLE. */
1999 ccid_close_reader (ccid_driver_t handle)
2001 if (!handle || (!handle->idev && handle->dev_fd == -1))
2004 do_close_reader (handle);
2010 /* Return False if a card is present and powered. */
2012 ccid_check_card_presence (ccid_driver_t handle)
2014 (void)handle; /* Not yet implemented. */
2019 /* Write NBYTES of BUF to file descriptor FD. */
2021 writen (int fd, const void *buf, size_t nbytes)
2023 size_t nleft = nbytes;
2028 nwritten = write (fd, buf, nleft);
2037 buf = (const char*)buf + nwritten;
2044 /* Write a MSG of length MSGLEN to the designated bulk out endpoint.
2045 Returns 0 on success. */
2047 bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
2052 /* No need to continue and clutter the log with USB write error
2053 messages after we got the first ENODEV. */
2054 if (handle->enodev_seen)
2055 return CCID_DRIVER_ERR_NO_READER;
2057 if (debug_level && (!no_debug || debug_level >= 3))
2059 switch (msglen? msg[0]:0)
2061 case PC_to_RDR_IccPowerOn:
2062 print_p2r_iccpoweron (msg, msglen);
2064 case PC_to_RDR_IccPowerOff:
2065 print_p2r_iccpoweroff (msg, msglen);
2067 case PC_to_RDR_GetSlotStatus:
2068 print_p2r_getslotstatus (msg, msglen);
2070 case PC_to_RDR_XfrBlock:
2071 print_p2r_xfrblock (msg, msglen);
2073 case PC_to_RDR_GetParameters:
2074 print_p2r_getparameters (msg, msglen);
2076 case PC_to_RDR_ResetParameters:
2077 print_p2r_resetparameters (msg, msglen);
2079 case PC_to_RDR_SetParameters:
2080 print_p2r_setparameters (msg, msglen);
2082 case PC_to_RDR_Escape:
2083 print_p2r_escape (msg, msglen);
2085 case PC_to_RDR_IccClock:
2086 print_p2r_iccclock (msg, msglen);
2088 case PC_to_RDR_T0APDU:
2089 print_p2r_to0apdu (msg, msglen);
2091 case PC_to_RDR_Secure:
2092 print_p2r_secure (msg, msglen);
2094 case PC_to_RDR_Mechanical:
2095 print_p2r_mechanical (msg, msglen);
2097 case PC_to_RDR_Abort:
2098 print_p2r_abort (msg, msglen);
2100 case PC_to_RDR_SetDataRate:
2101 print_p2r_setdatarate (msg, msglen);
2104 print_p2r_unknown (msg, msglen);
2113 rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_out,
2114 (char*)msg, msglen, &transferred,
2115 5000 /* ms timeout */);
2116 if (rc == 0 && transferred == msglen)
2121 DEBUGOUT_1 ("usb_bulk_write error: %s\n", libusb_error_name (rc));
2122 if (rc == LIBUSB_ERROR_NO_DEVICE)
2124 handle->enodev_seen = 1;
2125 return CCID_DRIVER_ERR_NO_READER;
2131 rc = writen (handle->dev_fd, msg, msglen);
2134 DEBUGOUT_2 ("writen to %d failed: %s\n",
2135 handle->dev_fd, strerror (errno));
2138 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2142 /* Read a maximum of LENGTH bytes from the bulk in endpoint into
2143 BUFFER and return the actual read number if bytes in NREAD. SEQNO
2144 is the sequence number used to send the request and EXPECTED_TYPE
2145 the type of message we expect. Does checks on the ccid
2146 header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to
2147 avoid debug messages in case of no error; this can be overriden
2148 with a glibal debug level of at least 3. Returns 0 on success. */
2150 bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
2151 size_t *nread, int expected_type, int seqno, int timeout,
2156 int eagain_retries = 0;
2158 /* Fixme: The next line for the current Valgrind without support
2160 memset (buffer, 0, length);
2164 rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_in,
2165 (char*)buffer, length, &msglen, timeout);
2168 DEBUGOUT_1 ("usb_bulk_read error: %s\n", libusb_error_name (rc));
2169 if (rc == LIBUSB_ERROR_NO_DEVICE)
2171 handle->enodev_seen = 1;
2172 return CCID_DRIVER_ERR_NO_READER;
2175 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2178 return CCID_DRIVER_ERR_INV_VALUE; /* Faulty libusb. */
2183 rc = read (handle->dev_fd, buffer, length);
2187 DEBUGOUT_2 ("read from %d failed: %s\n",
2188 handle->dev_fd, strerror (rc));
2189 if (rc == EAGAIN && eagain_retries++ < 5)
2194 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2196 *nread = msglen = rc;
2202 DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen);
2203 abort_cmd (handle, seqno);
2204 return CCID_DRIVER_ERR_INV_VALUE;
2208 DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]);
2209 return CCID_DRIVER_ERR_INV_VALUE;
2211 if (buffer[6] != seqno)
2213 DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n",
2215 /* Retry until we are synced again. */
2219 /* We need to handle the time extension request before we check that
2220 we got the expected message type. This is in particular required
2221 for the Cherry keyboard which sends a time extension request for
2223 if ( !(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80)
2225 /* Card present and active, time extension requested. */
2226 DEBUGOUT_2 ("time extension requested (%02X,%02X)\n",
2227 buffer[7], buffer[8]);
2231 if (buffer[0] != expected_type)
2233 DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]);
2234 abort_cmd (handle, seqno);
2235 return CCID_DRIVER_ERR_INV_VALUE;
2238 if (debug_level && (!no_debug || debug_level >= 3))
2242 case RDR_to_PC_DataBlock:
2243 print_r2p_datablock (buffer, msglen);
2245 case RDR_to_PC_SlotStatus:
2246 print_r2p_slotstatus (buffer, msglen);
2248 case RDR_to_PC_Parameters:
2249 print_r2p_parameters (buffer, msglen);
2251 case RDR_to_PC_Escape:
2252 print_r2p_escape (buffer, msglen);
2254 case RDR_to_PC_DataRate:
2255 print_r2p_datarate (buffer, msglen);
2258 print_r2p_unknown (buffer, msglen);
2262 if (CCID_COMMAND_FAILED (buffer))
2263 print_command_failed (buffer);
2265 /* Check whether a card is at all available. Note: If you add new
2266 error codes here, check whether they need to be ignored in
2268 switch ((buffer[7] & 0x03))
2270 case 0: /* no error */ break;
2271 case 1: return CCID_DRIVER_ERR_CARD_INACTIVE;
2272 case 2: return CCID_DRIVER_ERR_NO_CARD;
2273 case 3: /* RFU */ break;
2280 /* Send an abort sequence and wait until everything settled. */
2282 abort_cmd (ccid_driver_t handle, int seqno)
2286 unsigned char msg[100];
2291 /* I don't know how to send an abort to non-USB devices. */
2292 rc = CCID_DRIVER_ERR_NOT_SUPPORTED;
2296 DEBUGOUT_1 ("sending abort sequence for seqno %d\n", seqno);
2297 /* Send the abort command to the control pipe. Note that we don't
2298 need to keep track of sent abort commands because there should
2299 never be another thread using the same slot concurrently. */
2300 rc = libusb_control_transfer (handle->idev,
2301 0x21,/* bmRequestType: host-to-device,
2302 class specific, to interface. */
2304 (seqno << 8 | 0 /* slot */),
2307 1000 /* ms timeout */);
2310 DEBUGOUT_1 ("usb_control_msg error: %s\n", libusb_error_name (rc));
2311 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2314 /* Now send the abort command to the bulk out pipe using the same
2315 SEQNO and SLOT. Do this in a loop to so that all seqno are
2317 seqno--; /* Adjust for next increment. */
2323 msg[0] = PC_to_RDR_Abort;
2324 msg[5] = 0; /* slot */
2326 msg[7] = 0; /* RFU */
2327 msg[8] = 0; /* RFU */
2328 msg[9] = 0; /* RFU */
2330 set_msg_len (msg, 0);
2332 rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_out,
2333 (char*)msg, msglen, &transferred,
2334 5000 /* ms timeout */);
2335 if (rc == 0 && transferred == msglen)
2338 DEBUGOUT_1 ("usb_bulk_write error in abort_cmd: %s\n",
2339 libusb_error_name (rc));
2344 rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_in,
2345 (char*)msg, sizeof msg, &msglen,
2346 5000 /*ms timeout*/);
2349 DEBUGOUT_1 ("usb_bulk_read error in abort_cmd: %s\n",
2350 libusb_error_name (rc));
2351 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2356 DEBUGOUT_1 ("bulk-in msg in abort_cmd too short (%u)\n",
2357 (unsigned int)msglen);
2358 return CCID_DRIVER_ERR_INV_VALUE;
2362 DEBUGOUT_1 ("unexpected bulk-in slot (%d) in abort_cmd\n", msg[5]);
2363 return CCID_DRIVER_ERR_INV_VALUE;
2366 DEBUGOUT_3 ("status: %02X error: %02X octet[9]: %02X\n",
2367 msg[7], msg[8], msg[9]);
2368 if (CCID_COMMAND_FAILED (msg))
2369 print_command_failed (msg);
2371 while (msg[0] != RDR_to_PC_SlotStatus && msg[5] != 0 && msg[6] != seqno);
2373 handle->seqno = ((seqno + 1) & 0xff);
2374 DEBUGOUT ("sending abort sequence succeeded\n");
2380 /* Note that this function won't return the error codes NO_CARD or
2381 CARD_INACTIVE. IF RESULT is not NULL, the result from the
2382 operation will get returned in RESULT and its length in RESULTLEN.
2383 If the response is larger than RESULTMAX, an error is returned and
2384 the required buffer length returned in RESULTLEN. */
2386 send_escape_cmd (ccid_driver_t handle,
2387 const unsigned char *data, size_t datalen,
2388 unsigned char *result, size_t resultmax, size_t *resultlen)
2391 unsigned char msg[100];
2393 unsigned char seqno;
2398 if (datalen > sizeof msg - 10)
2399 return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large. */
2401 msg[0] = PC_to_RDR_Escape;
2402 msg[5] = 0; /* slot */
2403 msg[6] = seqno = handle->seqno++;
2404 msg[7] = 0; /* RFU */
2405 msg[8] = 0; /* RFU */
2406 msg[9] = 0; /* RFU */
2407 memcpy (msg+10, data, datalen);
2408 msglen = 10 + datalen;
2409 set_msg_len (msg, datalen);
2411 rc = bulk_out (handle, msg, msglen, 0);
2414 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape,
2419 /* We need to ignore certain errorcode here. */
2421 case CCID_DRIVER_ERR_CARD_INACTIVE:
2422 case CCID_DRIVER_ERR_NO_CARD:
2424 if (msglen > resultmax)
2425 rc = CCID_DRIVER_ERR_INV_VALUE; /* Response too large. */
2428 memcpy (result, msg, msglen);
2429 *resultlen = msglen;
2443 ccid_transceive_escape (ccid_driver_t handle,
2444 const unsigned char *data, size_t datalen,
2445 unsigned char *resp, size_t maxresplen, size_t *nresp)
2447 return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp);
2454 ccid_poll (ccid_driver_t handle)
2457 unsigned char msg[10];
2463 rc = libusb_interrupt_transfer (handle->idev, handle->ep_intr,
2464 (char*)msg, sizeof msg, &msglen,
2465 0 /* ms timeout */ );
2466 if (rc == LIBUSB_ERROR_TIMEOUT)
2474 DEBUGOUT_1 ("usb_intr_read error: %s\n", libusb_error_name (rc));
2475 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2480 DEBUGOUT ("intr-in msg too short\n");
2481 return CCID_DRIVER_ERR_INV_VALUE;
2484 if (msg[0] == RDR_to_PC_NotifySlotChange)
2486 DEBUGOUT ("notify slot change:");
2487 for (i=1; i < msglen; i++)
2488 for (j=0; j < 4; j++)
2489 DEBUGOUT_CONT_3 (" %d:%c%c",
2491 (msg[i] & (1<<(j*2)))? 'p':'-',
2492 (msg[i] & (2<<(j*2)))? '*':' ');
2495 else if (msg[0] == RDR_to_PC_HardwareError)
2497 DEBUGOUT ("hardware error occurred\n");
2501 DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]);
2508 /* Note that this function won't return the error codes NO_CARD or
2511 ccid_slot_status (ccid_driver_t handle, int *statusbits)
2514 unsigned char msg[100];
2516 unsigned char seqno;
2520 msg[0] = PC_to_RDR_GetSlotStatus;
2521 msg[5] = 0; /* slot */
2522 msg[6] = seqno = handle->seqno++;
2523 msg[7] = 0; /* RFU */
2524 msg[8] = 0; /* RFU */
2525 msg[9] = 0; /* RFU */
2526 set_msg_len (msg, 0);
2528 rc = bulk_out (handle, msg, 10, 1);
2531 /* Note that we set the NO_DEBUG flag here, so that the logs won't
2532 get cluttered up by a ticker function checking for the slot
2533 status and debugging enabled. */
2534 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
2535 seqno, retries? 1000 : 200, 1);
2536 if (rc == CCID_DRIVER_ERR_CARD_IO_ERROR && retries < 3)
2540 DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n");
2541 libusb_clear_halt (handle->idev, handle->ep_bulk_in);
2542 libusb_clear_halt (handle->idev, handle->ep_bulk_out);
2545 DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n");
2549 if (rc && rc != CCID_DRIVER_ERR_NO_CARD
2550 && rc != CCID_DRIVER_ERR_CARD_INACTIVE)
2552 *statusbits = (msg[7] & 3);
2558 /* Parse ATR string (of ATRLEN) and update parameters at PARAM.
2559 Calling this routine, it should prepare default values at PARAM
2560 beforehand. This routine assumes that card is accessed by T=1
2561 protocol. It doesn't analyze historical bytes at all.
2563 Returns < 0 value on error:
2564 -1 for parse error or integrity check error
2565 -2 for card doesn't support T=1 protocol
2566 -3 for parameters are nod explicitly defined by ATR
2567 -4 for this driver doesn't support CRC
2569 Returns >= 0 on success:
2570 0 for card is negotiable mode
2571 1 for card is specific mode (and not negotiable)
2574 update_param_by_atr (unsigned char *param, unsigned char *atr, size_t atrlen)
2578 int historical_bytes_num, negotiable = 1;
2580 #define NEXTBYTE() do { i++; if (atrlen <= i) return -1; } while (0)
2585 param[1] |= 0x02; /* Convention is inverse. */
2589 historical_bytes_num = atr[i] & 0x0f;
2594 param[0] = atr[i]; /* TA1 - Fi & Di */
2599 NEXTBYTE (); /* TB1 - ignore */
2603 param[2] = atr[i]; /* TC1 - Guard Time */
2609 y = (atr[i] >> 4); /* TD1 */
2614 { /* TA2 - PPS mode */
2615 if ((atr[i] & 0x0f) != 1)
2616 return -2; /* Wrong card protocol (!= 1). */
2618 if ((atr[i] & 0x10) != 0x10)
2619 return -3; /* Transmission parameters are implicitly defined. */
2621 negotiable = 0; /* TA2 means specific mode. */
2626 NEXTBYTE (); /* TB2 - ignore */
2629 NEXTBYTE (); /* TC2 - ignore */
2633 y = (atr[i] >> 4); /* TD2 */
2645 param[5] = atr[i]; /* IFSC */
2647 /* XXX: check voltage? */
2648 param[4] = (atr[i] >> 6); /* ClockStop */
2656 param[3] = atr[i]; /* TBx - BWI & CWI */
2663 param[1] |= (atr[i] & 0x01); /* TCx - LRC/CRC */
2666 if (param[1] & 0x01)
2667 return -4; /* CRC not supported yet. */
2672 y = (atr[i] >> 4); /* TDx */
2681 i += historical_bytes_num - 1;
2703 /* Return the ATR of the card. This is not a cached value and thus an
2704 actual reset is done. */
2706 ccid_get_atr (ccid_driver_t handle,
2707 unsigned char *atr, size_t maxatrlen, size_t *atrlen)
2711 unsigned char msg[100];
2712 unsigned char *tpdu;
2713 size_t msglen, tpdulen;
2714 unsigned char seqno;
2719 unsigned char param[7] = { /* For Protocol T=1 */
2720 0x11, /* bmFindexDindex */
2721 0x10, /* bmTCCKST1 */
2722 0x00, /* bGuardTimeT1 */
2723 0x4d, /* bmWaitingIntegersT1 */
2724 0x00, /* bClockStop */
2726 0x00 /* bNadValue */
2729 /* First check whether a card is available. */
2730 rc = ccid_slot_status (handle, &statusbits);
2733 if (statusbits == 2)
2734 return CCID_DRIVER_ERR_NO_CARD;
2736 /* For an inactive and also for an active card, issue the PowerOn
2737 command to get the ATR. */
2739 msg[0] = PC_to_RDR_IccPowerOn;
2740 msg[5] = 0; /* slot */
2741 msg[6] = seqno = handle->seqno++;
2742 /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */
2743 msg[7] = handle->auto_voltage ? 0 : 1;
2744 msg[8] = 0; /* RFU */
2745 msg[9] = 0; /* RFU */
2746 set_msg_len (msg, 0);
2749 rc = bulk_out (handle, msg, msglen, 0);
2752 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2756 if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb
2757 && ((handle->id_vendor == VENDOR_CHERRY
2758 && handle->id_product == 0x0005)
2759 || (handle->id_vendor == VENDOR_GEMPC
2760 && handle->id_product == 0x4433)
2764 /* Try switching to ISO mode. */
2765 if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2,
2769 else if (CCID_COMMAND_FAILED (msg))
2770 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2773 handle->powered_off = 0;
2777 size_t n = msglen - 10;
2781 memcpy (atr, msg+10, n);
2785 param[6] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2786 rc = update_param_by_atr (param, msg+10, msglen - 10);
2789 DEBUGOUT_1 ("update_param_by_atr failed: %d\n", rc);
2790 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2795 if (handle->auto_param)
2797 msg[0] = PC_to_RDR_GetParameters;
2798 msg[5] = 0; /* slot */
2799 msg[6] = seqno = handle->seqno++;
2800 msg[7] = 0; /* RFU */
2801 msg[8] = 0; /* RFU */
2802 msg[9] = 0; /* RFU */
2803 set_msg_len (msg, 0);
2805 rc = bulk_out (handle, msg, msglen, 0);
2807 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2810 DEBUGOUT ("GetParameters failed\n");
2811 else if (msglen == 17 && msg[9] == 1)
2814 else if (handle->auto_pps)
2816 else if (rc == 1) /* It's negotiable, send PPS. */
2818 msg[0] = PC_to_RDR_XfrBlock;
2819 msg[5] = 0; /* slot */
2820 msg[6] = seqno = handle->seqno++;
2824 msg[10] = 0xff; /* PPSS */
2825 msg[11] = 0x11; /* PPS0: PPS1, Protocol T=1 */
2826 msg[12] = param[0]; /* PPS1: Fi / Di */
2827 msg[13] = 0xff ^ 0x11 ^ param[0]; /* PCK */
2828 set_msg_len (msg, 4);
2831 rc = bulk_out (handle, msg, msglen, 0);
2835 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2840 if (msglen != 10 + 4)
2842 DEBUGOUT_1 ("Setting PPS failed: %zu\n", msglen);
2843 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2846 if (msg[10] != 0xff || msg[11] != 0x11 || msg[12] != param[0])
2848 DEBUGOUT_1 ("Setting PPS failed: 0x%02x\n", param[0]);
2849 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2853 /* Setup parameters to select T=1. */
2854 msg[0] = PC_to_RDR_SetParameters;
2855 msg[5] = 0; /* slot */
2856 msg[6] = seqno = handle->seqno++;
2857 msg[7] = 1; /* Select T=1. */
2858 msg[8] = 0; /* RFU */
2859 msg[9] = 0; /* RFU */
2862 memcpy (&msg[10], param, 7);
2863 set_msg_len (msg, 7);
2866 rc = bulk_out (handle, msg, msglen, 0);
2869 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2872 DEBUGOUT ("SetParameters failed (ignored)\n");
2874 if (!rc && msglen > 15 && msg[15] >= 16 && msg[15] <= 254 )
2875 handle->ifsc = msg[15];
2877 handle->ifsc = 128; /* Something went wrong, assume 128 bytes. */
2879 if (handle->nonnull_nad && msglen > 16 && msg[16] == 0)
2881 DEBUGOUT ("Use Null-NAD, clearing handle->nonnull_nad.\n");
2882 handle->nonnull_nad = 0;
2888 /* Send an S-Block with our maximum IFSD to the CCID. */
2889 if (!handle->apdu_level && !handle->auto_ifsd)
2892 /* NAD: DAD=1, SAD=0 */
2893 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2894 tpdu[1] = (0xc0 | 0 | 1); /* S-block request: change IFSD */
2896 tpdu[3] = handle->max_ifsd? handle->max_ifsd : 32;
2898 edc = compute_edc (tpdu, tpdulen, use_crc);
2900 tpdu[tpdulen++] = (edc >> 8);
2901 tpdu[tpdulen++] = edc;
2903 msg[0] = PC_to_RDR_XfrBlock;
2904 msg[5] = 0; /* slot */
2905 msg[6] = seqno = handle->seqno++;
2907 msg[8] = 0; /* RFU */
2908 msg[9] = 0; /* RFU */
2909 set_msg_len (msg, tpdulen);
2910 msglen = 10 + tpdulen;
2912 if (debug_level > 1)
2913 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
2914 ((msg[11] & 0xc0) == 0x80)? 'R' :
2915 (msg[11] & 0x80)? 'S' : 'I',
2916 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2917 : !!(msg[11] & 0x40)),
2918 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2920 rc = bulk_out (handle, msg, msglen, 0);
2925 rc = bulk_in (handle, msg, sizeof msg, &msglen,
2926 RDR_to_PC_DataBlock, seqno, 5000, 0);
2931 tpdulen = msglen - 10;
2934 return CCID_DRIVER_ERR_ABORTED;
2936 if (debug_level > 1)
2937 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2938 ((msg[11] & 0xc0) == 0x80)? 'R' :
2939 (msg[11] & 0x80)? 'S' : 'I',
2940 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2941 : !!(msg[11] & 0x40)),
2942 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2943 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2945 if ((tpdu[1] & 0xe0) != 0xe0 || tpdu[2] != 1)
2947 DEBUGOUT ("invalid response for S-block (Change-IFSD)\n");
2950 DEBUGOUT_1 ("IFSD has been set to %d\n", tpdu[3]);
2960 compute_edc (const unsigned char *data, size_t datalen, int use_crc)
2964 return 0x42; /* Not yet implemented. */
2968 unsigned char crc = 0;
2970 for (; datalen; datalen--)
2977 /* Return true if APDU is an extended length one. */
2979 is_exlen_apdu (const unsigned char *apdu, size_t apdulen)
2981 if (apdulen < 7 || apdu[4])
2982 return 0; /* Too short or no Z byte. */
2987 /* Helper for ccid_transceive used for APDU level exchanges. */
2989 ccid_transceive_apdu_level (ccid_driver_t handle,
2990 const unsigned char *apdu_buf, size_t apdu_len,
2991 unsigned char *resp, size_t maxresplen,
2995 unsigned char msg[CCID_MAX_BUF];
2996 const unsigned char *apdu_p;
2997 size_t apdu_part_len;
2999 unsigned char seqno;
3001 unsigned char chain = 0;
3003 if (apdu_len == 0 || apdu_len > sizeof (msg) - 10)
3004 return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
3009 apdu_part_len = apdu_len;
3010 if (apdu_part_len > handle->max_ccid_msglen - 10)
3012 apdu_part_len = handle->max_ccid_msglen - 10;
3016 msg[0] = PC_to_RDR_XfrBlock;
3017 msg[5] = 0; /* slot */
3018 msg[6] = seqno = handle->seqno++;
3022 memcpy (msg+10, apdu_p, apdu_part_len);
3023 set_msg_len (msg, apdu_part_len);
3024 msglen = 10 + apdu_part_len;
3026 rc = bulk_out (handle, msg, msglen, 0);
3030 apdu_p += apdu_part_len;
3031 apdu_len -= apdu_part_len;
3033 rc = bulk_in (handle, msg, sizeof msg, &msglen,
3034 RDR_to_PC_DataBlock, seqno, CCID_CMD_TIMEOUT, 0);
3038 if (!(chain & 0x01))
3047 apdu_part_len = msglen - 10;
3048 if (resp && apdu_len + apdu_part_len <= maxresplen)
3049 memcpy (resp + apdu_len, msg+10, apdu_part_len);
3050 apdu_len += apdu_part_len;
3052 if (!(msg[9] & 0x01))
3055 msg[0] = PC_to_RDR_XfrBlock;
3056 msg[5] = 0; /* slot */
3057 msg[6] = seqno = handle->seqno++;
3059 msg[8] = 0x10; /* Request next data block */
3061 set_msg_len (msg, 0);
3064 rc = bulk_out (handle, msg, msglen, 0);
3068 rc = bulk_in (handle, msg, sizeof msg, &msglen,
3069 RDR_to_PC_DataBlock, seqno, CCID_CMD_TIMEOUT, 0);
3076 if (apdu_len > maxresplen)
3078 DEBUGOUT_2 ("provided buffer too short for received data "
3080 (unsigned int)apdu_len, (unsigned int)maxresplen);
3081 return CCID_DRIVER_ERR_INV_VALUE;
3093 Protocol T=1 overview
3097 1 byte Node Address (NAD)
3098 1 byte Protocol Control Byte (PCB)
3101 0-254 byte APDU or Control Information (INF)
3103 1 byte Error Detection Code (EDC)
3107 bit 4..6 Destination Node Address (DAD)
3109 bit 2..0 Source Node Address (SAD)
3111 If node adresses are not used, SAD and DAD should be set to 0 on
3112 the first block sent to the card. If they are used they should
3113 have different values (0 for one is okay); that first block sets up
3114 the addresses of the nodes.
3117 Information Block (I-Block):
3119 bit 6 Sequence number (yep, that is modulo 2)
3122 Received-Ready Block (R-Block):
3126 bit 4 Sequence number
3127 bit 3..0 0 = no error
3128 1 = EDC or parity error
3130 other values are reserved
3131 Supervisory Block (S-Block):
3134 bit 5 clear=request,set=response
3135 bit 4..0 0 = resyncronisation request
3136 1 = information field size request
3138 3 = extension of BWT request
3140 other values are reserved
3145 ccid_transceive (ccid_driver_t handle,
3146 const unsigned char *apdu_buf, size_t apdu_buflen,
3147 unsigned char *resp, size_t maxresplen, size_t *nresp)
3150 /* The size of the buffer used to be 10+259. For the via_escape
3151 hack we need one extra byte, thus 11+259. */
3152 unsigned char send_buffer[11+259], recv_buffer[11+259];
3153 const unsigned char *apdu;
3155 unsigned char *msg, *tpdu, *p;
3156 size_t msglen, tpdulen, last_tpdulen, n;
3157 unsigned char seqno;
3170 nresp = &dummy_nresp;
3173 /* Smarter readers allow sending APDUs directly; divert here. */
3174 if (handle->apdu_level)
3176 /* We employ a hack for Omnikey readers which are able to send
3177 TPDUs using an escape sequence. There is no documentation
3178 but the Windows driver does it this way. Tested using a
3179 CM6121. This method works also for the Cherry XX44
3180 keyboards; however there are problems with the
3181 ccid_tranceive_secure which leads to a loss of sync on the
3182 CCID level. If Cherry wants to make their keyboard work
3183 again, they should hand over some docs. */
3184 if ((handle->id_vendor == VENDOR_OMNIKEY
3185 || (!handle->idev && handle->id_product == TRANSPORT_CM4040))
3186 && handle->apdu_level < 2
3187 && is_exlen_apdu (apdu_buf, apdu_buflen))
3190 return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen,
3191 resp, maxresplen, nresp);
3194 /* The other readers we support require sending TPDUs. */
3196 tpdulen = 0; /* Avoid compiler warning about no initialization. */
3198 hdrlen = via_escape? 11 : 10;
3200 /* NAD: DAD=1, SAD=0 */
3201 nad_byte = handle->nonnull_nad? ((1 << 4) | 0): 0;
3205 last_tpdulen = 0; /* Avoid gcc warning (controlled by RESYNCING). */
3213 apdulen = apdu_buflen;
3216 /* Construct an I-Block. */
3217 tpdu = msg + hdrlen;
3219 tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */
3220 if (apdulen > handle->ifsc )
3222 apdulen = handle->ifsc;
3223 apdu_buf += handle->ifsc;
3224 apdu_buflen -= handle->ifsc;
3225 tpdu[1] |= (1 << 5); /* Set more bit. */
3228 memcpy (tpdu+3, apdu, apdulen);
3229 tpdulen = 3 + apdulen;
3230 edc = compute_edc (tpdu, tpdulen, use_crc);
3232 tpdu[tpdulen++] = (edc >> 8);
3233 tpdu[tpdulen++] = edc;
3238 msg[0] = PC_to_RDR_Escape;
3239 msg[5] = 0; /* slot */
3240 msg[6] = seqno = handle->seqno++;
3241 msg[7] = 0; /* RFU */
3242 msg[8] = 0; /* RFU */
3243 msg[9] = 0; /* RFU */
3244 msg[10] = 0x1a; /* Omnikey command to send a TPDU. */
3245 set_msg_len (msg, 1 + tpdulen);
3249 msg[0] = PC_to_RDR_XfrBlock;
3250 msg[5] = 0; /* slot */
3251 msg[6] = seqno = handle->seqno++;
3252 msg[7] = 4; /* bBWI */
3253 msg[8] = 0; /* RFU */
3254 msg[9] = 0; /* RFU */
3255 set_msg_len (msg, tpdulen);
3257 msglen = hdrlen + tpdulen;
3259 last_tpdulen = tpdulen;
3262 if (debug_level > 1)
3263 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
3264 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
3265 (msg[pcboff] & 0x80)? 'S' : 'I',
3266 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
3267 : !!(msg[pcboff] & 0x40)),
3268 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
3271 rc = bulk_out (handle, msg, msglen, 0);
3276 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3277 via_escape? RDR_to_PC_Escape : RDR_to_PC_DataBlock,
3278 seqno, CCID_CMD_TIMEOUT, 0);
3282 tpdu = msg + hdrlen;
3283 tpdulen = msglen - hdrlen;
3288 libusb_clear_halt (handle->idev, handle->ep_bulk_in);
3289 return CCID_DRIVER_ERR_ABORTED;
3292 if (debug_level > 1)
3293 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3294 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
3295 (msg[pcboff] & 0x80)? 'S' : 'I',
3296 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
3297 : !!(msg[pcboff] & 0x40)),
3298 ((msg[pcboff] & 0xc0) == 0x80)? (msg[pcboff] & 0x0f) : 0,
3299 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
3302 if (!(tpdu[1] & 0x80))
3303 { /* This is an I-block. */
3306 { /* last block sent was successful. */
3311 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3312 { /* Response does not match our sequence number. */
3314 tpdu = msg + hdrlen;
3316 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */
3319 edc = compute_edc (tpdu, tpdulen, use_crc);
3321 tpdu[tpdulen++] = (edc >> 8);
3322 tpdu[tpdulen++] = edc;
3329 p = tpdu + 3; /* Skip the prologue field. */
3330 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3331 /* fixme: verify the checksum. */
3336 DEBUGOUT_2 ("provided buffer too short for received data "
3338 (unsigned int)n, (unsigned int)maxresplen);
3339 return CCID_DRIVER_ERR_INV_VALUE;
3342 memcpy (resp, p, n);
3348 if (!(tpdu[1] & 0x20))
3349 return 0; /* No chaining requested - ready. */
3352 tpdu = msg + hdrlen;
3354 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */
3357 edc = compute_edc (tpdu, tpdulen, use_crc);
3359 tpdu[tpdulen++] = (edc >> 8);
3360 tpdu[tpdulen++] = edc;
3362 else if ((tpdu[1] & 0xc0) == 0x80)
3363 { /* This is a R-block. */
3364 if ( (tpdu[1] & 0x0f))
3367 if (via_escape && retries == 1 && (msg[pcboff] & 0x0f))
3369 /* Error probably due to switching to TPDU. Send a
3370 resync request. We use the recv_buffer so that
3371 we don't corrupt the send_buffer. */
3373 tpdu = msg + hdrlen;
3375 tpdu[1] = 0xc0; /* S-block resync request. */
3378 edc = compute_edc (tpdu, tpdulen, use_crc);
3380 tpdu[tpdulen++] = (edc >> 8);
3381 tpdu[tpdulen++] = edc;
3383 DEBUGOUT ("T=1: requesting resync\n");
3385 else if (retries > 3)
3387 DEBUGOUT ("T=1: 3 failed retries\n");
3388 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3392 /* Error: repeat last block */
3394 tpdulen = last_tpdulen;
3397 else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns)
3398 { /* Response does not match our sequence number. */
3399 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3400 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3403 { /* Send next chunk. */
3411 DEBUGOUT ("unexpected ACK R-block received\n");
3412 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3416 { /* This is a S-block. */
3418 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d\n",
3419 (tpdu[1] & 0x20)? "response": "request",
3421 if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 1 && tpdu[2] == 1)
3423 /* Information field size request. */
3424 unsigned char ifsc = tpdu[3];
3426 if (ifsc < 16 || ifsc > 254)
3427 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3430 tpdu = msg + hdrlen;
3432 tpdu[1] = (0xc0 | 0x20 | 1); /* S-block response */
3436 edc = compute_edc (tpdu, tpdulen, use_crc);
3438 tpdu[tpdulen++] = (edc >> 8);
3439 tpdu[tpdulen++] = edc;
3440 DEBUGOUT_1 ("T=1: requesting an ifsc=%d\n", ifsc);
3442 else if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2])
3444 /* Wait time extension request. */
3445 unsigned char bwi = tpdu[3];
3447 tpdu = msg + hdrlen;
3449 tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */
3453 edc = compute_edc (tpdu, tpdulen, use_crc);
3455 tpdu[tpdulen++] = (edc >> 8);
3456 tpdu[tpdulen++] = edc;
3457 DEBUGOUT_1 ("T=1: waittime extension of bwi=%d\n", bwi);
3458 print_progress (handle);
3460 else if ( (tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 0 && !tpdu[2])
3462 DEBUGOUT ("T=1: resync ack from reader\n");
3463 /* Repeat previous block. */
3465 tpdulen = last_tpdulen;
3468 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3470 } /* end T=1 protocol loop. */
3476 /* Send the CCID Secure command to the reader. APDU_BUF should
3477 contain the APDU template. PIN_MODE defines how the pin gets
3480 1 := The PIN is ASCII encoded and of variable length. The
3481 length of the PIN entered will be put into Lc by the reader.
3482 The APDU should me made up of 4 bytes without Lc.
3484 PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0
3485 may be used t enable reasonable defaults.
3487 When called with RESP and NRESP set to NULL, the function will
3488 merely check whether the reader supports the secure command for the
3489 given APDU and PIN_MODE. */
3491 ccid_transceive_secure (ccid_driver_t handle,
3492 const unsigned char *apdu_buf, size_t apdu_buflen,
3494 unsigned char *resp, size_t maxresplen, size_t *nresp)
3497 unsigned char send_buffer[10+259], recv_buffer[10+259];
3498 unsigned char *msg, *tpdu, *p;
3499 size_t msglen, tpdulen, n;
3500 unsigned char seqno;
3503 int cherry_mode = 0;
3505 int enable_varlen = 0;
3507 testmode = !resp && !nresp;
3510 nresp = &dummy_nresp;
3513 if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1))
3515 else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2))
3518 return CCID_DRIVER_ERR_NO_PINPAD;
3520 if (!pininfo->minlen)
3521 pininfo->minlen = 1;
3522 if (!pininfo->maxlen)
3523 pininfo->maxlen = 15;
3525 /* Note that the 25 is the maximum value the SPR532 allows. */
3526 if (pininfo->minlen < 1 || pininfo->minlen > 25
3527 || pininfo->maxlen < 1 || pininfo->maxlen > 25
3528 || pininfo->minlen > pininfo->maxlen)
3529 return CCID_DRIVER_ERR_INV_VALUE;
3531 /* We have only tested a few readers so better don't risk anything
3532 and do not allow the use with other readers. */
3533 switch (handle->id_vendor)
3535 case VENDOR_SCM: /* Tested with SPR 532. */
3536 case VENDOR_KAAN: /* Tested with KAAN Advanced (1.02). */
3537 case VENDOR_FSIJ: /* Tested with Gnuk (0.21). */
3538 pininfo->maxlen = 25;
3541 case VENDOR_REINER:/* Tested with cyberJack go */
3542 case VENDOR_VASCO: /* Tested with DIGIPASS 920 */
3546 pininfo->maxlen = 15;
3548 /* The CHERRY XX44 keyboard echos an asterisk for each entered
3549 character on the keyboard channel. We use a special variant
3550 of PC_to_RDR_Secure which directs these characters to the
3551 smart card's bulk-in channel. We also need to append a zero
3552 Lc byte to the APDU. It seems that it will be replaced with
3553 the actual length instead of being appended before the APDU
3554 is send to the card. */
3556 if (handle->id_product != CHERRY_ST2000)
3560 if ((handle->id_vendor == VENDOR_GEMPC &&
3561 handle->id_product == GEMPC_PINPAD)
3562 || (handle->id_vendor == VENDOR_VEGA &&
3563 handle->id_product == VEGA_ALPHA))
3566 pininfo->minlen = 4;
3567 pininfo->maxlen = 8;
3570 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3574 pininfo->fixedlen = 0;
3577 return 0; /* Success */
3579 if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
3580 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3583 if (handle->id_vendor == VENDOR_SCM)
3585 DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n");
3586 rc = send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3,
3592 msg[0] = cherry_mode? 0x89 : PC_to_RDR_Secure;
3593 msg[5] = 0; /* slot */
3594 msg[6] = seqno = handle->seqno++;
3595 msg[7] = 0; /* bBWI */
3596 msg[8] = 0; /* RFU */
3597 msg[9] = 0; /* RFU */
3598 msg[10] = apdu_buf[1] == 0x20 ? 0 : 1;
3599 /* Perform PIN verification or PIN modification. */
3600 msg[11] = 0; /* Timeout in seconds. */
3601 msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
3602 if (handle->id_vendor == VENDOR_SCM)
3604 /* For the SPR532 the next 2 bytes need to be zero. We do this
3605 for all SCM products. Kudos to Martin Paljak for this
3607 msg[13] = msg[14] = 0;
3611 msg[13] = pininfo->fixedlen; /* bmPINBlockString:
3612 0 bits of pin length to insert.
3613 PIN block size by fixedlen. */
3614 msg[14] = 0x00; /* bmPINLengthFormat:
3615 Units are bytes, position is 0. */
3619 if (apdu_buf[1] == 0x24)
3621 msg[msglen++] = 0; /* bInsertionOffsetOld */
3622 msg[msglen++] = pininfo->fixedlen; /* bInsertionOffsetNew */
3625 /* The following is a little endian word. */
3626 msg[msglen++] = pininfo->maxlen; /* wPINMaxExtraDigit-Maximum. */
3627 msg[msglen++] = pininfo->minlen; /* wPINMaxExtraDigit-Minimum. */
3629 if (apdu_buf[1] == 0x24)
3630 msg[msglen++] = apdu_buf[2] == 0 ? 0x03 : 0x01;
3632 * 0x00: new PIN once
3633 * 0x01: new PIN twice (confirmation)
3634 * 0x02: old PIN and new PIN once
3635 * 0x03: old PIN and new PIN twice (confirmation)
3638 msg[msglen] = 0x02; /* bEntryValidationCondition:
3639 Validation key pressed */
3640 if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
3641 msg[msglen] |= 0x01; /* Max size reached. */
3644 if (apdu_buf[1] == 0x20)
3645 msg[msglen++] = 0x01; /* bNumberMessage. */
3647 msg[msglen++] = 0x03; /* bNumberMessage. */
3649 msg[msglen++] = 0x09; /* wLangId-Low: English FIXME: use the first entry. */
3650 msg[msglen++] = 0x04; /* wLangId-High. */
3652 if (apdu_buf[1] == 0x20)
3653 msg[msglen++] = 0; /* bMsgIndex. */
3656 msg[msglen++] = 0; /* bMsgIndex1. */
3657 msg[msglen++] = 1; /* bMsgIndex2. */
3658 msg[msglen++] = 2; /* bMsgIndex3. */
3662 n = pininfo->fixedlen;
3663 if (apdu_buf[1] == 0x24)
3664 n += pininfo->fixedlen;
3666 /* bTeoProlog follows: */
3667 msg[msglen++] = handle->nonnull_nad? ((1 << 4) | 0): 0;
3668 msg[msglen++] = ((handle->t1_ns & 1) << 6); /* I-block */
3670 msg[msglen++] = n + 5; /* apdulen should be filled for fixed length. */
3672 msg[msglen++] = 0; /* The apdulen will be filled in by the reader. */
3674 msg[msglen++] = apdu_buf[0]; /* CLA */
3675 msg[msglen++] = apdu_buf[1]; /* INS */
3676 msg[msglen++] = apdu_buf[2]; /* P1 */
3677 msg[msglen++] = apdu_buf[3]; /* P2 */
3680 else if (pininfo->fixedlen != 0)
3683 memset (&msg[msglen], 0xff, n);
3686 /* An EDC is not required. */
3687 set_msg_len (msg, msglen - 10);
3689 rc = bulk_out (handle, msg, msglen, 0);
3694 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3695 RDR_to_PC_DataBlock, seqno, 30000, 0);
3700 tpdulen = msglen - 10;
3702 if (handle->apdu_level)
3706 if (tpdulen > maxresplen)
3708 DEBUGOUT_2 ("provided buffer too short for received data "
3710 (unsigned int)tpdulen, (unsigned int)maxresplen);
3711 return CCID_DRIVER_ERR_INV_VALUE;
3714 memcpy (resp, tpdu, tpdulen);
3722 libusb_clear_halt (handle->idev, handle->ep_bulk_in);
3723 return CCID_DRIVER_ERR_ABORTED;
3725 if (debug_level > 1)
3726 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3727 ((msg[11] & 0xc0) == 0x80)? 'R' :
3728 (msg[11] & 0x80)? 'S' : 'I',
3729 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
3730 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
3731 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
3733 if (!(tpdu[1] & 0x80))
3734 { /* This is an I-block. */
3735 /* Last block sent was successful. */
3738 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3739 { /* Response does not match our sequence number. */
3740 DEBUGOUT ("I-block with wrong seqno received\n");
3741 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3746 p = tpdu + 3; /* Skip the prologue field. */
3747 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3748 /* fixme: verify the checksum. */
3753 DEBUGOUT_2 ("provided buffer too short for received data "
3755 (unsigned int)n, (unsigned int)maxresplen);
3756 return CCID_DRIVER_ERR_INV_VALUE;
3759 memcpy (resp, p, n);
3765 if (!(tpdu[1] & 0x20))
3766 return 0; /* No chaining requested - ready. */
3768 DEBUGOUT ("chaining requested but not supported for Secure operation\n");
3769 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3771 else if ((tpdu[1] & 0xc0) == 0x80)
3772 { /* This is a R-block. */
3773 if ( (tpdu[1] & 0x0f))
3774 { /* Error: repeat last block */
3775 DEBUGOUT ("No retries supported for Secure operation\n");
3776 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3778 else if (!!(tpdu[1] & 0x10) == handle->t1_ns)
3779 { /* Response does not match our sequence number. */
3780 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3781 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3784 { /* Send next chunk. */
3785 DEBUGOUT ("chaining not supported on Secure operation\n");
3786 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3790 { /* This is a S-block. */
3791 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d for Secure operation\n",
3792 (tpdu[1] & 0x20)? "response": "request",
3794 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3807 print_error (int err)
3814 case 0: p = "success";
3815 case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break;
3816 case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break;
3817 case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break;
3818 case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break;
3819 case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break;
3820 case CCID_DRIVER_ERR_BUSY: p = "busy"; break;
3821 case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break;
3822 case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break;
3823 case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break;
3824 case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break;
3825 case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break;
3826 case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break;
3827 default: sprintf (buf, "0x%05x", err); p = buf; break;
3829 fprintf (stderr, "operation failed: %s\n", p);
3834 print_data (const unsigned char *data, size_t length)
3838 fprintf (stderr, "operation status: %02X%02X\n",
3839 data[length-2], data[length-1]);
3844 fputs (" returned data:", stderr);
3845 for (; length; length--, data++)
3846 fprintf (stderr, " %02X", *data);
3847 putc ('\n', stderr);
3852 print_result (int rc, const unsigned char *data, size_t length)
3857 print_data (data, length);
3861 main (int argc, char **argv)
3866 unsigned char result[512];
3869 int verify_123456 = 0;
3881 if ( !strcmp (*argv, "--list"))
3884 p = ccid_get_reader_list ();
3891 else if ( !strcmp (*argv, "--debug"))
3893 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
3896 else if ( !strcmp (*argv, "--no-poll"))
3901 else if ( !strcmp (*argv, "--no-pinpad"))
3906 else if ( !strcmp (*argv, "--verify-123456"))
3915 rc = ccid_open_reader (&ccid, argc? *argv:NULL, NULL);
3921 fputs ("getting ATR ...\n", stderr);
3922 rc = ccid_get_atr (ccid, NULL, 0, NULL);
3931 fputs ("getting slot status ...\n", stderr);
3932 rc = ccid_slot_status (ccid, &slotstat);
3942 fputs ("selecting application OpenPGP ....\n", stderr);
3944 static unsigned char apdu[] = {
3945 0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01};
3946 rc = ccid_transceive (ccid,
3948 result, sizeof result, &resultlen);
3949 print_result (rc, result, resultlen);
3956 fputs ("getting OpenPGP DO 0x65 ....\n", stderr);
3958 static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 };
3959 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3960 result, sizeof result, &resultlen);
3961 print_result (rc, result, resultlen);
3970 static unsigned char apdu[] = { 0, 0x20, 0, 0x81 };
3973 if (ccid_transceive_secure (ccid,
3977 fputs ("can't verify using a PIN-Pad reader\n", stderr);
3980 fputs ("verifying CHV1 using the PINPad ....\n", stderr);
3982 rc = ccid_transceive_secure (ccid,
3985 result, sizeof result, &resultlen);
3986 print_result (rc, result, resultlen);
3991 if (verify_123456 && !did_verify)
3993 fputs ("verifying that CHV1 is 123456....\n", stderr);
3995 static unsigned char apdu[] = {0, 0x20, 0, 0x81,
3996 6, '1','2','3','4','5','6'};
3997 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3998 result, sizeof result, &resultlen);
3999 print_result (rc, result, resultlen);
4005 fputs ("getting OpenPGP DO 0x5E ....\n", stderr);
4007 static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 };
4008 rc = ccid_transceive (ccid, apdu, sizeof apdu,
4009 result, sizeof result, &resultlen);
4010 print_result (rc, result, resultlen);
4014 ccid_close_reader (ccid);
4021 * compile-command: "gcc -DTEST -Wall -I/usr/local/include -lusb -g ccid-driver.c"
4025 #endif /*HAVE_LIBUSB*/