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 command + lc + le = 4 + 3 + 0
104 Sending: write data object of cardholder certificate
106 command + lc + le = 4 + 3 + 0
107 Receiving: 2048 for cardholder certificate
109 #define CCID_MAX_BUF (2048+7+10)
111 /* CCID command timeout. */
112 #define CCID_CMD_TIMEOUT (5*1000)
114 /* Number of supported devices. See MAX_READER in apdu.c. */
115 #define CCID_MAX_DEVICE 4
118 /* Depending on how this source is used we either define our error
119 output to go to stderr or to the GnuPG based logging functions. We
120 use the latter when GNUPG_MAJOR_VERSION or GNUPG_SCD_MAIN_HEADER
122 #if defined(GNUPG_MAJOR_VERSION) || defined(GNUPG_SCD_MAIN_HEADER)
124 #if defined(GNUPG_SCD_MAIN_HEADER)
125 # include GNUPG_SCD_MAIN_HEADER
126 #elif GNUPG_MAJOR_VERSION == 1 /* GnuPG Version is < 1.9. */
127 # include "options.h"
130 # include "cardglue.h"
131 # else /* This is the modularized GnuPG 1.9 or later. */
132 # include "scdaemon.h"
136 # define DEBUGOUT(t) do { if (debug_level) \
137 log_debug (DRVNAME t); } while (0)
138 # define DEBUGOUT_1(t,a) do { if (debug_level) \
139 log_debug (DRVNAME t,(a)); } while (0)
140 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
141 log_debug (DRVNAME t,(a),(b)); } while (0)
142 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
143 log_debug (DRVNAME t,(a),(b),(c));} while (0)
144 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
145 log_debug (DRVNAME t,(a),(b),(c),(d));} while (0)
146 # define DEBUGOUT_CONT(t) do { if (debug_level) \
147 log_printf (t); } while (0)
148 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
149 log_printf (t,(a)); } while (0)
150 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
151 log_printf (t,(a),(b)); } while (0)
152 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
153 log_printf (t,(a),(b),(c)); } while (0)
154 # define DEBUGOUT_LF() do { if (debug_level) \
155 log_printf ("\n"); } while (0)
157 #else /* Other usage of this source - don't use gnupg specifics. */
159 # define DEBUGOUT(t) do { if (debug_level) \
160 fprintf (stderr, DRVNAME t); } while (0)
161 # define DEBUGOUT_1(t,a) do { if (debug_level) \
162 fprintf (stderr, DRVNAME t, (a)); } while (0)
163 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
164 fprintf (stderr, DRVNAME t, (a), (b)); } while (0)
165 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
166 fprintf (stderr, DRVNAME t, (a), (b), (c)); } while (0)
167 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
168 fprintf (stderr, DRVNAME t, (a), (b), (c), (d));} while(0)
169 # define DEBUGOUT_CONT(t) do { if (debug_level) \
170 fprintf (stderr, t); } while (0)
171 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
172 fprintf (stderr, t, (a)); } while (0)
173 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
174 fprintf (stderr, t, (a), (b)); } while (0)
175 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
176 fprintf (stderr, t, (a), (b), (c)); } while (0)
177 # define DEBUGOUT_LF() do { if (debug_level) \
178 putc ('\n', stderr); } while (0)
180 #endif /* This source not used by scdaemon. */
184 #define EAGAIN EWOULDBLOCK
190 RDR_to_PC_NotifySlotChange= 0x50,
191 RDR_to_PC_HardwareError = 0x51,
193 PC_to_RDR_SetParameters = 0x61,
194 PC_to_RDR_IccPowerOn = 0x62,
195 PC_to_RDR_IccPowerOff = 0x63,
196 PC_to_RDR_GetSlotStatus = 0x65,
197 PC_to_RDR_Secure = 0x69,
198 PC_to_RDR_T0APDU = 0x6a,
199 PC_to_RDR_Escape = 0x6b,
200 PC_to_RDR_GetParameters = 0x6c,
201 PC_to_RDR_ResetParameters = 0x6d,
202 PC_to_RDR_IccClock = 0x6e,
203 PC_to_RDR_XfrBlock = 0x6f,
204 PC_to_RDR_Mechanical = 0x71,
205 PC_to_RDR_Abort = 0x72,
206 PC_to_RDR_SetDataRate = 0x73,
208 RDR_to_PC_DataBlock = 0x80,
209 RDR_to_PC_SlotStatus = 0x81,
210 RDR_to_PC_Parameters = 0x82,
211 RDR_to_PC_Escape = 0x83,
212 RDR_to_PC_DataRate = 0x84
216 /* Two macro to detect whether a CCID command has failed and to get
217 the error code. These macros assume that we can access the
218 mandatory first 10 bytes of a CCID message in BUF. */
219 #define CCID_COMMAND_FAILED(buf) ((buf)[7] & 0x40)
220 #define CCID_ERROR_CODE(buf) (((unsigned char *)(buf))[8])
223 /* Store information on the driver's state. A pointer to such a
224 structure is used as handle for most functions. */
227 libusb_device_handle *idev;
229 unsigned short id_vendor;
230 unsigned short id_product;
238 unsigned char nonnull_nad;
242 unsigned char apdu_level:2; /* Reader supports short APDU level
243 exchange. With a value of 2 short
244 and extended level is supported.*/
245 unsigned int auto_voltage:1;
246 unsigned int auto_param:1;
247 unsigned int auto_pps:1;
248 unsigned int auto_ifsd:1;
249 unsigned int has_pinpad:2;
250 unsigned int enodev_seen:1;
253 time_t last_progress; /* Last time we sent progress line. */
255 /* The progress callback and its first arg as supplied to
256 ccid_set_progress_cb. */
257 void (*progress_cb)(void *, const char *, int, int, int);
258 void *progress_cb_arg;
260 void (*prompt_cb)(void *, int);
263 unsigned char intr_buf[64];
264 struct libusb_transfer *transfer;
268 /* Object to keep infos about found ccid devices. */
269 struct ccid_dev_table {
270 int n; /* Index to ccid_usb_dev_list */
271 int interface_number;
273 unsigned char *ifcdesc_extra;
277 size_t ifcdesc_extra_len;
281 static int initialized_usb; /* Tracks whether USB has been initialized. */
282 static int debug_level; /* Flag to control the debug output.
285 2 = Level 1 + T=1 protocol tracing
286 3 = Level 2 + USB/I/O tracing of SlotStatus.
288 static int ccid_usb_thread_is_alive;
290 static libusb_device **ccid_usb_dev_list;
291 static struct ccid_dev_table ccid_dev_table[CCID_MAX_DEVICE];
295 static unsigned int compute_edc (const unsigned char *data, size_t datalen,
297 static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
299 static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
300 size_t *nread, int expected_type, int seqno, int timeout,
302 static int abort_cmd (ccid_driver_t handle, int seqno, int init);
303 static int send_escape_cmd (ccid_driver_t handle, const unsigned char *data,
304 size_t datalen, unsigned char *result,
305 size_t resultmax, size_t *resultlen);
309 map_libusb_error (int usberr)
314 case LIBUSB_ERROR_IO: return CCID_DRIVER_ERR_USB_IO;
315 case LIBUSB_ERROR_ACCESS: return CCID_DRIVER_ERR_USB_ACCESS;
316 case LIBUSB_ERROR_NO_DEVICE:return CCID_DRIVER_ERR_USB_NO_DEVICE;
317 case LIBUSB_ERROR_BUSY: return CCID_DRIVER_ERR_USB_BUSY;
318 case LIBUSB_ERROR_TIMEOUT: return CCID_DRIVER_ERR_USB_TIMEOUT;
319 case LIBUSB_ERROR_OVERFLOW: return CCID_DRIVER_ERR_USB_OVERFLOW;
321 return CCID_DRIVER_ERR_USB_OTHER;
325 /* Convert a little endian stored 4 byte value into an unsigned
328 convert_le_u32 (const unsigned char *buf)
330 return buf[0] | (buf[1] << 8) | (buf[2] << 16) | ((unsigned int)buf[3] << 24);
334 /* Convert a little endian stored 2 byte value into an unsigned
337 convert_le_u16 (const unsigned char *buf)
339 return buf[0] | (buf[1] << 8);
343 set_msg_len (unsigned char *msg, unsigned int length)
346 msg[2] = length >> 8;
347 msg[3] = length >> 16;
348 msg[4] = length >> 24;
353 print_progress (ccid_driver_t handle)
355 time_t ct = time (NULL);
357 /* We don't want to print progress lines too often. */
358 if (ct == handle->last_progress)
361 if (handle->progress_cb)
362 handle->progress_cb (handle->progress_cb_arg, "card_busy", 'w', 0, 0);
364 handle->last_progress = ct;
369 /* Pint an error message for a failed CCID command including a textual
370 error code. MSG shall be the CCID message at a minimum of 10 bytes. */
372 print_command_failed (const unsigned char *msg)
381 ec = CCID_ERROR_CODE (msg);
384 case 0x00: t = "Command not supported"; break;
386 case 0xE0: t = "Slot busy"; break;
387 case 0xEF: t = "PIN cancelled"; break;
388 case 0xF0: t = "PIN timeout"; break;
390 case 0xF2: t = "Automatic sequence ongoing"; break;
391 case 0xF3: t = "Deactivated Protocol"; break;
392 case 0xF4: t = "Procedure byte conflict"; break;
393 case 0xF5: t = "ICC class not supported"; break;
394 case 0xF6: t = "ICC protocol not supported"; break;
395 case 0xF7: t = "Bad checksum in ATR"; break;
396 case 0xF8: t = "Bad TS in ATR"; break;
398 case 0xFB: t = "An all inclusive hardware error occurred"; break;
399 case 0xFC: t = "Overrun error while talking to the ICC"; break;
400 case 0xFD: t = "Parity error while talking to the ICC"; break;
401 case 0xFE: t = "CCID timed out while talking to the ICC"; break;
402 case 0xFF: t = "Host aborted the current activity"; break;
405 if (ec > 0 && ec < 128)
406 sprintf (buffer, "Parameter error at offset %d", ec);
408 sprintf (buffer, "Error code %02X", ec);
412 DEBUGOUT_1 ("CCID command failed: %s\n", t);
417 print_pr_data (const unsigned char *data, size_t datalen, size_t off)
421 for (; off < datalen; off++)
423 if (!any || !(off % 16))
427 DEBUGOUT_1 (" [%04lu] ", (unsigned long) off);
429 DEBUGOUT_CONT_1 (" %02X", data[off]);
432 if (any && (off % 16))
438 print_p2r_header (const char *name, const unsigned char *msg, size_t msglen)
440 DEBUGOUT_1 ("%s:\n", name);
443 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
444 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
445 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
450 print_p2r_iccpoweron (const unsigned char *msg, size_t msglen)
452 print_p2r_header ("PC_to_RDR_IccPowerOn", msg, msglen);
455 DEBUGOUT_2 (" bPowerSelect ......: 0x%02x (%s)\n", msg[7],
457 msg[7] == 1? "5.0 V":
458 msg[7] == 2? "3.0 V":
459 msg[7] == 3? "1.8 V":"");
460 print_pr_data (msg, msglen, 8);
465 print_p2r_iccpoweroff (const unsigned char *msg, size_t msglen)
467 print_p2r_header ("PC_to_RDR_IccPowerOff", msg, msglen);
468 print_pr_data (msg, msglen, 7);
473 print_p2r_getslotstatus (const unsigned char *msg, size_t msglen)
475 print_p2r_header ("PC_to_RDR_GetSlotStatus", msg, msglen);
476 print_pr_data (msg, msglen, 7);
481 print_p2r_xfrblock (const unsigned char *msg, size_t msglen)
485 print_p2r_header ("PC_to_RDR_XfrBlock", msg, msglen);
488 DEBUGOUT_1 (" bBWI ..............: 0x%02x\n", msg[7]);
489 val = convert_le_u16 (msg+8);
490 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
491 val == 1? " (continued)":
492 val == 2? " (continues+ends)":
493 val == 3? " (continues+continued)":
494 val == 16? " (DataBlock-expected)":"");
495 print_pr_data (msg, msglen, 10);
500 print_p2r_getparameters (const unsigned char *msg, size_t msglen)
502 print_p2r_header ("PC_to_RDR_GetParameters", msg, msglen);
503 print_pr_data (msg, msglen, 7);
508 print_p2r_resetparameters (const unsigned char *msg, size_t msglen)
510 print_p2r_header ("PC_to_RDR_ResetParameters", msg, msglen);
511 print_pr_data (msg, msglen, 7);
516 print_p2r_setparameters (const unsigned char *msg, size_t msglen)
518 print_p2r_header ("PC_to_RDR_SetParameters", msg, msglen);
521 DEBUGOUT_1 (" bProtocolNum ......: 0x%02x\n", msg[7]);
522 print_pr_data (msg, msglen, 8);
527 print_p2r_escape (const unsigned char *msg, size_t msglen)
529 print_p2r_header ("PC_to_RDR_Escape", msg, msglen);
530 print_pr_data (msg, msglen, 7);
535 print_p2r_iccclock (const unsigned char *msg, size_t msglen)
537 print_p2r_header ("PC_to_RDR_IccClock", msg, msglen);
540 DEBUGOUT_1 (" bClockCommand .....: 0x%02x\n", msg[7]);
541 print_pr_data (msg, msglen, 8);
546 print_p2r_to0apdu (const unsigned char *msg, size_t msglen)
548 print_p2r_header ("PC_to_RDR_T0APDU", msg, msglen);
551 DEBUGOUT_1 (" bmChanges .........: 0x%02x\n", msg[7]);
552 DEBUGOUT_1 (" bClassGetResponse .: 0x%02x\n", msg[8]);
553 DEBUGOUT_1 (" bClassEnvelope ....: 0x%02x\n", msg[9]);
554 print_pr_data (msg, msglen, 10);
559 print_p2r_secure (const unsigned char *msg, size_t msglen)
563 print_p2r_header ("PC_to_RDR_Secure", msg, msglen);
566 DEBUGOUT_1 (" bBMI ..............: 0x%02x\n", msg[7]);
567 val = convert_le_u16 (msg+8);
568 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
569 val == 1? " (continued)":
570 val == 2? " (continues+ends)":
571 val == 3? " (continues+continued)":
572 val == 16? " (DataBlock-expected)":"");
573 print_pr_data (msg, msglen, 10);
578 print_p2r_mechanical (const unsigned char *msg, size_t msglen)
580 print_p2r_header ("PC_to_RDR_Mechanical", msg, msglen);
583 DEBUGOUT_1 (" bFunction .........: 0x%02x\n", msg[7]);
584 print_pr_data (msg, msglen, 8);
589 print_p2r_abort (const unsigned char *msg, size_t msglen)
591 print_p2r_header ("PC_to_RDR_Abort", msg, msglen);
592 print_pr_data (msg, msglen, 7);
597 print_p2r_setdatarate (const unsigned char *msg, size_t msglen)
599 print_p2r_header ("PC_to_RDR_SetDataRate", msg, msglen);
602 print_pr_data (msg, msglen, 7);
607 print_p2r_unknown (const unsigned char *msg, size_t msglen)
609 print_p2r_header ("Unknown PC_to_RDR command", msg, msglen);
612 print_pr_data (msg, msglen, 0);
617 print_r2p_header (const char *name, const unsigned char *msg, size_t msglen)
619 DEBUGOUT_1 ("%s:\n", name);
622 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
623 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
624 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
625 DEBUGOUT_1 (" bStatus ...........: %u\n", msg[7]);
627 DEBUGOUT_1 (" bError ............: %u\n", msg[8]);
632 print_r2p_datablock (const unsigned char *msg, size_t msglen)
634 print_r2p_header ("RDR_to_PC_DataBlock", msg, msglen);
638 DEBUGOUT_2 (" bChainParameter ...: 0x%02x%s\n", msg[9],
639 msg[9] == 1? " (continued)":
640 msg[9] == 2? " (continues+ends)":
641 msg[9] == 3? " (continues+continued)":
642 msg[9] == 16? " (XferBlock-expected)":"");
643 print_pr_data (msg, msglen, 10);
648 print_r2p_slotstatus (const unsigned char *msg, size_t msglen)
650 print_r2p_header ("RDR_to_PC_SlotStatus", msg, msglen);
653 DEBUGOUT_2 (" bClockStatus ......: 0x%02x%s\n", msg[9],
654 msg[9] == 0? " (running)":
655 msg[9] == 1? " (stopped-L)":
656 msg[9] == 2? " (stopped-H)":
657 msg[9] == 3? " (stopped)":"");
658 print_pr_data (msg, msglen, 10);
663 print_r2p_parameters (const unsigned char *msg, size_t msglen)
665 print_r2p_header ("RDR_to_PC_Parameters", msg, msglen);
669 DEBUGOUT_1 (" protocol ..........: T=%d\n", msg[9]);
670 if (msglen == 17 && msg[9] == 1)
673 DEBUGOUT_1 (" bmFindexDindex ....: %02X\n", msg[10]);
674 DEBUGOUT_1 (" bmTCCKST1 .........: %02X\n", msg[11]);
675 DEBUGOUT_1 (" bGuardTimeT1 ......: %02X\n", msg[12]);
676 DEBUGOUT_1 (" bmWaitingIntegersT1: %02X\n", msg[13]);
677 DEBUGOUT_1 (" bClockStop ........: %02X\n", msg[14]);
678 DEBUGOUT_1 (" bIFSC .............: %d\n", msg[15]);
679 DEBUGOUT_1 (" bNadValue .........: %d\n", msg[16]);
682 print_pr_data (msg, msglen, 10);
687 print_r2p_escape (const unsigned char *msg, size_t msglen)
689 print_r2p_header ("RDR_to_PC_Escape", msg, msglen);
692 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
693 print_pr_data (msg, msglen, 10);
698 print_r2p_datarate (const unsigned char *msg, size_t msglen)
700 print_r2p_header ("RDR_to_PC_DataRate", msg, msglen);
705 DEBUGOUT_1 (" dwClockFrequency ..: %u\n", convert_le_u32 (msg+10));
706 DEBUGOUT_1 (" dwDataRate ..... ..: %u\n", convert_le_u32 (msg+14));
707 print_pr_data (msg, msglen, 18);
710 print_pr_data (msg, msglen, 10);
715 print_r2p_unknown (const unsigned char *msg, size_t msglen)
717 print_r2p_header ("Unknown RDR_to_PC command", msg, msglen);
720 DEBUGOUT_1 (" bMessageType ......: %02X\n", msg[0]);
721 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
722 print_pr_data (msg, msglen, 10);
726 /* Parse a CCID descriptor, optionally print all available features
727 and test whether this reader is usable by this driver. Returns 0
730 Note, that this code is based on the one in lsusb.c of the
731 usb-utils package, I wrote on 2003-09-01. -wk. */
733 parse_ccid_descriptor (ccid_driver_t handle, unsigned short bcd_device,
734 const unsigned char *buf, size_t buflen)
738 int have_t1 = 0, have_tpdu=0;
740 handle->nonnull_nad = 0;
741 handle->auto_ifsd = 0;
742 handle->max_ifsd = 32;
743 handle->has_pinpad = 0;
744 handle->apdu_level = 0;
745 handle->auto_voltage = 0;
746 handle->auto_param = 0;
747 handle->auto_pps = 0;
748 DEBUGOUT_3 ("idVendor: %04X idProduct: %04X bcdDevice: %04X\n",
749 handle->id_vendor, handle->id_product, bcd_device);
750 if (buflen < 54 || buf[0] < 54)
752 DEBUGOUT ("CCID device descriptor is too short\n");
756 DEBUGOUT ("ChipCard Interface Descriptor:\n");
757 DEBUGOUT_1 (" bLength %5u\n", buf[0]);
758 DEBUGOUT_1 (" bDescriptorType %5u\n", buf[1]);
759 DEBUGOUT_2 (" bcdCCID %2x.%02x", buf[3], buf[2]);
760 if (buf[3] != 1 || buf[2] != 0)
761 DEBUGOUT_CONT(" (Warning: Only accurate for version 1.0)");
764 DEBUGOUT_1 (" nMaxSlotIndex %5u\n", buf[4]);
765 DEBUGOUT_2 (" bVoltageSupport %5u %s\n",
766 buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V"
767 : buf[5] == 3? "1.8V":"?"));
769 us = convert_le_u32 (buf+6);
770 DEBUGOUT_1 (" dwProtocols %5u ", us);
772 DEBUGOUT_CONT (" T=0");
775 DEBUGOUT_CONT (" T=1");
779 DEBUGOUT_CONT (" (Invalid values detected)");
782 us = convert_le_u32(buf+10);
783 DEBUGOUT_1 (" dwDefaultClock %5u\n", us);
784 us = convert_le_u32(buf+14);
785 DEBUGOUT_1 (" dwMaxiumumClock %5u\n", us);
786 DEBUGOUT_1 (" bNumClockSupported %5u\n", buf[18]);
787 us = convert_le_u32(buf+19);
788 DEBUGOUT_1 (" dwDataRate %7u bps\n", us);
789 us = convert_le_u32(buf+23);
790 DEBUGOUT_1 (" dwMaxDataRate %7u bps\n", us);
791 DEBUGOUT_1 (" bNumDataRatesSupp. %5u\n", buf[27]);
793 us = convert_le_u32(buf+28);
794 DEBUGOUT_1 (" dwMaxIFSD %5u\n", us);
795 handle->max_ifsd = us;
797 us = convert_le_u32(buf+32);
798 DEBUGOUT_1 (" dwSyncProtocols %08X ", us);
800 DEBUGOUT_CONT ( " 2-wire");
802 DEBUGOUT_CONT ( " 3-wire");
804 DEBUGOUT_CONT ( " I2C");
807 us = convert_le_u32(buf+36);
808 DEBUGOUT_1 (" dwMechanical %08X ", us);
810 DEBUGOUT_CONT (" accept");
812 DEBUGOUT_CONT (" eject");
814 DEBUGOUT_CONT (" capture");
816 DEBUGOUT_CONT (" lock");
819 us = convert_le_u32(buf+40);
820 DEBUGOUT_1 (" dwFeatures %08X\n", us);
823 DEBUGOUT (" Auto configuration based on ATR (assumes auto voltage)\n");
824 handle->auto_voltage = 1;
827 DEBUGOUT (" Auto activation on insert\n");
830 DEBUGOUT (" Auto voltage selection\n");
831 handle->auto_voltage = 1;
834 DEBUGOUT (" Auto clock change\n");
836 DEBUGOUT (" Auto baud rate change\n");
839 DEBUGOUT (" Auto parameter negotiation made by CCID\n");
840 handle->auto_param = 1;
842 else if ((us & 0x0080))
844 DEBUGOUT (" Auto PPS made by CCID\n");
845 handle->auto_pps = 1;
847 if ((us & (0x0040 | 0x0080)) == (0x0040 | 0x0080))
848 DEBUGOUT (" WARNING: conflicting negotiation features\n");
851 DEBUGOUT (" CCID can set ICC in clock stop mode\n");
854 DEBUGOUT (" NAD value other than 0x00 accepted\n");
855 handle->nonnull_nad = 1;
859 DEBUGOUT (" Auto IFSD exchange\n");
860 handle->auto_ifsd = 1;
863 if ((us & 0x00010000))
865 DEBUGOUT (" TPDU level exchange\n");
868 else if ((us & 0x00020000))
870 DEBUGOUT (" Short APDU level exchange\n");
871 handle->apdu_level = 1;
873 else if ((us & 0x00040000))
875 DEBUGOUT (" Short and extended APDU level exchange\n");
876 handle->apdu_level = 2;
878 else if ((us & 0x00070000))
879 DEBUGOUT (" WARNING: conflicting exchange levels\n");
881 us = convert_le_u32(buf+44);
882 DEBUGOUT_1 (" dwMaxCCIDMsgLen %5u\n", us);
883 handle->max_ccid_msglen = us;
885 DEBUGOUT ( " bClassGetResponse ");
887 DEBUGOUT_CONT ("echo\n");
889 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
891 DEBUGOUT ( " bClassEnvelope ");
893 DEBUGOUT_CONT ("echo\n");
895 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
897 DEBUGOUT ( " wlcdLayout ");
898 if (!buf[50] && !buf[51])
899 DEBUGOUT_CONT ("none\n");
901 DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]);
903 DEBUGOUT_1 (" bPINSupport %5u ", buf[52]);
906 DEBUGOUT_CONT ( " verification");
907 handle->has_pinpad |= 1;
911 DEBUGOUT_CONT ( " modification");
912 handle->has_pinpad |= 2;
916 DEBUGOUT_1 (" bMaxCCIDBusySlots %5u\n", buf[53]);
921 for (i=54; i < buf[0]-54; i++)
922 DEBUGOUT_CONT_1 (" %02X", buf[i]);
926 if (!have_t1 || !(have_tpdu || handle->apdu_level))
928 DEBUGOUT ("this drivers requires that the reader supports T=1, "
929 "TPDU or APDU level exchange - this is not available\n");
934 /* SCM drivers get stuck in their internal USB stack if they try to
935 send a frame of n*wMaxPacketSize back to us. Given that
936 wMaxPacketSize is 64 for these readers we set the IFSD to a value
938 64 - 10 CCID header - 4 T1frame - 2 reserved = 48
945 0x5117 - SCR 3320 USB ID-000 reader
946 seems to be very slow but enabling this workaround boosts the
947 performance to a more or less acceptable level (tested by David).
950 if (handle->id_vendor == VENDOR_SCM
951 && handle->max_ifsd > 48
952 && ( (handle->id_product == SCM_SCR331 && bcd_device < 0x0516)
953 ||(handle->id_product == SCM_SCR331DI && bcd_device < 0x0620)
954 ||(handle->id_product == SCM_SCR335 && bcd_device < 0x0514)
955 ||(handle->id_product == SCM_SPR532 && bcd_device < 0x0504)
956 ||(handle->id_product == SCM_SCR3320 && bcd_device < 0x0522)
959 DEBUGOUT ("enabling workaround for buggy SCM readers\n");
960 handle->max_ifsd = 48;
963 if (handle->id_vendor == VENDOR_GEMPC)
965 DEBUGOUT ("enabling product quirk: disable non-null NAD\n");
966 handle->nonnull_nad = 0;
974 get_escaped_usb_string (libusb_device_handle *idev, int idx,
975 const char *prefix, const char *suffix)
978 unsigned char buf[280];
987 /* Fixme: The next line is for the current Valgrid without support
989 memset (buf, 0, sizeof buf);
991 /* First get the list of supported languages and use the first one.
992 If we do don't find it we try to use English. Note that this is
993 all in a 2 bute Unicode encoding using little endian. */
997 rc = libusb_control_transfer (idev, LIBUSB_ENDPOINT_IN,
998 LIBUSB_REQUEST_GET_DESCRIPTOR,
999 (LIBUSB_DT_STRING << 8), 0,
1000 buf, sizeof buf, 1000 /* ms timeout */);
1005 langid = 0x0409; /* English. */
1007 langid = (buf[3] << 8) | buf[2];
1012 rc = libusb_control_transfer (idev, LIBUSB_ENDPOINT_IN,
1013 LIBUSB_REQUEST_GET_DESCRIPTOR,
1014 (LIBUSB_DT_STRING << 8) + idx, langid,
1015 buf, sizeof buf, 1000 /* ms timeout */);
1019 if (rc < 2 || buf[1] != LIBUSB_DT_STRING)
1020 return NULL; /* Error or not a string. */
1023 return NULL; /* Larger than our buffer. */
1025 for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2)
1028 n++; /* High byte set. */
1029 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
1035 result = malloc (strlen (prefix) + n + strlen (suffix) + 1);
1039 strcpy (result, prefix);
1040 n = strlen (prefix);
1041 for (s=buf+2, i=2; i+1 < len; i += 2, s += 2)
1044 result[n++] = '\xff'; /* High byte set. */
1045 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
1047 sprintf (result+n, "%%%02X", *s);
1053 strcpy (result+n, suffix);
1058 /* This function creates an reader id to be used to find the same
1059 physical reader after a reset. It returns an allocated and possibly
1060 percent escaped string or NULL if not enough memory is available. */
1062 make_reader_id (libusb_device_handle *idev,
1063 unsigned int vendor, unsigned int product,
1064 unsigned char serialno_index)
1069 sprintf (prefix, "%04X:%04X:", (vendor & 0xffff), (product & 0xffff));
1070 rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0");
1073 rid = malloc (strlen (prefix) + 3 + 1);
1076 strcpy (rid, prefix);
1077 strcat (rid, "X:0");
1083 /* Helper to find the endpoint from an interface descriptor. */
1085 find_endpoint (const struct libusb_interface_descriptor *ifcdesc, int mode)
1088 int want_bulk_in = 0;
1091 want_bulk_in = 0x80;
1092 for (no=0; no < ifcdesc->bNumEndpoints; no++)
1094 const struct libusb_endpoint_descriptor *ep = ifcdesc->endpoint + no;
1095 if (ep->bDescriptorType != LIBUSB_DT_ENDPOINT)
1098 && ((ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
1099 == LIBUSB_TRANSFER_TYPE_INTERRUPT)
1100 && (ep->bEndpointAddress & 0x80))
1101 return ep->bEndpointAddress;
1102 else if ((mode == 0 || mode == 1)
1103 && ((ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
1104 == LIBUSB_TRANSFER_TYPE_BULK)
1105 && (ep->bEndpointAddress & 0x80) == want_bulk_in)
1106 return ep->bEndpointAddress;
1113 /* Helper for scan_devices. This function returns true if a
1114 requested device has been found or the caller should stop scanning
1115 for other reasons. */
1117 scan_usb_device (int *count, char **rid_list, struct libusb_device *dev)
1121 const struct libusb_interface_descriptor *ifcdesc;
1123 libusb_device_handle *idev = NULL;
1125 struct libusb_config_descriptor *config;
1126 struct libusb_device_descriptor desc;
1129 err = libusb_get_device_descriptor (dev, &desc);
1133 err = libusb_get_active_config_descriptor (dev, &config);
1137 for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
1138 for (set_no=0; set_no < config->interface[ifc_no].num_altsetting; set_no++)
1140 ifcdesc = (config->interface[ifc_no].altsetting + set_no);
1141 /* The second condition is for older SCM SPR 532 who did
1142 not know about the assigned CCID class. The third
1143 condition does the same for a Cherry SmartTerminal
1144 ST-2000. Instead of trying to interpret the strings
1145 we simply check the product ID. */
1146 if (ifcdesc && ifcdesc->extra
1147 && ((ifcdesc->bInterfaceClass == 11
1148 && ifcdesc->bInterfaceSubClass == 0
1149 && ifcdesc->bInterfaceProtocol == 0)
1150 || (ifcdesc->bInterfaceClass == 255
1151 && desc.idVendor == VENDOR_SCM
1152 && desc.idProduct == SCM_SPR532)
1153 || (ifcdesc->bInterfaceClass == 255
1154 && desc.idVendor == VENDOR_CHERRY
1155 && desc.idProduct == CHERRY_ST2000)))
1159 err = libusb_open (dev, &idev);
1162 DEBUGOUT_1 ("usb_open failed: %s\n", libusb_error_name (err));
1163 continue; /* with next setting. */
1166 rid = make_reader_id (idev, desc.idVendor, desc.idProduct,
1167 desc.iSerialNumber);
1170 libusb_free_config_descriptor (config);
1174 /* We are collecting infos about all available CCID
1175 readers. Store them and continue. */
1176 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n", *count, rid);
1177 p = malloc ((*rid_list? strlen (*rid_list):0) + 1
1178 + strlen (rid) + 1);
1184 strcat (p, *rid_list);
1191 else /* Out of memory. */
1193 libusb_free_config_descriptor (config);
1199 libusb_close (idev);
1204 libusb_free_config_descriptor (config);
1207 /* Scan all CCID devices.
1209 The function returns 0 if a reader has been found or when a scan
1210 returned without error.
1212 R_RID should be the address where to store the list of reader_ids
1213 we found. If on return this list is empty, no CCID device has been
1214 found; otherwise it points to an allocated linked list of reader
1218 scan_devices (char **r_rid)
1220 char *rid_list = NULL;
1222 libusb_device **dev_list = NULL;
1227 /* Set return values to a default. */
1231 n = libusb_get_device_list (NULL, &dev_list);
1233 for (i = 0; i < n; i++)
1236 scan_usb_device (&count, &rid_list, dev);
1239 libusb_free_device_list (dev_list, 1);
1246 /* Set the level of debugging to LEVEL and return the old level. -1
1247 just returns the old level. A level of 0 disables debugging, 1
1248 enables debugging, 2 enables additional tracing of the T=1
1249 protocol, 3 additionally enables debugging for GetSlotStatus, other
1250 values are not yet defined.
1252 Note that libusb may provide its own debugging feature which is
1253 enabled by setting the envvar USB_DEBUG. */
1255 ccid_set_debug_level (int level)
1257 int old = debug_level;
1259 debug_level = level;
1265 ccid_get_reader_list (void)
1269 if (!initialized_usb)
1272 if ((rc = libusb_init (NULL)))
1274 DEBUGOUT_1 ("usb_init failed: %s.\n", libusb_error_name (rc));
1277 initialized_usb = 1;
1280 if (scan_devices (&reader_list))
1281 return NULL; /* Error. */
1286 /* Vendor specific custom initialization. */
1288 ccid_vendor_specific_init (ccid_driver_t handle)
1292 if (handle->id_vendor == VENDOR_VEGA && handle->id_product == VEGA_ALPHA)
1295 * Vega alpha has a feature to show retry counter on the pinpad
1296 * display. But it assumes that the card returns the value of
1297 * retry counter by VERIFY with empty data (return code of
1298 * 63Cx). Unfortunately, existing OpenPGP cards don't support
1299 * VERIFY command with empty data. This vendor specific command
1300 * sequence is to disable the feature.
1302 const unsigned char cmd[] = { '\xb5', '\x01', '\x00', '\x03', '\x00' };
1304 r = send_escape_cmd (handle, cmd, sizeof (cmd), NULL, 0, NULL);
1306 else if (handle->id_vendor == VENDOR_SCM && handle->id_product == SCM_SPR532)
1309 * It seems that SEQ may be out of sync between host and the card reader,
1310 * and SET_INTERFACE doesn't reset it. Make sure it works at the init.
1312 abort_cmd (handle, 0, 1);
1315 if (r != 0 && r != CCID_DRIVER_ERR_CARD_INACTIVE
1316 && r != CCID_DRIVER_ERR_NO_CARD)
1324 ccid_vendor_specific_setup (ccid_driver_t handle)
1326 if (handle->id_vendor == VENDOR_SCM && handle->id_product == SCM_SPR532)
1328 libusb_clear_halt (handle->idev, handle->ep_intr);
1335 ccid_vendor_specific_pinpad_setup (ccid_driver_t handle)
1337 if (handle->id_vendor == VENDOR_SCM && handle->id_product == SCM_SPR532)
1339 DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n");
1340 send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3,
1348 ccid_dev_scan (int *idx_max_p, void **t_p)
1361 if (!initialized_usb)
1364 if ((rc = libusb_init (NULL)))
1366 DEBUGOUT_1 ("usb_init failed: %s.\n", libusb_error_name (rc));
1367 return gpg_error (GPG_ERR_ENODEV);
1369 initialized_usb = 1;
1372 n = libusb_get_device_list (NULL, &ccid_usb_dev_list);
1373 for (i = 0; i < n; i++)
1375 struct libusb_config_descriptor *config;
1376 struct libusb_device_descriptor desc;
1378 dev = ccid_usb_dev_list[i];
1380 if (libusb_get_device_descriptor (dev, &desc))
1383 if (libusb_get_active_config_descriptor (dev, &config))
1386 for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
1387 for (set_no=0; set_no < config->interface[ifc_no].num_altsetting;
1390 const struct libusb_interface_descriptor *ifcdesc;
1392 ifcdesc = &config->interface[ifc_no].altsetting[set_no];
1393 /* The second condition is for older SCM SPR 532 who did
1394 not know about the assigned CCID class. The third
1395 condition does the same for a Cherry SmartTerminal
1396 ST-2000. Instead of trying to interpret the strings
1397 we simply check the product ID. */
1398 if (ifcdesc && ifcdesc->extra
1399 && ((ifcdesc->bInterfaceClass == 11
1400 && ifcdesc->bInterfaceSubClass == 0
1401 && ifcdesc->bInterfaceProtocol == 0)
1402 || (ifcdesc->bInterfaceClass == 255
1403 && desc.idVendor == VENDOR_SCM
1404 && desc.idProduct == SCM_SPR532)
1405 || (ifcdesc->bInterfaceClass == 255
1406 && desc.idVendor == VENDOR_CHERRY
1407 && desc.idProduct == CHERRY_ST2000)))
1409 /* Found a reader. */
1410 unsigned char *ifcdesc_extra;
1412 ifcdesc_extra = malloc (ifcdesc->extra_length);
1415 err = gpg_error_from_syserror ();
1416 libusb_free_config_descriptor (config);
1419 memcpy (ifcdesc_extra, ifcdesc->extra, ifcdesc->extra_length);
1421 ccid_dev_table[idx].n = i;
1422 ccid_dev_table[idx].interface_number = ifc_no;
1423 ccid_dev_table[idx].setting_number = set_no;
1424 ccid_dev_table[idx].ifcdesc_extra = ifcdesc_extra;
1425 ccid_dev_table[idx].ifcdesc_extra_len = ifcdesc->extra_length;
1426 ccid_dev_table[idx].ep_bulk_out = find_endpoint (ifcdesc, 0);
1427 ccid_dev_table[idx].ep_bulk_in = find_endpoint (ifcdesc, 1);
1428 ccid_dev_table[idx].ep_intr = find_endpoint (ifcdesc, 2);
1431 if (idx >= CCID_MAX_DEVICE)
1433 libusb_free_config_descriptor (config);
1440 libusb_free_config_descriptor (config);
1447 for (i = 0; i < idx; i++)
1449 free (ccid_dev_table[i].ifcdesc_extra);
1450 ccid_dev_table[i].n = 0;
1451 ccid_dev_table[i].interface_number = 0;
1452 ccid_dev_table[i].setting_number = 0;
1453 ccid_dev_table[i].ifcdesc_extra = NULL;
1454 ccid_dev_table[i].ifcdesc_extra_len = 0;
1455 ccid_dev_table[i].ep_bulk_out = 0;
1456 ccid_dev_table[i].ep_bulk_in = 0;
1457 ccid_dev_table[i].ep_intr = 0;
1459 libusb_free_device_list (ccid_usb_dev_list, 1);
1460 ccid_usb_dev_list = NULL;
1466 *t_p = ccid_dev_table;
1475 ccid_dev_scan_finish (void *tbl0, int max)
1478 struct ccid_dev_table *tbl = tbl0;
1480 for (i = 0; i < max; i++)
1482 free (tbl[i].ifcdesc_extra);
1484 tbl[i].interface_number = 0;
1485 tbl[i].setting_number = 0;
1486 tbl[i].ifcdesc_extra = NULL;
1487 tbl[i].ifcdesc_extra_len = 0;
1488 tbl[i].ep_bulk_out = 0;
1489 tbl[i].ep_bulk_in = 0;
1492 libusb_free_device_list (ccid_usb_dev_list, 1);
1493 ccid_usb_dev_list = NULL;
1497 ccid_get_BAI (int idx, void *tbl0)
1500 int bus, addr, intf;
1503 struct ccid_dev_table *tbl = tbl0;
1506 dev = ccid_usb_dev_list[n];
1508 bus = libusb_get_bus_number (dev);
1509 addr = libusb_get_device_address (dev);
1510 intf = tbl[idx].interface_number;
1511 bai = (bus << 16) | (addr << 8) | intf;
1517 ccid_compare_BAI (ccid_driver_t handle, unsigned int bai)
1519 return handle->bai == bai;
1524 intr_cb (struct libusb_transfer *transfer)
1526 ccid_driver_t handle = transfer->user_data;
1528 DEBUGOUT_2 ("CCID: interrupt callback %d (%d)\n",
1529 transfer->status, transfer->actual_length);
1531 if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT)
1536 /* Submit the URB again to keep watching the INTERRUPT transfer. */
1537 err = libusb_submit_transfer (transfer);
1538 if (err == LIBUSB_ERROR_NO_DEVICE)
1539 goto device_removed;
1541 DEBUGOUT_1 ("CCID submit transfer again %d\n", err);
1543 else if (transfer->status == LIBUSB_TRANSFER_COMPLETED)
1545 size_t len = transfer->actual_length;
1546 unsigned char *p = transfer->buffer;
1547 int card_removed = 0;
1551 if (*p == RDR_to_PC_NotifySlotChange)
1556 DEBUGOUT_1 ("CCID: NotifySlotChange: %02x\n", p[1]);
1566 else if (*p == RDR_to_PC_HardwareError)
1571 DEBUGOUT_1 ("CCID: hardware error detected: %02x\n", p[3]);
1577 DEBUGOUT_1 ("CCID: unknown intr: %02x\n", p[0]);
1584 DEBUGOUT ("CCID: card removed\n");
1585 handle->powered_off = 1;
1586 #if defined(GNUPG_MAJOR_VERSION)
1587 scd_kick_the_loop ();
1592 /* Event other than card removal. */
1596 else if (transfer->status == LIBUSB_TRANSFER_CANCELLED)
1597 handle->powered_off = 1;
1598 else if (transfer->status == LIBUSB_TRANSFER_OVERFLOW)
1600 /* Something goes wrong. Ignore. */
1601 DEBUGOUT ("CCID: interrupt transfer overflow\n");
1606 DEBUGOUT ("CCID: device removed\n");
1607 handle->powered_off = 1;
1608 #if defined(GNUPG_MAJOR_VERSION)
1609 scd_kick_the_loop ();
1615 ccid_setup_intr (ccid_driver_t handle)
1617 struct libusb_transfer *transfer;
1620 transfer = libusb_alloc_transfer (0);
1621 handle->transfer = transfer;
1622 libusb_fill_interrupt_transfer (transfer, handle->idev, handle->ep_intr,
1623 handle->intr_buf, sizeof (handle->intr_buf),
1624 intr_cb, handle, 0);
1625 err = libusb_submit_transfer (transfer);
1626 DEBUGOUT_2 ("CCID submit transfer (%x): %d", handle->ep_intr, err);
1631 ccid_usb_thread (void *arg)
1633 libusb_context *ctx = arg;
1635 while (ccid_usb_thread_is_alive)
1640 libusb_handle_events_completed (ctx, NULL);
1651 ccid_open_usb_reader (const char *spec_reader_name,
1652 int idx, void *ccid_table0,
1653 ccid_driver_t *handle, char **rdrname_p)
1656 libusb_device_handle *idev = NULL;
1660 struct libusb_device_descriptor desc;
1664 struct ccid_dev_table *ccid_table = ccid_table0;
1666 n = ccid_table[idx].n;
1667 ifc_no = ccid_table[idx].interface_number;
1668 set_no = ccid_table[idx].setting_number;
1670 dev = ccid_usb_dev_list[n];
1671 bus = libusb_get_bus_number (dev);
1672 addr = libusb_get_device_address (dev);
1673 bai = (bus << 16) | (addr << 8) | ifc_no;
1675 rc = libusb_open (dev, &idev);
1678 DEBUGOUT_1 ("usb_open failed: %s\n", libusb_error_name (rc));
1681 return map_libusb_error (rc);
1684 if (ccid_usb_thread_is_alive++ == 0)
1690 err = npth_attr_init (&tattr);
1693 DEBUGOUT_1 ("npth_attr_init failed: %s\n", strerror (err));
1699 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
1700 err = npth_create (&thread, &tattr, ccid_usb_thread, NULL);
1703 DEBUGOUT_1 ("npth_create failed: %s\n", strerror (err));
1709 npth_attr_destroy (&tattr);
1712 rc = libusb_get_device_descriptor (dev, &desc);
1715 DEBUGOUT ("get_device_descripor failed\n");
1716 rc = map_libusb_error (rc);
1720 rid = make_reader_id (idev, desc.idVendor, desc.idProduct,
1721 desc.iSerialNumber);
1723 /* Check to see if reader name matches the spec. */
1724 if (spec_reader_name
1725 && strncmp (rid, spec_reader_name, strlen (spec_reader_name)))
1727 DEBUGOUT ("device not matched\n");
1728 rc = CCID_DRIVER_ERR_NO_READER;
1732 (*handle)->id_vendor = desc.idVendor;
1733 (*handle)->id_product = desc.idProduct;
1734 (*handle)->idev = idev;
1735 (*handle)->bai = bai;
1736 (*handle)->ifc_no = ifc_no;
1737 (*handle)->ep_bulk_out = ccid_table[idx].ep_bulk_out;
1738 (*handle)->ep_bulk_in = ccid_table[idx].ep_bulk_in;
1739 (*handle)->ep_intr = ccid_table[idx].ep_intr;
1741 DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n", idx, rid);
1743 if (parse_ccid_descriptor (*handle, desc.bcdDevice,
1744 ccid_table[idx].ifcdesc_extra,
1745 ccid_table[idx].ifcdesc_extra_len))
1747 DEBUGOUT ("device not supported\n");
1748 rc = CCID_DRIVER_ERR_NO_READER;
1752 rc = libusb_claim_interface (idev, ifc_no);
1755 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1756 rc = map_libusb_error (rc);
1760 /* Submit SET_INTERFACE control transfer which can reset the device. */
1761 rc = libusb_set_interface_alt_setting (idev, ifc_no, set_no);
1764 DEBUGOUT_1 ("usb_set_interface_alt_setting failed: %d\n", rc);
1765 rc = map_libusb_error (rc);
1769 rc = ccid_vendor_specific_init (*handle);
1774 --ccid_usb_thread_is_alive;
1776 libusb_release_interface (idev, ifc_no);
1777 libusb_close (idev);
1792 /* Open the reader with the internal number READERNO and return a
1793 pointer to be used as handle in HANDLE. Returns 0 on success. */
1795 ccid_open_reader (const char *spec_reader_name, int idx,
1797 ccid_driver_t *handle, char **rdrname_p)
1799 struct ccid_dev_table *ccid_table = ccid_table0;
1801 *handle = calloc (1, sizeof **handle);
1804 DEBUGOUT ("out of memory\n");
1805 return CCID_DRIVER_ERR_OUT_OF_CORE;
1808 return ccid_open_usb_reader (spec_reader_name, idx, ccid_table,
1814 ccid_require_get_status (ccid_driver_t handle)
1816 /* When a card reader supports interrupt transfer to check the
1817 status of card, it is possible to submit only an interrupt
1818 transfer, and no check is required by application layer. USB can
1819 detect removal of a card and can detect removal of a reader.
1821 if (handle->ep_intr >= 0)
1823 if (handle->id_vendor != VENDOR_SCM)
1827 * For card reader with interrupt transfer support, ideally,
1828 * removal is detected by intr_cb, but some card reader
1829 * (e.g. SPR532) has a possible case of missing report to
1830 * intr_cb, and another case of valid report to intr_cb.
1832 * For such a reader, the removal should be able to be detected
1833 * by PC_to_RDR_GetSlotStatus, too. Thus, calls to
1834 * ccid_slot_status should go on wire even if "on_wire" is not
1838 if (handle->transfer == NULL)
1842 /* Libusb actually detects the removal of USB device in use.
1843 However, there is no good API to handle the removal (yet),
1844 cleanly and with good portability.
1846 There is libusb_set_pollfd_notifiers function, but it doesn't
1847 offer libusb_device_handle* data to its callback. So, when it
1848 watches multiple devices, there is no way to know which device is
1851 Once, we will have a good programming interface of libusb, we can
1852 list tokens (with no interrupt transfer support, but always with
1853 card inserted) here to return 0, so that scdaemon can submit
1854 minimum packet on wire.
1860 send_power_off (ccid_driver_t handle)
1863 unsigned char msg[100];
1865 unsigned char seqno;
1867 msg[0] = PC_to_RDR_IccPowerOff;
1868 msg[5] = 0; /* slot */
1869 msg[6] = seqno = handle->seqno++;
1870 msg[7] = 0; /* RFU */
1871 msg[8] = 0; /* RFU */
1872 msg[9] = 0; /* RFU */
1873 set_msg_len (msg, 0);
1876 rc = bulk_out (handle, msg, msglen, 0);
1878 bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1884 do_close_reader (ccid_driver_t handle)
1888 if (!handle->powered_off)
1889 send_power_off (handle);
1891 if (handle->transfer)
1893 if (!handle->powered_off)
1895 DEBUGOUT ("libusb_cancel_transfer\n");
1897 rc = libusb_cancel_transfer (handle->transfer);
1898 if (rc != LIBUSB_ERROR_NOT_FOUND)
1899 while (!handle->powered_off)
1901 DEBUGOUT ("libusb_handle_events_completed\n");
1905 libusb_handle_events_completed (NULL, &handle->powered_off);
1912 libusb_free_transfer (handle->transfer);
1913 handle->transfer = NULL;
1916 DEBUGOUT ("libusb_release_interface and libusb_close\n");
1917 libusb_release_interface (handle->idev, handle->ifc_no);
1918 --ccid_usb_thread_is_alive;
1919 libusb_close (handle->idev);
1920 handle->idev = NULL;
1925 ccid_set_progress_cb (ccid_driver_t handle,
1926 void (*cb)(void *, const char *, int, int, int),
1930 return CCID_DRIVER_ERR_INV_VALUE;
1932 handle->progress_cb = cb;
1933 handle->progress_cb_arg = cb_arg;
1939 ccid_set_prompt_cb (ccid_driver_t handle,
1940 void (*cb)(void *, int), void *cb_arg)
1943 return CCID_DRIVER_ERR_INV_VALUE;
1945 handle->prompt_cb = cb;
1946 handle->prompt_cb_arg = cb_arg;
1951 /* Close the reader HANDLE. */
1953 ccid_close_reader (ccid_driver_t handle)
1958 do_close_reader (handle);
1964 /* Return False if a card is present and powered. */
1966 ccid_check_card_presence (ccid_driver_t handle)
1968 (void)handle; /* Not yet implemented. */
1973 /* Write a MSG of length MSGLEN to the designated bulk out endpoint.
1974 Returns 0 on success. */
1976 bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
1982 /* No need to continue and clutter the log with USB write error
1983 messages after we got the first ENODEV. */
1984 if (handle->enodev_seen)
1985 return CCID_DRIVER_ERR_NO_READER;
1987 if (debug_level && (!no_debug || debug_level >= 3))
1989 switch (msglen? msg[0]:0)
1991 case PC_to_RDR_IccPowerOn:
1992 print_p2r_iccpoweron (msg, msglen);
1994 case PC_to_RDR_IccPowerOff:
1995 print_p2r_iccpoweroff (msg, msglen);
1997 case PC_to_RDR_GetSlotStatus:
1998 print_p2r_getslotstatus (msg, msglen);
2000 case PC_to_RDR_XfrBlock:
2001 print_p2r_xfrblock (msg, msglen);
2003 case PC_to_RDR_GetParameters:
2004 print_p2r_getparameters (msg, msglen);
2006 case PC_to_RDR_ResetParameters:
2007 print_p2r_resetparameters (msg, msglen);
2009 case PC_to_RDR_SetParameters:
2010 print_p2r_setparameters (msg, msglen);
2012 case PC_to_RDR_Escape:
2013 print_p2r_escape (msg, msglen);
2015 case PC_to_RDR_IccClock:
2016 print_p2r_iccclock (msg, msglen);
2018 case PC_to_RDR_T0APDU:
2019 print_p2r_to0apdu (msg, msglen);
2021 case PC_to_RDR_Secure:
2022 print_p2r_secure (msg, msglen);
2024 case PC_to_RDR_Mechanical:
2025 print_p2r_mechanical (msg, msglen);
2027 case PC_to_RDR_Abort:
2028 print_p2r_abort (msg, msglen);
2030 case PC_to_RDR_SetDataRate:
2031 print_p2r_setdatarate (msg, msglen);
2034 print_p2r_unknown (msg, msglen);
2042 rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_out,
2043 msg, msglen, &transferred,
2044 5000 /* ms timeout */);
2048 if (rc == 0 && transferred == msglen)
2053 DEBUGOUT_1 ("usb_bulk_write error: %s\n", libusb_error_name (rc));
2054 if (rc == LIBUSB_ERROR_NO_DEVICE)
2056 handle->enodev_seen = 1;
2057 return CCID_DRIVER_ERR_NO_READER;
2065 /* Read a maximum of LENGTH bytes from the bulk in endpoint into
2066 BUFFER and return the actual read number if bytes in NREAD. SEQNO
2067 is the sequence number used to send the request and EXPECTED_TYPE
2068 the type of message we expect. Does checks on the ccid
2069 header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to
2070 avoid debug messages in case of no error; this can be overriden
2071 with a glibal debug level of at least 3. Returns 0 on success. */
2073 bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
2074 size_t *nread, int expected_type, int seqno, int timeout,
2082 /* Fixme: The next line for the current Valgrind without support
2084 memset (buffer, 0, length);
2090 rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_in,
2091 buffer, length, &msglen, bwi*timeout);
2097 DEBUGOUT_1 ("usb_bulk_read error: %s\n", libusb_error_name (rc));
2098 if (rc == LIBUSB_ERROR_NO_DEVICE)
2099 handle->enodev_seen = 1;
2101 return map_libusb_error (rc);
2104 return CCID_DRIVER_ERR_INV_VALUE; /* Faulty libusb. */
2109 DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen);
2110 abort_cmd (handle, seqno, 0);
2111 return CCID_DRIVER_ERR_INV_VALUE;
2115 DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]);
2116 return CCID_DRIVER_ERR_INV_VALUE;
2118 if (buffer[6] != seqno)
2120 DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n",
2122 /* Retry until we are synced again. */
2126 /* We need to handle the time extension request before we check that
2127 we got the expected message type. This is in particular required
2128 for the Cherry keyboard which sends a time extension request for
2130 if (!(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80)
2132 /* Card present and active, time extension requested. */
2133 DEBUGOUT_2 ("time extension requested (%02X,%02X)\n",
2134 buffer[7], buffer[8]);
2137 if (buffer[8] != 0 && buffer[8] != 0xff)
2140 /* Gnuk enhancement to prompt user input by ack button */
2141 if (buffer[8] == 0xff && !notified)
2144 handle->prompt_cb (handle->prompt_cb_arg, 1);
2151 handle->prompt_cb (handle->prompt_cb_arg, 0);
2153 if (buffer[0] != expected_type && buffer[0] != RDR_to_PC_SlotStatus)
2155 DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]);
2156 abort_cmd (handle, seqno, 0);
2157 return CCID_DRIVER_ERR_INV_VALUE;
2160 if (debug_level && (!no_debug || debug_level >= 3))
2164 case RDR_to_PC_DataBlock:
2165 print_r2p_datablock (buffer, msglen);
2167 case RDR_to_PC_SlotStatus:
2168 print_r2p_slotstatus (buffer, msglen);
2170 case RDR_to_PC_Parameters:
2171 print_r2p_parameters (buffer, msglen);
2173 case RDR_to_PC_Escape:
2174 print_r2p_escape (buffer, msglen);
2176 case RDR_to_PC_DataRate:
2177 print_r2p_datarate (buffer, msglen);
2180 print_r2p_unknown (buffer, msglen);
2184 if (CCID_COMMAND_FAILED (buffer))
2185 print_command_failed (buffer);
2187 /* Check whether a card is at all available. Note: If you add new
2188 error codes here, check whether they need to be ignored in
2190 switch ((buffer[7] & 0x03))
2192 case 0: /* no error */ break;
2193 case 1: rc = CCID_DRIVER_ERR_CARD_INACTIVE; break;
2194 case 2: rc = CCID_DRIVER_ERR_NO_CARD; break;
2195 case 3: /* RFU */ break;
2201 * Communication failure by device side.
2202 * Possibly, it was forcibly suspended and resumed.
2204 if (handle->ep_intr < 0)
2206 DEBUGOUT ("CCID: card inactive/removed\n");
2207 handle->powered_off = 1;
2210 #if defined(GNUPG_MAJOR_VERSION)
2211 scd_kick_the_loop ();
2220 /* Send an abort sequence and wait until everything settled. */
2222 abort_cmd (ccid_driver_t handle, int seqno, int init)
2225 unsigned char dummybuf[8];
2226 unsigned char msg[100];
2230 DEBUGOUT_1 ("sending abort sequence for seqno %d\n", seqno);
2231 /* Send the abort command to the control pipe. Note that we don't
2232 need to keep track of sent abort commands because there should
2233 never be another thread using the same slot concurrently. */
2237 rc = libusb_control_transfer (handle->idev,
2238 0x21,/* bmRequestType: host-to-device,
2239 class specific, to interface. */
2241 (seqno << 8 | 0 /* slot */),
2244 1000 /* ms timeout */);
2250 DEBUGOUT_1 ("usb_control_msg error: %s\n", libusb_error_name (rc));
2252 return map_libusb_error (rc);
2255 /* Now send the abort command to the bulk out pipe using the same
2256 SEQNO and SLOT. Do this in a loop to so that all seqno are
2258 seqno--; /* Adjust for next increment. */
2264 msg[0] = PC_to_RDR_Abort;
2265 msg[5] = 0; /* slot */
2267 msg[7] = 0; /* RFU */
2268 msg[8] = 0; /* RFU */
2269 msg[9] = 0; /* RFU */
2271 set_msg_len (msg, 0);
2276 rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_out,
2277 msg, msglen, &transferred,
2278 init? 100: 5000 /* ms timeout */);
2282 if (rc == 0 && transferred == msglen)
2285 DEBUGOUT_1 ("usb_bulk_write error in abort_cmd: %s\n",
2286 libusb_error_name (rc));
2289 return map_libusb_error (rc);
2294 rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_in,
2295 msg, sizeof msg, &msglen,
2296 init? 100: 5000 /*ms timeout*/);
2302 DEBUGOUT_1 ("usb_bulk_read error in abort_cmd: %s\n",
2303 libusb_error_name (rc));
2304 if (init && rc == LIBUSB_ERROR_TIMEOUT)
2307 return map_libusb_error (rc);
2312 DEBUGOUT_1 ("bulk-in msg in abort_cmd too short (%u)\n",
2313 (unsigned int)msglen);
2314 return CCID_DRIVER_ERR_INV_VALUE;
2318 DEBUGOUT_1 ("unexpected bulk-in slot (%d) in abort_cmd\n", msg[5]);
2319 return CCID_DRIVER_ERR_INV_VALUE;
2322 DEBUGOUT_3 ("status: %02X error: %02X octet[9]: %02X\n",
2323 msg[7], msg[8], msg[9]);
2324 if (CCID_COMMAND_FAILED (msg))
2325 print_command_failed (msg);
2327 while (rc == LIBUSB_ERROR_TIMEOUT
2328 || (msg[0] != RDR_to_PC_SlotStatus && msg[5] != 0 && msg[6] != seqno));
2330 handle->seqno = ((seqno + 1) & 0xff);
2331 DEBUGOUT ("sending abort sequence succeeded\n");
2337 /* Note that this function won't return the error codes NO_CARD or
2338 CARD_INACTIVE. IF RESULT is not NULL, the result from the
2339 operation will get returned in RESULT and its length in RESULTLEN.
2340 If the response is larger than RESULTMAX, an error is returned and
2341 the required buffer length returned in RESULTLEN. */
2343 send_escape_cmd (ccid_driver_t handle,
2344 const unsigned char *data, size_t datalen,
2345 unsigned char *result, size_t resultmax, size_t *resultlen)
2348 unsigned char msg[100];
2350 unsigned char seqno;
2355 if (datalen > sizeof msg - 10)
2356 return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large. */
2358 msg[0] = PC_to_RDR_Escape;
2359 msg[5] = 0; /* slot */
2360 msg[6] = seqno = handle->seqno++;
2361 msg[7] = 0; /* RFU */
2362 msg[8] = 0; /* RFU */
2363 msg[9] = 0; /* RFU */
2364 memcpy (msg+10, data, datalen);
2365 msglen = 10 + datalen;
2366 set_msg_len (msg, datalen);
2368 rc = bulk_out (handle, msg, msglen, 0);
2371 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape,
2376 /* We need to ignore certain errorcode here. */
2378 case CCID_DRIVER_ERR_CARD_INACTIVE:
2379 case CCID_DRIVER_ERR_NO_CARD:
2381 if (msglen > resultmax)
2382 rc = CCID_DRIVER_ERR_INV_VALUE; /* Response too large. */
2385 memcpy (result, msg, msglen);
2387 *resultlen = msglen;
2401 ccid_transceive_escape (ccid_driver_t handle,
2402 const unsigned char *data, size_t datalen,
2403 unsigned char *resp, size_t maxresplen, size_t *nresp)
2405 return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp);
2412 ccid_poll (ccid_driver_t handle)
2415 unsigned char msg[10];
2419 rc = libusb_interrupt_transfer (handle->idev, handle->ep_intr,
2420 msg, sizeof msg, &msglen,
2421 0 /* ms timeout */ );
2422 if (rc == LIBUSB_ERROR_TIMEOUT)
2427 DEBUGOUT_1 ("usb_intr_read error: %s\n", libusb_error_name (rc));
2428 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2433 DEBUGOUT ("intr-in msg too short\n");
2434 return CCID_DRIVER_ERR_INV_VALUE;
2437 if (msg[0] == RDR_to_PC_NotifySlotChange)
2439 DEBUGOUT ("notify slot change:");
2440 for (i=1; i < msglen; i++)
2441 for (j=0; j < 4; j++)
2442 DEBUGOUT_CONT_3 (" %d:%c%c",
2444 (msg[i] & (1<<(j*2)))? 'p':'-',
2445 (msg[i] & (2<<(j*2)))? '*':' ');
2448 else if (msg[0] == RDR_to_PC_HardwareError)
2450 DEBUGOUT ("hardware error occurred\n");
2454 DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]);
2461 /* Note that this function won't return the error codes NO_CARD or
2464 ccid_slot_status (ccid_driver_t handle, int *statusbits, int on_wire)
2467 unsigned char msg[100];
2469 unsigned char seqno;
2472 if (handle->powered_off)
2473 return CCID_DRIVER_ERR_NO_READER;
2475 /* If the card (with its lower-level driver) doesn't require
2476 GET_STATUS on wire (because it supports INTERRUPT transfer for
2477 status change, or it's a token which has a card always inserted),
2478 no need to send on wire. */
2479 if (!on_wire && !ccid_require_get_status (handle))
2481 /* Setup interrupt transfer at the initial call of slot_status
2482 with ON_WIRE == 0 */
2483 if (handle->transfer == NULL)
2484 ccid_setup_intr (handle);
2491 msg[0] = PC_to_RDR_GetSlotStatus;
2492 msg[5] = 0; /* slot */
2493 msg[6] = seqno = handle->seqno++;
2494 msg[7] = 0; /* RFU */
2495 msg[8] = 0; /* RFU */
2496 msg[9] = 0; /* RFU */
2497 set_msg_len (msg, 0);
2499 rc = bulk_out (handle, msg, 10, 1);
2502 /* Note that we set the NO_DEBUG flag here, so that the logs won't
2503 get cluttered up by a ticker function checking for the slot
2504 status and debugging enabled. */
2505 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
2506 seqno, retries? 1000 : 200, 1);
2507 if ((rc == CCID_DRIVER_ERR_CARD_IO_ERROR || rc == CCID_DRIVER_ERR_USB_TIMEOUT)
2512 DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n");
2516 libusb_clear_halt (handle->idev, handle->ep_bulk_in);
2517 libusb_clear_halt (handle->idev, handle->ep_bulk_out);
2523 DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n");
2527 if (rc && rc != CCID_DRIVER_ERR_NO_CARD && rc != CCID_DRIVER_ERR_CARD_INACTIVE)
2529 *statusbits = (msg[7] & 3);
2535 /* Parse ATR string (of ATRLEN) and update parameters at PARAM.
2536 Calling this routine, it should prepare default values at PARAM
2537 beforehand. This routine assumes that card is accessed by T=1
2538 protocol. It doesn't analyze historical bytes at all.
2540 Returns < 0 value on error:
2541 -1 for parse error or integrity check error
2542 -2 for card doesn't support T=1 protocol
2543 -3 for parameters are nod explicitly defined by ATR
2544 -4 for this driver doesn't support CRC
2546 Returns >= 0 on success:
2547 0 for card is negotiable mode
2548 1 for card is specific mode (and not negotiable)
2551 update_param_by_atr (unsigned char *param, unsigned char *atr, size_t atrlen)
2555 int historical_bytes_num, negotiable = 1;
2557 #define NEXTBYTE() do { i++; if (atrlen <= i) return -1; } while (0)
2562 param[1] |= 0x02; /* Convention is inverse. */
2566 historical_bytes_num = atr[i] & 0x0f;
2571 param[0] = atr[i]; /* TA1 - Fi & Di */
2576 NEXTBYTE (); /* TB1 - ignore */
2580 param[2] = atr[i]; /* TC1 - Guard Time */
2586 y = (atr[i] >> 4); /* TD1 */
2591 { /* TA2 - PPS mode */
2592 if ((atr[i] & 0x0f) != 1)
2593 return -2; /* Wrong card protocol (!= 1). */
2595 if ((atr[i] & 0x10) != 0x10)
2596 return -3; /* Transmission parameters are implicitly defined. */
2598 negotiable = 0; /* TA2 means specific mode. */
2603 NEXTBYTE (); /* TB2 - ignore */
2606 NEXTBYTE (); /* TC2 - ignore */
2610 y = (atr[i] >> 4); /* TD2 */
2622 param[5] = atr[i]; /* IFSC */
2624 /* XXX: check voltage? */
2625 param[4] = (atr[i] >> 6); /* ClockStop */
2633 param[3] = atr[i]; /* TBx - BWI & CWI */
2640 param[1] |= (atr[i] & 0x01); /* TCx - LRC/CRC */
2643 if (param[1] & 0x01)
2644 return -4; /* CRC not supported yet. */
2649 y = (atr[i] >> 4); /* TDx */
2658 i += historical_bytes_num - 1;
2680 /* Return the ATR of the card. This is not a cached value and thus an
2681 actual reset is done. */
2683 ccid_get_atr (ccid_driver_t handle,
2684 unsigned char *atr, size_t maxatrlen, size_t *atrlen)
2688 unsigned char msg[100];
2689 unsigned char *tpdu;
2690 size_t msglen, tpdulen;
2691 unsigned char seqno;
2696 unsigned char param[7] = { /* For Protocol T=1 */
2697 0x11, /* bmFindexDindex */
2698 0x10, /* bmTCCKST1 */
2699 0x00, /* bGuardTimeT1 */
2700 0x4d, /* bmWaitingIntegersT1 */
2701 0x00, /* bClockStop */
2703 0x00 /* bNadValue */
2706 /* First check whether a card is available. */
2707 rc = ccid_slot_status (handle, &statusbits, 1);
2710 if (statusbits == 2)
2711 return CCID_DRIVER_ERR_NO_CARD;
2714 * In the first invocation of ccid_slot_status, card reader may
2715 * return CCID_DRIVER_ERR_CARD_INACTIVE and handle->powered_off may
2716 * become 1. Because inactive card is no problem (we are turning it
2717 * ON here), clear the flag.
2719 handle->powered_off = 0;
2721 /* For an inactive and also for an active card, issue the PowerOn
2722 command to get the ATR. */
2724 msg[0] = PC_to_RDR_IccPowerOn;
2725 msg[5] = 0; /* slot */
2726 msg[6] = seqno = handle->seqno++;
2727 /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */
2728 msg[7] = handle->auto_voltage ? 0 : 1;
2729 msg[8] = 0; /* RFU */
2730 msg[9] = 0; /* RFU */
2731 set_msg_len (msg, 0);
2734 rc = bulk_out (handle, msg, msglen, 0);
2737 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2741 if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb
2742 && ((handle->id_vendor == VENDOR_CHERRY
2743 && handle->id_product == 0x0005)
2744 || (handle->id_vendor == VENDOR_GEMPC
2745 && handle->id_product == 0x4433)
2749 /* Try switching to ISO mode. */
2750 if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2,
2754 else if (statusbits == 0 && CCID_COMMAND_FAILED (msg))
2756 /* Card was active already, and something went wrong with
2757 PC_to_RDR_IccPowerOn command. It may be baud-rate mismatch
2758 between the card and the reader. To recover from this state,
2759 send PC_to_RDR_IccPowerOff command to reset the card and try
2762 rc = send_power_off (handle);
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]);
2953 ccid_vendor_specific_setup (handle);
2961 compute_edc (const unsigned char *data, size_t datalen, int use_crc)
2965 return 0x42; /* Not yet implemented. */
2969 unsigned char crc = 0;
2971 for (; datalen; datalen--)
2978 /* Return true if APDU is an extended length one. */
2980 is_exlen_apdu (const unsigned char *apdu, size_t apdulen)
2982 if (apdulen < 7 || apdu[4])
2983 return 0; /* Too short or no Z byte. */
2988 /* Helper for ccid_transceive used for APDU level exchanges. */
2990 ccid_transceive_apdu_level (ccid_driver_t handle,
2991 const unsigned char *apdu_buf, size_t apdu_len,
2992 unsigned char *resp, size_t maxresplen,
2996 unsigned char msg[CCID_MAX_BUF];
2997 const unsigned char *apdu_p;
2998 size_t apdu_part_len;
3000 unsigned char seqno;
3002 unsigned char chain = 0;
3004 if (apdu_len == 0 || apdu_len > sizeof (msg) - 10)
3005 return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
3010 apdu_part_len = apdu_len;
3011 if (apdu_part_len > handle->max_ccid_msglen - 10)
3013 apdu_part_len = handle->max_ccid_msglen - 10;
3017 msg[0] = PC_to_RDR_XfrBlock;
3018 msg[5] = 0; /* slot */
3019 msg[6] = seqno = handle->seqno++;
3023 memcpy (msg+10, apdu_p, apdu_part_len);
3024 set_msg_len (msg, apdu_part_len);
3025 msglen = 10 + apdu_part_len;
3027 rc = bulk_out (handle, msg, msglen, 0);
3031 apdu_p += apdu_part_len;
3032 apdu_len -= apdu_part_len;
3034 rc = bulk_in (handle, msg, sizeof msg, &msglen,
3035 RDR_to_PC_DataBlock, seqno, CCID_CMD_TIMEOUT, 0);
3039 if (!(chain & 0x01))
3048 apdu_part_len = msglen - 10;
3049 if (resp && apdu_len + apdu_part_len <= maxresplen)
3050 memcpy (resp + apdu_len, msg+10, apdu_part_len);
3051 apdu_len += apdu_part_len;
3053 if (!(msg[9] & 0x01))
3056 msg[0] = PC_to_RDR_XfrBlock;
3057 msg[5] = 0; /* slot */
3058 msg[6] = seqno = handle->seqno++;
3060 msg[8] = 0x10; /* Request next data block */
3062 set_msg_len (msg, 0);
3065 rc = bulk_out (handle, msg, msglen, 0);
3069 rc = bulk_in (handle, msg, sizeof msg, &msglen,
3070 RDR_to_PC_DataBlock, seqno, CCID_CMD_TIMEOUT, 0);
3077 if (apdu_len > maxresplen)
3079 DEBUGOUT_2 ("provided buffer too short for received data "
3081 (unsigned int)apdu_len, (unsigned int)maxresplen);
3082 return CCID_DRIVER_ERR_INV_VALUE;
3094 Protocol T=1 overview
3098 1 byte Node Address (NAD)
3099 1 byte Protocol Control Byte (PCB)
3102 0-254 byte APDU or Control Information (INF)
3104 1 byte Error Detection Code (EDC)
3108 bit 4..6 Destination Node Address (DAD)
3110 bit 2..0 Source Node Address (SAD)
3112 If node adresses are not used, SAD and DAD should be set to 0 on
3113 the first block sent to the card. If they are used they should
3114 have different values (0 for one is okay); that first block sets up
3115 the addresses of the nodes.
3118 Information Block (I-Block):
3120 bit 6 Sequence number (yep, that is modulo 2)
3123 Received-Ready Block (R-Block):
3127 bit 4 Sequence number
3128 bit 3..0 0 = no error
3129 1 = EDC or parity error
3131 other values are reserved
3132 Supervisory Block (S-Block):
3135 bit 5 clear=request,set=response
3136 bit 4..0 0 = resynchronization request
3137 1 = information field size request
3139 3 = extension of BWT request
3141 other values are reserved
3146 ccid_transceive (ccid_driver_t handle,
3147 const unsigned char *apdu_buf, size_t apdu_buflen,
3148 unsigned char *resp, size_t maxresplen, size_t *nresp)
3151 /* The size of the buffer used to be 10+259. For the via_escape
3152 hack we need one extra byte, thus 11+259. */
3153 unsigned char send_buffer[11+259], recv_buffer[11+259];
3154 const unsigned char *apdu;
3156 unsigned char *msg, *tpdu, *p;
3157 size_t msglen, tpdulen, last_tpdulen, n;
3158 unsigned char seqno;
3172 nresp = &dummy_nresp;
3175 /* Smarter readers allow sending APDUs directly; divert here. */
3176 if (handle->apdu_level)
3178 /* We employ a hack for Omnikey readers which are able to send
3179 TPDUs using an escape sequence. There is no documentation
3180 but the Windows driver does it this way. Tested using a
3181 CM6121. This method works also for the Cherry XX44
3182 keyboards; however there are problems with the
3183 ccid_transceive_secure which leads to a loss of sync on the
3184 CCID level. If Cherry wants to make their keyboard work
3185 again, they should hand over some docs. */
3186 if ((handle->id_vendor == VENDOR_OMNIKEY)
3187 && handle->apdu_level < 2
3188 && is_exlen_apdu (apdu_buf, apdu_buflen))
3191 return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen,
3192 resp, maxresplen, nresp);
3195 /* The other readers we support require sending TPDUs. */
3197 tpdulen = 0; /* Avoid compiler warning about no initialization. */
3199 hdrlen = via_escape? 11 : 10;
3201 /* NAD: DAD=1, SAD=0 */
3202 nad_byte = handle->nonnull_nad? ((1 << 4) | 0): 0;
3206 last_tpdulen = 0; /* Avoid gcc warning (controlled by RESYNCING). */
3214 apdulen = apdu_buflen;
3217 /* Construct an I-Block. */
3218 tpdu = msg + hdrlen;
3220 tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */
3221 if (apdulen > handle->ifsc )
3223 apdulen = handle->ifsc;
3224 apdu_buf += handle->ifsc;
3225 apdu_buflen -= handle->ifsc;
3226 tpdu[1] |= (1 << 5); /* Set more bit. */
3229 memcpy (tpdu+3, apdu, apdulen);
3230 tpdulen = 3 + apdulen;
3231 edc = compute_edc (tpdu, tpdulen, use_crc);
3233 tpdu[tpdulen++] = (edc >> 8);
3234 tpdu[tpdulen++] = edc;
3239 msg[0] = PC_to_RDR_Escape;
3240 msg[5] = 0; /* slot */
3241 msg[6] = seqno = handle->seqno++;
3242 msg[7] = 0; /* RFU */
3243 msg[8] = 0; /* RFU */
3244 msg[9] = 0; /* RFU */
3245 msg[10] = 0x1a; /* Omnikey command to send a TPDU. */
3246 set_msg_len (msg, 1 + tpdulen);
3250 msg[0] = PC_to_RDR_XfrBlock;
3251 msg[5] = 0; /* slot */
3252 msg[6] = seqno = handle->seqno++;
3253 msg[7] = (wait_more ? wait_more : 1); /* bBWI */
3254 msg[8] = 0; /* RFU */
3255 msg[9] = 0; /* RFU */
3256 set_msg_len (msg, tpdulen);
3258 msglen = hdrlen + tpdulen;
3260 last_tpdulen = tpdulen;
3263 if (debug_level > 1)
3264 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
3265 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
3266 (msg[pcboff] & 0x80)? 'S' : 'I',
3267 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
3268 : !!(msg[pcboff] & 0x40)),
3269 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
3272 rc = bulk_out (handle, msg, msglen, 0);
3277 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3278 via_escape? RDR_to_PC_Escape : RDR_to_PC_DataBlock, seqno,
3279 (wait_more ? wait_more : 1) * CCID_CMD_TIMEOUT, 0);
3283 tpdu = msg + hdrlen;
3284 tpdulen = msglen - hdrlen;
3292 libusb_clear_halt (handle->idev, handle->ep_bulk_in);
3296 return CCID_DRIVER_ERR_ABORTED;
3299 if (debug_level > 1)
3300 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3301 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
3302 (msg[pcboff] & 0x80)? 'S' : 'I',
3303 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
3304 : !!(msg[pcboff] & 0x40)),
3305 ((msg[pcboff] & 0xc0) == 0x80)? (msg[pcboff] & 0x0f) : 0,
3306 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
3310 if (!(tpdu[1] & 0x80))
3311 { /* This is an I-block. */
3314 { /* last block sent was successful. */
3319 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3320 { /* Response does not match our sequence number. */
3322 tpdu = msg + hdrlen;
3324 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */
3327 edc = compute_edc (tpdu, tpdulen, use_crc);
3329 tpdu[tpdulen++] = (edc >> 8);
3330 tpdu[tpdulen++] = edc;
3337 p = tpdu + 3; /* Skip the prologue field. */
3338 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3339 /* fixme: verify the checksum. */
3344 DEBUGOUT_2 ("provided buffer too short for received data "
3346 (unsigned int)n, (unsigned int)maxresplen);
3347 return CCID_DRIVER_ERR_INV_VALUE;
3350 memcpy (resp, p, n);
3356 if (!(tpdu[1] & 0x20))
3357 return 0; /* No chaining requested - ready. */
3360 tpdu = msg + hdrlen;
3362 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */
3365 edc = compute_edc (tpdu, tpdulen, use_crc);
3367 tpdu[tpdulen++] = (edc >> 8);
3368 tpdu[tpdulen++] = edc;
3370 else if ((tpdu[1] & 0xc0) == 0x80)
3371 { /* This is a R-block. */
3372 if ( (tpdu[1] & 0x0f))
3375 if (via_escape && retries == 1 && (msg[pcboff] & 0x0f))
3377 /* Error probably due to switching to TPDU. Send a
3378 resync request. We use the recv_buffer so that
3379 we don't corrupt the send_buffer. */
3381 tpdu = msg + hdrlen;
3383 tpdu[1] = 0xc0; /* S-block resync request. */
3386 edc = compute_edc (tpdu, tpdulen, use_crc);
3388 tpdu[tpdulen++] = (edc >> 8);
3389 tpdu[tpdulen++] = edc;
3391 DEBUGOUT ("T=1: requesting resync\n");
3393 else if (retries > 3)
3395 DEBUGOUT ("T=1: 3 failed retries\n");
3396 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3400 /* Error: repeat last block */
3402 tpdulen = last_tpdulen;
3405 else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns)
3406 { /* Response does not match our sequence number. */
3407 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3408 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3411 { /* Send next chunk. */
3419 DEBUGOUT ("unexpected ACK R-block received\n");
3420 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3424 { /* This is a S-block. */
3426 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d\n",
3427 (tpdu[1] & 0x20)? "response": "request",
3429 if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 1 && tpdu[2] == 1)
3431 /* Information field size request. */
3432 unsigned char ifsc = tpdu[3];
3434 if (ifsc < 16 || ifsc > 254)
3435 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3438 tpdu = msg + hdrlen;
3440 tpdu[1] = (0xc0 | 0x20 | 1); /* S-block response */
3444 edc = compute_edc (tpdu, tpdulen, use_crc);
3446 tpdu[tpdulen++] = (edc >> 8);
3447 tpdu[tpdulen++] = edc;
3448 DEBUGOUT_1 ("T=1: requesting an ifsc=%d\n", ifsc);
3450 else if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2])
3452 /* Wait time extension request. */
3453 unsigned char bwi = tpdu[3];
3458 tpdu = msg + hdrlen;
3460 tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */
3464 edc = compute_edc (tpdu, tpdulen, use_crc);
3466 tpdu[tpdulen++] = (edc >> 8);
3467 tpdu[tpdulen++] = edc;
3468 DEBUGOUT_1 ("T=1: waittime extension of bwi=%d\n", bwi);
3469 print_progress (handle);
3471 else if ( (tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 0 && !tpdu[2])
3473 DEBUGOUT ("T=1: resync ack from reader\n");
3474 /* Repeat previous block. */
3476 tpdulen = last_tpdulen;
3479 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3481 } /* end T=1 protocol loop. */
3487 /* Send the CCID Secure command to the reader. APDU_BUF should
3488 contain the APDU template. PIN_MODE defines how the pin gets
3491 1 := The PIN is ASCII encoded and of variable length. The
3492 length of the PIN entered will be put into Lc by the reader.
3493 The APDU should me made up of 4 bytes without Lc.
3495 PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0
3496 may be used t enable reasonable defaults.
3498 When called with RESP and NRESP set to NULL, the function will
3499 merely check whether the reader supports the secure command for the
3500 given APDU and PIN_MODE. */
3502 ccid_transceive_secure (ccid_driver_t handle,
3503 const unsigned char *apdu_buf, size_t apdu_buflen,
3505 unsigned char *resp, size_t maxresplen, size_t *nresp)
3508 unsigned char send_buffer[10+259], recv_buffer[10+259];
3509 unsigned char *msg, *tpdu, *p;
3510 size_t msglen, tpdulen, n;
3511 unsigned char seqno;
3514 int cherry_mode = 0;
3516 int enable_varlen = 0;
3518 testmode = !resp && !nresp;
3521 nresp = &dummy_nresp;
3524 if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1))
3526 else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2))
3529 return CCID_DRIVER_ERR_NO_PINPAD;
3531 if (!pininfo->minlen)
3532 pininfo->minlen = 1;
3533 if (!pininfo->maxlen)
3534 pininfo->maxlen = 15;
3536 /* Note that the 25 is the maximum value the SPR532 allows. */
3537 if (pininfo->minlen < 1 || pininfo->minlen > 25
3538 || pininfo->maxlen < 1 || pininfo->maxlen > 25
3539 || pininfo->minlen > pininfo->maxlen)
3540 return CCID_DRIVER_ERR_INV_VALUE;
3542 /* We have only tested a few readers so better don't risk anything
3543 and do not allow the use with other readers. */
3544 switch (handle->id_vendor)
3546 case VENDOR_SCM: /* Tested with SPR 532. */
3547 case VENDOR_KAAN: /* Tested with KAAN Advanced (1.02). */
3548 case VENDOR_FSIJ: /* Tested with Gnuk (0.21). */
3549 pininfo->maxlen = 25;
3552 case VENDOR_REINER:/* Tested with cyberJack go */
3553 case VENDOR_VASCO: /* Tested with DIGIPASS 920 */
3557 pininfo->maxlen = 15;
3559 /* The CHERRY XX44 keyboard echos an asterisk for each entered
3560 character on the keyboard channel. We use a special variant
3561 of PC_to_RDR_Secure which directs these characters to the
3562 smart card's bulk-in channel. We also need to append a zero
3563 Lc byte to the APDU. It seems that it will be replaced with
3564 the actual length instead of being appended before the APDU
3565 is send to the card. */
3567 if (handle->id_product != CHERRY_ST2000)
3571 if (handle->id_product == CRYPTOUCAN){
3572 pininfo->maxlen = 25;
3576 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3578 if (handle->id_product == GEMPC_PINPAD)
3581 pininfo->minlen = 4;
3582 pininfo->maxlen = 8;
3585 else if (handle->id_product == GEMPC_EZIO)
3587 pininfo->maxlen = 25;
3591 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3593 if ((handle->id_vendor == VENDOR_VEGA &&
3594 handle->id_product == VEGA_ALPHA))
3597 pininfo->minlen = 4;
3598 pininfo->maxlen = 8;
3601 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3605 pininfo->fixedlen = 0;
3608 return 0; /* Success */
3610 if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
3611 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3613 ccid_vendor_specific_pinpad_setup (handle);
3616 msg[0] = cherry_mode? 0x89 : PC_to_RDR_Secure;
3617 msg[5] = 0; /* slot */
3618 msg[6] = seqno = handle->seqno++;
3619 msg[7] = 0; /* bBWI */
3620 msg[8] = 0; /* RFU */
3621 msg[9] = 0; /* RFU */
3622 msg[10] = apdu_buf[1] == 0x20 ? 0 : 1;
3623 /* Perform PIN verification or PIN modification. */
3624 msg[11] = 0; /* Timeout in seconds. */
3625 msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
3626 if (handle->id_vendor == VENDOR_SCM)
3628 /* For the SPR532 the next 2 bytes need to be zero. We do this
3629 for all SCM products. Kudos to Martin Paljak for this
3631 msg[13] = msg[14] = 0;
3635 msg[13] = pininfo->fixedlen; /* bmPINBlockString:
3636 0 bits of pin length to insert.
3637 PIN block size by fixedlen. */
3638 msg[14] = 0x00; /* bmPINLengthFormat:
3639 Units are bytes, position is 0. */
3643 if (apdu_buf[1] == 0x24)
3645 msg[msglen++] = 0; /* bInsertionOffsetOld */
3646 msg[msglen++] = pininfo->fixedlen; /* bInsertionOffsetNew */
3649 /* The following is a little endian word. */
3650 msg[msglen++] = pininfo->maxlen; /* wPINMaxExtraDigit-Maximum. */
3651 msg[msglen++] = pininfo->minlen; /* wPINMaxExtraDigit-Minimum. */
3653 if (apdu_buf[1] == 0x24)
3654 msg[msglen++] = apdu_buf[2] == 0 ? 0x03 : 0x01;
3656 * 0x00: new PIN once
3657 * 0x01: new PIN twice (confirmation)
3658 * 0x02: old PIN and new PIN once
3659 * 0x03: old PIN and new PIN twice (confirmation)
3662 msg[msglen] = 0x02; /* bEntryValidationCondition:
3663 Validation key pressed */
3664 if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
3665 msg[msglen] |= 0x01; /* Max size reached. */
3668 if (apdu_buf[1] == 0x20)
3669 msg[msglen++] = 0x01; /* bNumberMessage. */
3671 msg[msglen++] = 0x03; /* bNumberMessage. */
3673 msg[msglen++] = 0x09; /* wLangId-Low: English FIXME: use the first entry. */
3674 msg[msglen++] = 0x04; /* wLangId-High. */
3676 if (apdu_buf[1] == 0x20)
3677 msg[msglen++] = 0; /* bMsgIndex. */
3680 msg[msglen++] = 0; /* bMsgIndex1. */
3681 msg[msglen++] = 1; /* bMsgIndex2. */
3682 msg[msglen++] = 2; /* bMsgIndex3. */
3686 n = pininfo->fixedlen;
3687 if (apdu_buf[1] == 0x24)
3688 n += pininfo->fixedlen;
3690 /* bTeoProlog follows: */
3691 msg[msglen++] = handle->nonnull_nad? ((1 << 4) | 0): 0;
3692 msg[msglen++] = ((handle->t1_ns & 1) << 6); /* I-block */
3694 msg[msglen++] = n + 5; /* apdulen should be filled for fixed length. */
3696 msg[msglen++] = 0; /* The apdulen will be filled in by the reader. */
3698 msg[msglen++] = apdu_buf[0]; /* CLA */
3699 msg[msglen++] = apdu_buf[1]; /* INS */
3700 msg[msglen++] = apdu_buf[2]; /* P1 */
3701 msg[msglen++] = apdu_buf[3]; /* P2 */
3704 else if (pininfo->fixedlen != 0)
3707 memset (&msg[msglen], 0xff, n);
3710 /* An EDC is not required. */
3711 set_msg_len (msg, msglen - 10);
3713 rc = bulk_out (handle, msg, msglen, 0);
3718 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3719 RDR_to_PC_DataBlock, seqno, 30000, 0);
3724 tpdulen = msglen - 10;
3726 if (handle->apdu_level)
3730 if (tpdulen > maxresplen)
3732 DEBUGOUT_2 ("provided buffer too short for received data "
3734 (unsigned int)tpdulen, (unsigned int)maxresplen);
3735 return CCID_DRIVER_ERR_INV_VALUE;
3738 memcpy (resp, tpdu, tpdulen);
3749 libusb_clear_halt (handle->idev, handle->ep_bulk_in);
3753 return CCID_DRIVER_ERR_ABORTED;
3755 if (debug_level > 1)
3756 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3757 ((msg[11] & 0xc0) == 0x80)? 'R' :
3758 (msg[11] & 0x80)? 'S' : 'I',
3759 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
3760 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
3761 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
3763 if (!(tpdu[1] & 0x80))
3764 { /* This is an I-block. */
3765 /* Last block sent was successful. */
3768 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3769 { /* Response does not match our sequence number. */
3770 DEBUGOUT ("I-block with wrong seqno received\n");
3771 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3776 p = tpdu + 3; /* Skip the prologue field. */
3777 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3778 /* fixme: verify the checksum. */
3783 DEBUGOUT_2 ("provided buffer too short for received data "
3785 (unsigned int)n, (unsigned int)maxresplen);
3786 return CCID_DRIVER_ERR_INV_VALUE;
3789 memcpy (resp, p, n);
3793 if (!(tpdu[1] & 0x20))
3794 return 0; /* No chaining requested - ready. */
3796 DEBUGOUT ("chaining requested but not supported for Secure operation\n");
3797 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3799 else if ((tpdu[1] & 0xc0) == 0x80)
3800 { /* This is a R-block. */
3801 if ( (tpdu[1] & 0x0f))
3802 { /* Error: repeat last block */
3803 DEBUGOUT ("No retries supported for Secure operation\n");
3804 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3806 else if (!!(tpdu[1] & 0x10) == handle->t1_ns)
3807 { /* Response does not match our sequence number. */
3808 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3809 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3812 { /* Send next chunk. */
3813 DEBUGOUT ("chaining not supported on Secure operation\n");
3814 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3818 { /* This is a S-block. */
3819 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d for Secure operation\n",
3820 (tpdu[1] & 0x20)? "response": "request",
3822 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3835 print_error (int err)
3842 case 0: p = "success"; break;
3843 case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break;
3844 case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break;
3845 case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break;
3846 case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break;
3847 case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break;
3848 case CCID_DRIVER_ERR_BUSY: p = "busy"; break;
3849 case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break;
3850 case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break;
3851 case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break;
3852 case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break;
3853 case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break;
3854 case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break;
3855 default: sprintf (buf, "0x%05x", err); p = buf; break;
3857 fprintf (stderr, "operation failed: %s\n", p);
3862 print_data (const unsigned char *data, size_t length)
3866 fprintf (stderr, "operation status: %02X%02X\n",
3867 data[length-2], data[length-1]);
3872 fputs (" returned data:", stderr);
3873 for (; length; length--, data++)
3874 fprintf (stderr, " %02X", *data);
3875 putc ('\n', stderr);
3880 print_result (int rc, const unsigned char *data, size_t length)
3885 print_data (data, length);
3889 main (int argc, char **argv)
3894 unsigned char result[512];
3897 int verify_123456 = 0;
3901 struct ccid_dev_table *ccid_table;
3911 if ( !strcmp (*argv, "--list"))
3914 p = ccid_get_reader_list ();
3921 else if ( !strcmp (*argv, "--debug"))
3923 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
3926 else if ( !strcmp (*argv, "--no-poll"))
3931 else if ( !strcmp (*argv, "--no-pinpad"))
3936 else if ( !strcmp (*argv, "--verify-123456"))
3945 err = ccid_dev_scan (&idx_max, &ccid_table);
3952 err = ccid_open_reader (argc? *argv:NULL, 0, ccid_table, &ccid, NULL);
3956 ccid_dev_scan_finish (ccid_table, idx_max);
3960 fputs ("getting ATR ...\n", stderr);
3961 err = ccid_get_atr (ccid, NULL, 0, NULL);
3970 fputs ("getting slot status ...\n", stderr);
3971 err = ccid_slot_status (ccid, &slotstat, 1);
3981 fputs ("selecting application OpenPGP ....\n", stderr);
3983 static unsigned char apdu[] = {
3984 0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01};
3985 err = ccid_transceive (ccid,
3987 result, sizeof result, &resultlen);
3988 print_result (err, result, resultlen);
3995 fputs ("getting OpenPGP DO 0x65 ....\n", stderr);
3997 static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 };
3998 err = ccid_transceive (ccid, apdu, sizeof apdu,
3999 result, sizeof result, &resultlen);
4000 print_result (err, result, resultlen);
4009 static unsigned char apdu[] = { 0, 0x20, 0, 0x81 };
4010 pininfo_t pininfo = { 0, 0, 0 };
4012 if (ccid_transceive_secure (ccid, apdu, sizeof apdu, &pininfo,
4014 fputs ("can't verify using a PIN-Pad reader\n", stderr);
4017 fputs ("verifying CHV1 using the PINPad ....\n", stderr);
4019 err = ccid_transceive_secure (ccid, apdu, sizeof apdu, &pininfo,
4020 result, sizeof result, &resultlen);
4021 print_result (err, result, resultlen);
4026 if (verify_123456 && !did_verify)
4028 fputs ("verifying that CHV1 is 123456....\n", stderr);
4030 static unsigned char apdu[] = {0, 0x20, 0, 0x81,
4031 6, '1','2','3','4','5','6'};
4032 err = ccid_transceive (ccid, apdu, sizeof apdu,
4033 result, sizeof result, &resultlen);
4034 print_result (err, result, resultlen);
4040 fputs ("getting OpenPGP DO 0x5E ....\n", stderr);
4042 static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 };
4043 err = ccid_transceive (ccid, apdu, sizeof apdu,
4044 result, sizeof result, &resultlen);
4045 print_result (err, result, resultlen);
4049 ccid_close_reader (ccid);
4056 * compile-command: "gcc -DTEST -DGPGRT_ENABLE_ES_MACROS -DHAVE_NPTH -DUSE_NPTH -Wall -I/usr/include/libusb-1.0 -I/usr/local/include -lusb-1.0 -g ccid-driver.c -lnpth -lgpg-error"
4060 #endif /*HAVE_LIBUSB*/