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)
81 #include <sys/types.h>
94 #define CCID_DRIVER_INCLUDE_USB_IDS 1
95 #include "ccid-driver.h"
97 #define DRVNAME "ccid-driver: "
99 /* Max length of buffer with out CCID message header of 10-byte
100 Sending: 547 for RSA-4096 key import
101 APDU size = 540 (24+4+256+256)
102 command + lc + le = 4 + 3 + 0
103 Sending: write data object of cardholder certificate
105 command + lc + le = 4 + 3 + 0
106 Receiving: 2048 for cardholder certificate
108 #define CCID_MAX_BUF (2048+7+10)
110 /* CCID command timeout. */
111 #define CCID_CMD_TIMEOUT (5*1000)
113 /* Number of supported devices. See MAX_READER in apdu.c. */
114 #define CCID_MAX_DEVICE 16
117 /* Depending on how this source is used we either define our error
118 * output to go to stderr or to the GnuPG based logging functions. We
119 * use the latter when GNUPG_MAJOR_VERSION is defined. */
120 #if defined(GNUPG_MAJOR_VERSION)
121 # include "scdaemon.h"
123 # define DEBUGOUT(t) do { if (debug_level) \
124 log_debug (DRVNAME t); } while (0)
125 # define DEBUGOUT_1(t,a) do { if (debug_level) \
126 log_debug (DRVNAME t,(a)); } while (0)
127 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
128 log_debug (DRVNAME t,(a),(b)); } while (0)
129 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
130 log_debug (DRVNAME t,(a),(b),(c));} while (0)
131 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
132 log_debug (DRVNAME t,(a),(b),(c),(d));} while (0)
133 # define DEBUGOUT_CONT(t) do { if (debug_level) \
134 log_printf (t); } while (0)
135 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
136 log_printf (t,(a)); } while (0)
137 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
138 log_printf (t,(a),(b)); } while (0)
139 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
140 log_printf (t,(a),(b),(c)); } while (0)
141 # define DEBUGOUT_LF() do { if (debug_level) \
142 log_printf ("\n"); } while (0)
144 #else /* Other usage of this source - don't use gnupg specifics. */
146 # define DEBUGOUT(t) do { if (debug_level) \
147 fprintf (stderr, DRVNAME t); } while (0)
148 # define DEBUGOUT_1(t,a) do { if (debug_level) \
149 fprintf (stderr, DRVNAME t, (a)); } while (0)
150 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
151 fprintf (stderr, DRVNAME t, (a), (b)); } while (0)
152 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
153 fprintf (stderr, DRVNAME t, (a), (b), (c)); } while (0)
154 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
155 fprintf (stderr, DRVNAME t, (a), (b), (c), (d));} while(0)
156 # define DEBUGOUT_CONT(t) do { if (debug_level) \
157 fprintf (stderr, t); } while (0)
158 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
159 fprintf (stderr, t, (a)); } while (0)
160 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
161 fprintf (stderr, t, (a), (b)); } while (0)
162 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
163 fprintf (stderr, t, (a), (b), (c)); } while (0)
164 # define DEBUGOUT_LF() do { if (debug_level) \
165 putc ('\n', stderr); } while (0)
167 #endif /* This source is not used by scdaemon. */
169 #undef USE_LIBUSB_DEBUG_CB
170 #if LIBUSB_API_VERSION >= 0x01000107
171 # define USE_LIBUSB_DEBUG_CB 1
176 #define EAGAIN EWOULDBLOCK
182 RDR_to_PC_NotifySlotChange= 0x50,
183 RDR_to_PC_HardwareError = 0x51,
185 PC_to_RDR_SetParameters = 0x61,
186 PC_to_RDR_IccPowerOn = 0x62,
187 PC_to_RDR_IccPowerOff = 0x63,
188 PC_to_RDR_GetSlotStatus = 0x65,
189 PC_to_RDR_Secure = 0x69,
190 PC_to_RDR_T0APDU = 0x6a,
191 PC_to_RDR_Escape = 0x6b,
192 PC_to_RDR_GetParameters = 0x6c,
193 PC_to_RDR_ResetParameters = 0x6d,
194 PC_to_RDR_IccClock = 0x6e,
195 PC_to_RDR_XfrBlock = 0x6f,
196 PC_to_RDR_Mechanical = 0x71,
197 PC_to_RDR_Abort = 0x72,
198 PC_to_RDR_SetDataRate = 0x73,
200 RDR_to_PC_DataBlock = 0x80,
201 RDR_to_PC_SlotStatus = 0x81,
202 RDR_to_PC_Parameters = 0x82,
203 RDR_to_PC_Escape = 0x83,
204 RDR_to_PC_DataRate = 0x84
208 /* Two macro to detect whether a CCID command has failed and to get
209 the error code. These macros assume that we can access the
210 mandatory first 10 bytes of a CCID message in BUF. */
211 #define CCID_COMMAND_FAILED(buf) ((buf)[7] & 0x40)
212 #define CCID_ERROR_CODE(buf) (((unsigned char *)(buf))[8])
215 /* Store information on the driver's state. A pointer to such a
216 structure is used as handle for most functions. */
219 libusb_device_handle *idev;
221 unsigned short id_vendor;
222 unsigned short id_product;
230 unsigned char nonnull_nad;
234 unsigned char apdu_level:2; /* Reader supports short APDU level
235 exchange. With a value of 2 short
236 and extended level is supported.*/
237 unsigned int auto_voltage:1;
238 unsigned int auto_param:1;
239 unsigned int auto_pps:1;
240 unsigned int auto_ifsd:1;
241 unsigned int has_pinpad:2;
242 unsigned int enodev_seen:1;
245 time_t last_progress; /* Last time we sent progress line. */
247 /* The progress callback and its first arg as supplied to
248 ccid_set_progress_cb. */
249 void (*progress_cb)(void *, const char *, int, int, int);
250 void *progress_cb_arg;
252 void (*prompt_cb)(void *, int);
255 unsigned char intr_buf[64];
256 struct libusb_transfer *transfer;
260 /* Object to keep infos about found ccid devices. */
261 struct ccid_dev_table {
262 int n; /* Index to ccid_usb_dev_list */
263 int interface_number;
265 unsigned char *ifcdesc_extra;
269 size_t ifcdesc_extra_len;
274 static int initialized_usb; /* Tracks whether USB has been initialized. */
275 static int debug_level; /* Flag to control the debug output.
278 2 = Level 1 + T=1 protocol tracing
279 3 = Level 2 + USB/I/O tracing of SlotStatus.
281 static int ccid_usb_thread_is_alive;
283 static libusb_device **ccid_usb_dev_list;
284 static struct ccid_dev_table ccid_dev_table[CCID_MAX_DEVICE];
288 static unsigned int compute_edc (const unsigned char *data, size_t datalen,
290 static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
292 static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
293 size_t *nread, int expected_type, int seqno, int timeout,
295 static int abort_cmd (ccid_driver_t handle, int seqno, int init);
296 static int send_escape_cmd (ccid_driver_t handle, const unsigned char *data,
297 size_t datalen, unsigned char *result,
298 size_t resultmax, size_t *resultlen);
302 map_libusb_error (int usberr)
307 case LIBUSB_ERROR_IO: return CCID_DRIVER_ERR_USB_IO;
308 case LIBUSB_ERROR_ACCESS: return CCID_DRIVER_ERR_USB_ACCESS;
309 case LIBUSB_ERROR_NO_DEVICE:return CCID_DRIVER_ERR_USB_NO_DEVICE;
310 case LIBUSB_ERROR_BUSY: return CCID_DRIVER_ERR_USB_BUSY;
311 case LIBUSB_ERROR_TIMEOUT: return CCID_DRIVER_ERR_USB_TIMEOUT;
312 case LIBUSB_ERROR_OVERFLOW: return CCID_DRIVER_ERR_USB_OVERFLOW;
314 return CCID_DRIVER_ERR_USB_OTHER;
318 /* Convert a little endian stored 4 byte value into an unsigned
321 convert_le_u32 (const unsigned char *buf)
323 return buf[0] | (buf[1] << 8) | (buf[2] << 16) | ((unsigned int)buf[3] << 24);
327 /* Convert a little endian stored 2 byte value into an unsigned
330 convert_le_u16 (const unsigned char *buf)
332 return buf[0] | (buf[1] << 8);
336 set_msg_len (unsigned char *msg, unsigned int length)
339 msg[2] = length >> 8;
340 msg[3] = length >> 16;
341 msg[4] = length >> 24;
346 print_progress (ccid_driver_t handle)
348 time_t ct = time (NULL);
350 /* We don't want to print progress lines too often. */
351 if (ct == handle->last_progress)
354 if (handle->progress_cb)
355 handle->progress_cb (handle->progress_cb_arg, "card_busy", 'w', 0, 0);
357 handle->last_progress = ct;
362 /* Pint an error message for a failed CCID command including a textual
363 error code. MSG shall be the CCID message at a minimum of 10 bytes. */
365 print_command_failed (const unsigned char *msg)
374 ec = CCID_ERROR_CODE (msg);
377 case 0x00: t = "Command not supported"; break;
379 case 0xE0: t = "Slot busy"; break;
380 case 0xEF: t = "PIN cancelled"; break;
381 case 0xF0: t = "PIN timeout"; break;
383 case 0xF2: t = "Automatic sequence ongoing"; break;
384 case 0xF3: t = "Deactivated Protocol"; break;
385 case 0xF4: t = "Procedure byte conflict"; break;
386 case 0xF5: t = "ICC class not supported"; break;
387 case 0xF6: t = "ICC protocol not supported"; break;
388 case 0xF7: t = "Bad checksum in ATR"; break;
389 case 0xF8: t = "Bad TS in ATR"; break;
391 case 0xFB: t = "An all inclusive hardware error occurred"; break;
392 case 0xFC: t = "Overrun error while talking to the ICC"; break;
393 case 0xFD: t = "Parity error while talking to the ICC"; break;
394 case 0xFE: t = "CCID timed out while talking to the ICC"; break;
395 case 0xFF: t = "Host aborted the current activity"; break;
398 if (ec > 0 && ec < 128)
399 sprintf (buffer, "Parameter error at offset %d", ec);
401 sprintf (buffer, "Error code %02X", ec);
405 DEBUGOUT_1 ("CCID command failed: %s\n", t);
410 print_pr_data (const unsigned char *data, size_t datalen, size_t off)
414 for (; off < datalen; off++)
416 if (!any || !(off % 16))
420 DEBUGOUT_1 (" [%04lu] ", (unsigned long) off);
422 DEBUGOUT_CONT_1 (" %02X", data[off]);
425 if (any && (off % 16))
431 print_p2r_header (const char *name, const unsigned char *msg, size_t msglen)
433 DEBUGOUT_1 ("%s:\n", name);
436 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
437 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
438 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
443 print_p2r_iccpoweron (const unsigned char *msg, size_t msglen)
445 print_p2r_header ("PC_to_RDR_IccPowerOn", msg, msglen);
448 DEBUGOUT_2 (" bPowerSelect ......: 0x%02x (%s)\n", msg[7],
450 msg[7] == 1? "5.0 V":
451 msg[7] == 2? "3.0 V":
452 msg[7] == 3? "1.8 V":"");
453 print_pr_data (msg, msglen, 8);
458 print_p2r_iccpoweroff (const unsigned char *msg, size_t msglen)
460 print_p2r_header ("PC_to_RDR_IccPowerOff", msg, msglen);
461 print_pr_data (msg, msglen, 7);
466 print_p2r_getslotstatus (const unsigned char *msg, size_t msglen)
468 print_p2r_header ("PC_to_RDR_GetSlotStatus", msg, msglen);
469 print_pr_data (msg, msglen, 7);
474 print_p2r_xfrblock (const unsigned char *msg, size_t msglen)
478 print_p2r_header ("PC_to_RDR_XfrBlock", msg, msglen);
481 DEBUGOUT_1 (" bBWI ..............: 0x%02x\n", msg[7]);
482 val = convert_le_u16 (msg+8);
483 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
484 val == 1? " (continued)":
485 val == 2? " (continues+ends)":
486 val == 3? " (continues+continued)":
487 val == 16? " (DataBlock-expected)":"");
488 print_pr_data (msg, msglen, 10);
493 print_p2r_getparameters (const unsigned char *msg, size_t msglen)
495 print_p2r_header ("PC_to_RDR_GetParameters", msg, msglen);
496 print_pr_data (msg, msglen, 7);
501 print_p2r_resetparameters (const unsigned char *msg, size_t msglen)
503 print_p2r_header ("PC_to_RDR_ResetParameters", msg, msglen);
504 print_pr_data (msg, msglen, 7);
509 print_p2r_setparameters (const unsigned char *msg, size_t msglen)
511 print_p2r_header ("PC_to_RDR_SetParameters", msg, msglen);
514 DEBUGOUT_1 (" bProtocolNum ......: 0x%02x\n", msg[7]);
515 print_pr_data (msg, msglen, 8);
520 print_p2r_escape (const unsigned char *msg, size_t msglen)
522 print_p2r_header ("PC_to_RDR_Escape", msg, msglen);
523 print_pr_data (msg, msglen, 7);
528 print_p2r_iccclock (const unsigned char *msg, size_t msglen)
530 print_p2r_header ("PC_to_RDR_IccClock", msg, msglen);
533 DEBUGOUT_1 (" bClockCommand .....: 0x%02x\n", msg[7]);
534 print_pr_data (msg, msglen, 8);
539 print_p2r_to0apdu (const unsigned char *msg, size_t msglen)
541 print_p2r_header ("PC_to_RDR_T0APDU", msg, msglen);
544 DEBUGOUT_1 (" bmChanges .........: 0x%02x\n", msg[7]);
545 DEBUGOUT_1 (" bClassGetResponse .: 0x%02x\n", msg[8]);
546 DEBUGOUT_1 (" bClassEnvelope ....: 0x%02x\n", msg[9]);
547 print_pr_data (msg, msglen, 10);
552 print_p2r_secure (const unsigned char *msg, size_t msglen)
556 print_p2r_header ("PC_to_RDR_Secure", msg, msglen);
559 DEBUGOUT_1 (" bBMI ..............: 0x%02x\n", msg[7]);
560 val = convert_le_u16 (msg+8);
561 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
562 val == 1? " (continued)":
563 val == 2? " (continues+ends)":
564 val == 3? " (continues+continued)":
565 val == 16? " (DataBlock-expected)":"");
566 print_pr_data (msg, msglen, 10);
571 print_p2r_mechanical (const unsigned char *msg, size_t msglen)
573 print_p2r_header ("PC_to_RDR_Mechanical", msg, msglen);
576 DEBUGOUT_1 (" bFunction .........: 0x%02x\n", msg[7]);
577 print_pr_data (msg, msglen, 8);
582 print_p2r_abort (const unsigned char *msg, size_t msglen)
584 print_p2r_header ("PC_to_RDR_Abort", msg, msglen);
585 print_pr_data (msg, msglen, 7);
590 print_p2r_setdatarate (const unsigned char *msg, size_t msglen)
592 print_p2r_header ("PC_to_RDR_SetDataRate", msg, msglen);
595 print_pr_data (msg, msglen, 7);
600 print_p2r_unknown (const unsigned char *msg, size_t msglen)
602 print_p2r_header ("Unknown PC_to_RDR command", msg, msglen);
605 print_pr_data (msg, msglen, 0);
610 print_r2p_header (const char *name, const unsigned char *msg, size_t msglen)
612 DEBUGOUT_1 ("%s:\n", name);
615 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
616 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
617 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
618 DEBUGOUT_1 (" bStatus ...........: %u\n", msg[7]);
620 DEBUGOUT_1 (" bError ............: %u\n", msg[8]);
625 print_r2p_datablock (const unsigned char *msg, size_t msglen)
627 print_r2p_header ("RDR_to_PC_DataBlock", msg, msglen);
631 DEBUGOUT_2 (" bChainParameter ...: 0x%02x%s\n", msg[9],
632 msg[9] == 1? " (continued)":
633 msg[9] == 2? " (continues+ends)":
634 msg[9] == 3? " (continues+continued)":
635 msg[9] == 16? " (XferBlock-expected)":"");
636 print_pr_data (msg, msglen, 10);
641 print_r2p_slotstatus (const unsigned char *msg, size_t msglen)
643 print_r2p_header ("RDR_to_PC_SlotStatus", msg, msglen);
646 DEBUGOUT_2 (" bClockStatus ......: 0x%02x%s\n", msg[9],
647 msg[9] == 0? " (running)":
648 msg[9] == 1? " (stopped-L)":
649 msg[9] == 2? " (stopped-H)":
650 msg[9] == 3? " (stopped)":"");
651 print_pr_data (msg, msglen, 10);
656 print_r2p_parameters (const unsigned char *msg, size_t msglen)
658 print_r2p_header ("RDR_to_PC_Parameters", msg, msglen);
662 DEBUGOUT_1 (" protocol ..........: T=%d\n", msg[9]);
663 if (msglen == 17 && msg[9] == 1)
666 DEBUGOUT_1 (" bmFindexDindex ....: %02X\n", msg[10]);
667 DEBUGOUT_1 (" bmTCCKST1 .........: %02X\n", msg[11]);
668 DEBUGOUT_1 (" bGuardTimeT1 ......: %02X\n", msg[12]);
669 DEBUGOUT_1 (" bmWaitingIntegersT1: %02X\n", msg[13]);
670 DEBUGOUT_1 (" bClockStop ........: %02X\n", msg[14]);
671 DEBUGOUT_1 (" bIFSC .............: %d\n", msg[15]);
672 DEBUGOUT_1 (" bNadValue .........: %d\n", msg[16]);
675 print_pr_data (msg, msglen, 10);
680 print_r2p_escape (const unsigned char *msg, size_t msglen)
682 print_r2p_header ("RDR_to_PC_Escape", msg, msglen);
685 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
686 print_pr_data (msg, msglen, 10);
691 print_r2p_datarate (const unsigned char *msg, size_t msglen)
693 print_r2p_header ("RDR_to_PC_DataRate", msg, msglen);
698 DEBUGOUT_1 (" dwClockFrequency ..: %u\n", convert_le_u32 (msg+10));
699 DEBUGOUT_1 (" dwDataRate ..... ..: %u\n", convert_le_u32 (msg+14));
700 print_pr_data (msg, msglen, 18);
703 print_pr_data (msg, msglen, 10);
708 print_r2p_unknown (const unsigned char *msg, size_t msglen)
710 print_r2p_header ("Unknown RDR_to_PC command", msg, msglen);
713 DEBUGOUT_1 (" bMessageType ......: %02X\n", msg[0]);
714 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
715 print_pr_data (msg, msglen, 10);
719 /* Parse a CCID descriptor, optionally print all available features
720 and test whether this reader is usable by this driver. Returns 0
723 Note, that this code is based on the one in lsusb.c of the
724 usb-utils package, I wrote on 2003-09-01. -wk. */
726 parse_ccid_descriptor (ccid_driver_t handle, unsigned short bcd_device,
727 const unsigned char *buf, size_t buflen)
731 int have_t1 = 0, have_tpdu=0;
733 handle->nonnull_nad = 0;
734 handle->auto_ifsd = 0;
735 handle->max_ifsd = 32;
736 handle->has_pinpad = 0;
737 handle->apdu_level = 0;
738 handle->auto_voltage = 0;
739 handle->auto_param = 0;
740 handle->auto_pps = 0;
741 DEBUGOUT_3 ("idVendor: %04X idProduct: %04X bcdDevice: %04X\n",
742 handle->id_vendor, handle->id_product, bcd_device);
743 if (buflen < 54 || buf[0] < 54)
745 DEBUGOUT ("CCID device descriptor is too short\n");
749 DEBUGOUT ("ChipCard Interface Descriptor:\n");
750 DEBUGOUT_1 (" bLength %5u\n", buf[0]);
751 DEBUGOUT_1 (" bDescriptorType %5u\n", buf[1]);
752 DEBUGOUT_2 (" bcdCCID %2x.%02x", buf[3], buf[2]);
753 if (buf[3] != 1 || buf[2] != 0)
754 DEBUGOUT_CONT(" (Warning: Only accurate for version 1.0)");
757 DEBUGOUT_1 (" nMaxSlotIndex %5u\n", buf[4]);
758 DEBUGOUT_2 (" bVoltageSupport %5u %s\n",
759 buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V"
760 : buf[5] == 3? "1.8V":"?"));
762 us = convert_le_u32 (buf+6);
763 DEBUGOUT_1 (" dwProtocols %5u ", us);
765 DEBUGOUT_CONT (" T=0");
768 DEBUGOUT_CONT (" T=1");
772 DEBUGOUT_CONT (" (Invalid values detected)");
775 us = convert_le_u32(buf+10);
776 DEBUGOUT_1 (" dwDefaultClock %5u\n", us);
777 us = convert_le_u32(buf+14);
778 DEBUGOUT_1 (" dwMaxiumumClock %5u\n", us);
779 DEBUGOUT_1 (" bNumClockSupported %5u\n", buf[18]);
780 us = convert_le_u32(buf+19);
781 DEBUGOUT_1 (" dwDataRate %7u bps\n", us);
782 us = convert_le_u32(buf+23);
783 DEBUGOUT_1 (" dwMaxDataRate %7u bps\n", us);
784 DEBUGOUT_1 (" bNumDataRatesSupp. %5u\n", buf[27]);
786 us = convert_le_u32(buf+28);
787 DEBUGOUT_1 (" dwMaxIFSD %5u\n", us);
788 handle->max_ifsd = us;
790 us = convert_le_u32(buf+32);
791 DEBUGOUT_1 (" dwSyncProtocols %08X ", us);
793 DEBUGOUT_CONT ( " 2-wire");
795 DEBUGOUT_CONT ( " 3-wire");
797 DEBUGOUT_CONT ( " I2C");
800 us = convert_le_u32(buf+36);
801 DEBUGOUT_1 (" dwMechanical %08X ", us);
803 DEBUGOUT_CONT (" accept");
805 DEBUGOUT_CONT (" eject");
807 DEBUGOUT_CONT (" capture");
809 DEBUGOUT_CONT (" lock");
812 us = convert_le_u32(buf+40);
813 DEBUGOUT_1 (" dwFeatures %08X\n", us);
816 DEBUGOUT (" Auto configuration based on ATR (assumes auto voltage)\n");
817 handle->auto_voltage = 1;
820 DEBUGOUT (" Auto activation on insert\n");
823 DEBUGOUT (" Auto voltage selection\n");
824 handle->auto_voltage = 1;
827 DEBUGOUT (" Auto clock change\n");
829 DEBUGOUT (" Auto baud rate change\n");
832 DEBUGOUT (" Auto parameter negotiation made by CCID\n");
833 handle->auto_param = 1;
835 else if ((us & 0x0080))
837 DEBUGOUT (" Auto PPS made by CCID\n");
838 handle->auto_pps = 1;
840 if ((us & (0x0040 | 0x0080)) == (0x0040 | 0x0080))
841 DEBUGOUT (" WARNING: conflicting negotiation features\n");
844 DEBUGOUT (" CCID can set ICC in clock stop mode\n");
847 DEBUGOUT (" NAD value other than 0x00 accepted\n");
848 handle->nonnull_nad = 1;
852 DEBUGOUT (" Auto IFSD exchange\n");
853 handle->auto_ifsd = 1;
856 if ((us & 0x00010000))
858 DEBUGOUT (" TPDU level exchange\n");
861 else if ((us & 0x00020000))
863 DEBUGOUT (" Short APDU level exchange\n");
864 handle->apdu_level = 1;
866 else if ((us & 0x00040000))
868 DEBUGOUT (" Short and extended APDU level exchange\n");
869 handle->apdu_level = 2;
871 else if ((us & 0x00070000))
872 DEBUGOUT (" WARNING: conflicting exchange levels\n");
874 us = convert_le_u32(buf+44);
875 DEBUGOUT_1 (" dwMaxCCIDMsgLen %5u\n", us);
876 handle->max_ccid_msglen = us;
878 DEBUGOUT ( " bClassGetResponse ");
880 DEBUGOUT_CONT ("echo\n");
882 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
884 DEBUGOUT ( " bClassEnvelope ");
886 DEBUGOUT_CONT ("echo\n");
888 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
890 DEBUGOUT ( " wlcdLayout ");
891 if (!buf[50] && !buf[51])
892 DEBUGOUT_CONT ("none\n");
894 DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]);
896 DEBUGOUT_1 (" bPINSupport %5u ", buf[52]);
899 DEBUGOUT_CONT ( " verification");
900 handle->has_pinpad |= 1;
904 DEBUGOUT_CONT ( " modification");
905 handle->has_pinpad |= 2;
909 DEBUGOUT_1 (" bMaxCCIDBusySlots %5u\n", buf[53]);
914 for (i=54; i < buf[0]-54; i++)
915 DEBUGOUT_CONT_1 (" %02X", buf[i]);
919 if (!have_t1 || !(have_tpdu || handle->apdu_level))
921 DEBUGOUT ("this drivers requires that the reader supports T=1, "
922 "TPDU or APDU level exchange - this is not available\n");
927 /* SCM drivers get stuck in their internal USB stack if they try to
928 send a frame of n*wMaxPacketSize back to us. Given that
929 wMaxPacketSize is 64 for these readers we set the IFSD to a value
931 64 - 10 CCID header - 4 T1frame - 2 reserved = 48
938 0x5117 - SCR 3320 USB ID-000 reader
939 seems to be very slow but enabling this workaround boosts the
940 performance to a more or less acceptable level (tested by David).
943 if (handle->id_vendor == VENDOR_SCM
944 && handle->max_ifsd > 48
945 && ( (handle->id_product == SCM_SCR331 && bcd_device < 0x0516)
946 ||(handle->id_product == SCM_SCR331DI && bcd_device < 0x0620)
947 ||(handle->id_product == SCM_SCR335 && bcd_device < 0x0514)
948 ||(handle->id_product == SCM_SPR532 && bcd_device < 0x0504)
949 ||(handle->id_product == SCM_SCR3320 && bcd_device < 0x0522)
952 DEBUGOUT ("enabling workaround for buggy SCM readers\n");
953 handle->max_ifsd = 48;
956 if (handle->id_vendor == VENDOR_GEMPC)
958 DEBUGOUT ("enabling product quirk: disable non-null NAD\n");
959 handle->nonnull_nad = 0;
967 get_escaped_usb_string (libusb_device_handle *idev, int idx,
968 const char *prefix, const char *suffix)
971 unsigned char buf[280];
980 /* Fixme: The next line is for the current Valgrid without support
982 memset (buf, 0, sizeof buf);
984 /* First get the list of supported languages and use the first one.
985 If we do don't find it we try to use English. Note that this is
986 all in a 2 bute Unicode encoding using little endian. */
990 rc = libusb_control_transfer (idev, LIBUSB_ENDPOINT_IN,
991 LIBUSB_REQUEST_GET_DESCRIPTOR,
992 (LIBUSB_DT_STRING << 8), 0,
993 buf, sizeof buf, 1000 /* ms timeout */);
998 langid = 0x0409; /* English. */
1000 langid = (buf[3] << 8) | buf[2];
1005 rc = libusb_control_transfer (idev, LIBUSB_ENDPOINT_IN,
1006 LIBUSB_REQUEST_GET_DESCRIPTOR,
1007 (LIBUSB_DT_STRING << 8) + idx, langid,
1008 buf, sizeof buf, 1000 /* ms timeout */);
1012 if (rc < 2 || buf[1] != LIBUSB_DT_STRING)
1013 return NULL; /* Error or not a string. */
1016 return NULL; /* Larger than our buffer. */
1018 for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2)
1021 n++; /* High byte set. */
1022 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
1028 result = malloc (strlen (prefix) + n + strlen (suffix) + 1);
1032 strcpy (result, prefix);
1033 n = strlen (prefix);
1034 for (s=buf+2, i=2; i+1 < len; i += 2, s += 2)
1037 result[n++] = '\xff'; /* High byte set. */
1038 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
1040 sprintf (result+n, "%%%02X", *s);
1046 strcpy (result+n, suffix);
1051 /* This function creates an reader id to be used to find the same
1052 physical reader after a reset. It returns an allocated and possibly
1053 percent escaped string or NULL if not enough memory is available. */
1055 make_reader_id (libusb_device_handle *idev,
1056 unsigned int vendor, unsigned int product,
1057 unsigned char serialno_index)
1062 sprintf (prefix, "%04X:%04X:", (vendor & 0xffff), (product & 0xffff));
1063 rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0");
1066 rid = malloc (strlen (prefix) + 3 + 1);
1069 strcpy (rid, prefix);
1070 strcat (rid, "X:0");
1076 /* Helper to find the endpoint from an interface descriptor. */
1078 find_endpoint (const struct libusb_interface_descriptor *ifcdesc, int mode)
1081 int want_bulk_in = 0;
1084 want_bulk_in = 0x80;
1085 for (no=0; no < ifcdesc->bNumEndpoints; no++)
1087 const struct libusb_endpoint_descriptor *ep = ifcdesc->endpoint + no;
1088 if (ep->bDescriptorType != LIBUSB_DT_ENDPOINT)
1091 && ((ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
1092 == LIBUSB_TRANSFER_TYPE_INTERRUPT)
1093 && (ep->bEndpointAddress & 0x80))
1094 return ep->bEndpointAddress;
1095 else if ((mode == 0 || mode == 1)
1096 && ((ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
1097 == LIBUSB_TRANSFER_TYPE_BULK)
1098 && (ep->bEndpointAddress & 0x80) == want_bulk_in)
1099 return ep->bEndpointAddress;
1106 /* Helper for scan_devices. This function returns true if a
1107 requested device has been found or the caller should stop scanning
1108 for other reasons. */
1110 scan_usb_device (int *count, char **rid_list, struct libusb_device *dev)
1114 const struct libusb_interface_descriptor *ifcdesc;
1116 libusb_device_handle *idev = NULL;
1118 struct libusb_config_descriptor *config;
1119 struct libusb_device_descriptor desc;
1122 err = libusb_get_device_descriptor (dev, &desc);
1126 err = libusb_get_active_config_descriptor (dev, &config);
1130 for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
1131 for (set_no=0; set_no < config->interface[ifc_no].num_altsetting; set_no++)
1133 ifcdesc = (config->interface[ifc_no].altsetting + set_no);
1134 /* The second condition is for older SCM SPR 532 who did
1135 not know about the assigned CCID class. The third
1136 condition does the same for a Cherry SmartTerminal
1137 ST-2000. Instead of trying to interpret the strings
1138 we simply check the product ID. */
1139 if (ifcdesc && ifcdesc->extra
1140 && ((ifcdesc->bInterfaceClass == 11
1141 && ifcdesc->bInterfaceSubClass == 0
1142 && ifcdesc->bInterfaceProtocol == 0)
1143 || (ifcdesc->bInterfaceClass == 255
1144 && desc.idVendor == VENDOR_SCM
1145 && desc.idProduct == SCM_SPR532)
1146 || (ifcdesc->bInterfaceClass == 255
1147 && desc.idVendor == VENDOR_CHERRY
1148 && desc.idProduct == CHERRY_ST2000)))
1152 err = libusb_open (dev, &idev);
1155 DEBUGOUT_1 ("usb_open failed: %s\n", libusb_error_name (err));
1156 continue; /* with next setting. */
1159 rid = make_reader_id (idev, desc.idVendor, desc.idProduct,
1160 desc.iSerialNumber);
1163 libusb_free_config_descriptor (config);
1167 /* We are collecting infos about all available CCID
1168 readers. Store them and continue. */
1169 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n", *count, rid);
1170 p = malloc ((*rid_list? strlen (*rid_list):0) + 1
1171 + strlen (rid) + 1);
1177 strcat (p, *rid_list);
1184 else /* Out of memory. */
1186 libusb_free_config_descriptor (config);
1192 libusb_close (idev);
1197 libusb_free_config_descriptor (config);
1200 /* Scan all CCID devices.
1202 The function returns 0 if a reader has been found or when a scan
1203 returned without error.
1205 R_RID should be the address where to store the list of reader_ids
1206 we found. If on return this list is empty, no CCID device has been
1207 found; otherwise it points to an allocated linked list of reader
1211 scan_devices (char **r_rid)
1213 char *rid_list = NULL;
1215 libusb_device **dev_list = NULL;
1220 /* Set return values to a default. */
1224 n = libusb_get_device_list (NULL, &dev_list);
1226 for (i = 0; i < n; i++)
1229 scan_usb_device (&count, &rid_list, dev);
1232 libusb_free_device_list (dev_list, 1);
1239 #ifdef USE_LIBUSB_DEBUG_CB
1241 debug_libusb_cb (libusb_context *ctx, enum libusb_log_level level,
1244 int n = str? strlen (str):0;
1248 /* Strip the LF so that our logging filter does not escape it. */
1249 if (n && str[n-1] == '\n')
1251 log_debug ("libusb{%d}: %.*s\n", level, n, str);
1253 #endif /* USE_LIBUSB_DEBUG_CB */
1256 /* Set the level of debugging to LEVEL and return the old level. -1
1257 just returns the old level. A level of 0 disables debugging, 1
1258 enables debugging, 2 enables additional tracing of the T=1
1259 protocol, 3 additionally enables debugging for GetSlotStatus, other
1260 values are not yet defined.
1262 Note that libusb may provide its own debugging feature which is
1263 enabled by setting the envvar USB_DEBUG. */
1265 ccid_set_debug_level (int level)
1267 int old = debug_level;
1269 debug_level = level;
1270 #ifdef USE_LIBUSB_DEBUG_CB
1273 log_debug ("libusb: Enable logging\n");
1274 libusb_set_log_cb (NULL, debug_libusb_cb, LIBUSB_LOG_CB_GLOBAL);
1275 libusb_set_option (NULL, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_DEBUG);
1278 libusb_set_log_cb (NULL, NULL, LIBUSB_LOG_CB_GLOBAL);
1279 #endif /* USE_LIBUSB_DEBUG_CB */
1285 ccid_get_reader_list (void)
1289 if (!initialized_usb)
1292 if ((rc = libusb_init (NULL)))
1294 DEBUGOUT_1 ("usb_init failed: %s.\n", libusb_error_name (rc));
1297 initialized_usb = 1;
1300 if (scan_devices (&reader_list))
1301 return NULL; /* Error. */
1306 /* Vendor specific custom initialization. */
1308 ccid_vendor_specific_init (ccid_driver_t handle)
1312 if (handle->id_vendor == VENDOR_VEGA && handle->id_product == VEGA_ALPHA)
1315 * Vega alpha has a feature to show retry counter on the pinpad
1316 * display. But it assumes that the card returns the value of
1317 * retry counter by VERIFY with empty data (return code of
1318 * 63Cx). Unfortunately, existing OpenPGP cards don't support
1319 * VERIFY command with empty data. This vendor specific command
1320 * sequence is to disable the feature.
1322 const unsigned char cmd[] = { '\xb5', '\x01', '\x00', '\x03', '\x00' };
1324 r = send_escape_cmd (handle, cmd, sizeof (cmd), NULL, 0, NULL);
1326 else if (handle->id_vendor == VENDOR_SCM && handle->id_product == SCM_SPR532)
1329 * It seems that SEQ may be out of sync between host and the card reader,
1330 * and SET_INTERFACE doesn't reset it. Make sure it works at the init.
1332 abort_cmd (handle, 0, 1);
1335 if (r != 0 && r != CCID_DRIVER_ERR_CARD_INACTIVE
1336 && r != CCID_DRIVER_ERR_NO_CARD)
1344 ccid_vendor_specific_setup (ccid_driver_t handle)
1346 if (handle->id_vendor == VENDOR_SCM && handle->id_product == SCM_SPR532)
1351 libusb_clear_halt (handle->idev, handle->ep_intr);
1361 ccid_vendor_specific_pinpad_setup (ccid_driver_t handle)
1363 if (handle->id_vendor == VENDOR_SCM && handle->id_product == SCM_SPR532)
1365 DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n");
1366 send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3,
1374 ccid_dev_scan (int *idx_max_p, void **t_p)
1387 if (!initialized_usb)
1390 if ((rc = libusb_init (NULL)))
1392 DEBUGOUT_1 ("usb_init failed: %s.\n", libusb_error_name (rc));
1393 return gpg_error (GPG_ERR_ENODEV);
1395 initialized_usb = 1;
1398 n = libusb_get_device_list (NULL, &ccid_usb_dev_list);
1399 for (i = 0; i < n; i++)
1401 struct libusb_config_descriptor *config;
1402 struct libusb_device_descriptor desc;
1404 dev = ccid_usb_dev_list[i];
1406 if (libusb_get_device_descriptor (dev, &desc))
1409 if (libusb_get_active_config_descriptor (dev, &config))
1412 for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
1413 for (set_no=0; set_no < config->interface[ifc_no].num_altsetting;
1416 const struct libusb_interface_descriptor *ifcdesc;
1418 ifcdesc = &config->interface[ifc_no].altsetting[set_no];
1419 /* The second condition is for older SCM SPR 532 who did
1420 not know about the assigned CCID class. The third
1421 condition does the same for a Cherry SmartTerminal
1422 ST-2000. Instead of trying to interpret the strings
1423 we simply check the product ID. */
1424 if (ifcdesc && ifcdesc->extra
1425 && ((ifcdesc->bInterfaceClass == 11
1426 && ifcdesc->bInterfaceSubClass == 0
1427 && ifcdesc->bInterfaceProtocol == 0)
1428 || (ifcdesc->bInterfaceClass == 255
1429 && desc.idVendor == VENDOR_SCM
1430 && desc.idProduct == SCM_SPR532)
1431 || (ifcdesc->bInterfaceClass == 255
1432 && desc.idVendor == VENDOR_CHERRY
1433 && desc.idProduct == CHERRY_ST2000)))
1435 /* Found a reader. */
1436 unsigned char *ifcdesc_extra;
1438 ifcdesc_extra = malloc (ifcdesc->extra_length);
1441 err = gpg_error_from_syserror ();
1442 libusb_free_config_descriptor (config);
1445 memcpy (ifcdesc_extra, ifcdesc->extra, ifcdesc->extra_length);
1447 ccid_dev_table[idx].n = i;
1448 ccid_dev_table[idx].interface_number = ifc_no;
1449 ccid_dev_table[idx].setting_number = set_no;
1450 ccid_dev_table[idx].ifcdesc_extra = ifcdesc_extra;
1451 ccid_dev_table[idx].ifcdesc_extra_len = ifcdesc->extra_length;
1452 ccid_dev_table[idx].ep_bulk_out = find_endpoint (ifcdesc, 0);
1453 ccid_dev_table[idx].ep_bulk_in = find_endpoint (ifcdesc, 1);
1454 ccid_dev_table[idx].ep_intr = find_endpoint (ifcdesc, 2);
1457 if (idx >= CCID_MAX_DEVICE)
1459 libusb_free_config_descriptor (config);
1466 libusb_free_config_descriptor (config);
1473 for (i = 0; i < idx; i++)
1475 free (ccid_dev_table[i].ifcdesc_extra);
1476 ccid_dev_table[i].n = 0;
1477 ccid_dev_table[i].interface_number = 0;
1478 ccid_dev_table[i].setting_number = 0;
1479 ccid_dev_table[i].ifcdesc_extra = NULL;
1480 ccid_dev_table[i].ifcdesc_extra_len = 0;
1481 ccid_dev_table[i].ep_bulk_out = 0;
1482 ccid_dev_table[i].ep_bulk_in = 0;
1483 ccid_dev_table[i].ep_intr = 0;
1485 libusb_free_device_list (ccid_usb_dev_list, 1);
1486 ccid_usb_dev_list = NULL;
1492 *t_p = ccid_dev_table;
1501 ccid_dev_scan_finish (void *tbl0, int max)
1504 struct ccid_dev_table *tbl = tbl0;
1506 for (i = 0; i < max; i++)
1508 free (tbl[i].ifcdesc_extra);
1510 tbl[i].interface_number = 0;
1511 tbl[i].setting_number = 0;
1512 tbl[i].ifcdesc_extra = NULL;
1513 tbl[i].ifcdesc_extra_len = 0;
1514 tbl[i].ep_bulk_out = 0;
1515 tbl[i].ep_bulk_in = 0;
1518 libusb_free_device_list (ccid_usb_dev_list, 1);
1519 ccid_usb_dev_list = NULL;
1523 ccid_get_BAI (int idx, void *tbl0)
1526 int bus, addr, intf;
1529 struct ccid_dev_table *tbl = tbl0;
1532 dev = ccid_usb_dev_list[n];
1534 bus = libusb_get_bus_number (dev);
1535 addr = libusb_get_device_address (dev);
1536 intf = tbl[idx].interface_number;
1537 bai = (bus << 16) | (addr << 8) | intf;
1543 ccid_compare_BAI (ccid_driver_t handle, unsigned int bai)
1545 return handle->bai == bai;
1550 intr_cb (struct libusb_transfer *transfer)
1552 ccid_driver_t handle = transfer->user_data;
1554 DEBUGOUT_2 ("CCID: interrupt callback %d (%d)\n",
1555 transfer->status, transfer->actual_length);
1557 if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT)
1562 /* Submit the URB again to keep watching the INTERRUPT transfer. */
1563 err = libusb_submit_transfer (transfer);
1564 if (err == LIBUSB_ERROR_NO_DEVICE)
1565 goto device_removed;
1567 DEBUGOUT_1 ("CCID submit transfer again %d\n", err);
1569 else if (transfer->status == LIBUSB_TRANSFER_COMPLETED)
1571 size_t len = transfer->actual_length;
1572 unsigned char *p = transfer->buffer;
1573 int card_removed = 0;
1577 if (*p == RDR_to_PC_NotifySlotChange)
1582 DEBUGOUT_1 ("CCID: NotifySlotChange: %02x\n", p[1]);
1592 else if (*p == RDR_to_PC_HardwareError)
1597 DEBUGOUT_1 ("CCID: hardware error detected: %02x\n", p[3]);
1603 DEBUGOUT_1 ("CCID: unknown intr: %02x\n", p[0]);
1610 DEBUGOUT ("CCID: card removed\n");
1611 handle->powered_off = 1;
1612 #if defined(GNUPG_MAJOR_VERSION)
1613 scd_kick_the_loop ();
1618 /* Event other than card removal. */
1622 else if (transfer->status == LIBUSB_TRANSFER_CANCELLED)
1623 handle->powered_off = 1;
1624 else if (transfer->status == LIBUSB_TRANSFER_OVERFLOW)
1626 /* Something goes wrong. Ignore. */
1627 DEBUGOUT ("CCID: interrupt transfer overflow\n");
1632 DEBUGOUT ("CCID: device removed\n");
1633 handle->powered_off = 1;
1634 #if defined(GNUPG_MAJOR_VERSION)
1635 scd_kick_the_loop ();
1641 ccid_setup_intr (ccid_driver_t handle)
1643 struct libusb_transfer *transfer;
1646 transfer = libusb_alloc_transfer (0);
1647 handle->transfer = transfer;
1648 libusb_fill_interrupt_transfer (transfer, handle->idev, handle->ep_intr,
1649 handle->intr_buf, sizeof (handle->intr_buf),
1650 intr_cb, handle, 0);
1651 err = libusb_submit_transfer (transfer);
1652 DEBUGOUT_2 ("CCID submit transfer (%x): %d", handle->ep_intr, err);
1657 ccid_usb_thread (void *arg)
1659 libusb_context *ctx = arg;
1661 while (ccid_usb_thread_is_alive)
1666 libusb_handle_events_completed (ctx, NULL);
1677 ccid_open_usb_reader (const char *spec_reader_name,
1678 int idx, void *ccid_table0,
1679 ccid_driver_t *handle, char **rdrname_p)
1682 libusb_device_handle *idev = NULL;
1686 struct libusb_device_descriptor desc;
1690 struct ccid_dev_table *ccid_table = ccid_table0;
1692 n = ccid_table[idx].n;
1693 ifc_no = ccid_table[idx].interface_number;
1694 set_no = ccid_table[idx].setting_number;
1696 dev = ccid_usb_dev_list[n];
1697 bus = libusb_get_bus_number (dev);
1698 addr = libusb_get_device_address (dev);
1699 bai = (bus << 16) | (addr << 8) | ifc_no;
1701 rc = libusb_open (dev, &idev);
1704 DEBUGOUT_1 ("usb_open failed: %s\n", libusb_error_name (rc));
1707 return map_libusb_error (rc);
1710 if (ccid_usb_thread_is_alive++ == 0)
1716 err = npth_attr_init (&tattr);
1719 DEBUGOUT_1 ("npth_attr_init failed: %s\n", strerror (err));
1725 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
1726 err = npth_create (&thread, &tattr, ccid_usb_thread, NULL);
1729 DEBUGOUT_1 ("npth_create failed: %s\n", strerror (err));
1734 npth_setname_np (thread, "ccid_usb_thread");
1736 npth_attr_destroy (&tattr);
1739 rc = libusb_get_device_descriptor (dev, &desc);
1742 DEBUGOUT ("get_device_descripor failed\n");
1743 rc = map_libusb_error (rc);
1747 rid = make_reader_id (idev, desc.idVendor, desc.idProduct,
1748 desc.iSerialNumber);
1750 /* Check to see if reader name matches the spec. */
1751 if (spec_reader_name
1752 && strncmp (rid, spec_reader_name, strlen (spec_reader_name)))
1754 DEBUGOUT ("device not matched\n");
1755 rc = CCID_DRIVER_ERR_NO_READER;
1759 (*handle)->id_vendor = desc.idVendor;
1760 (*handle)->id_product = desc.idProduct;
1761 (*handle)->idev = idev;
1762 (*handle)->bai = bai;
1763 (*handle)->ifc_no = ifc_no;
1764 (*handle)->ep_bulk_out = ccid_table[idx].ep_bulk_out;
1765 (*handle)->ep_bulk_in = ccid_table[idx].ep_bulk_in;
1766 (*handle)->ep_intr = ccid_table[idx].ep_intr;
1768 DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n", idx, rid);
1770 if (parse_ccid_descriptor (*handle, desc.bcdDevice,
1771 ccid_table[idx].ifcdesc_extra,
1772 ccid_table[idx].ifcdesc_extra_len))
1774 DEBUGOUT ("device not supported\n");
1775 rc = CCID_DRIVER_ERR_NO_READER;
1782 rc = libusb_claim_interface (idev, ifc_no);
1788 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1789 rc = map_libusb_error (rc);
1793 /* Submit SET_INTERFACE control transfer which can reset the device. */
1794 rc = libusb_set_interface_alt_setting (idev, ifc_no, set_no);
1800 DEBUGOUT_1 ("usb_set_interface_alt_setting failed: %d\n", rc);
1801 rc = map_libusb_error (rc);
1809 rc = ccid_vendor_specific_init (*handle);
1814 --ccid_usb_thread_is_alive;
1816 libusb_release_interface (idev, ifc_no);
1817 libusb_close (idev);
1832 /* Open the reader with the internal number READERNO and return a
1833 pointer to be used as handle in HANDLE. Returns 0 on success. */
1835 ccid_open_reader (const char *spec_reader_name, int idx,
1837 ccid_driver_t *handle, char **rdrname_p)
1839 struct ccid_dev_table *ccid_table = ccid_table0;
1841 *handle = calloc (1, sizeof **handle);
1844 DEBUGOUT ("out of memory\n");
1845 return CCID_DRIVER_ERR_OUT_OF_CORE;
1848 return ccid_open_usb_reader (spec_reader_name, idx, ccid_table,
1854 ccid_require_get_status (ccid_driver_t handle)
1856 /* When a card reader supports interrupt transfer to check the
1857 status of card, it is possible to submit only an interrupt
1858 transfer, and no check is required by application layer. USB can
1859 detect removal of a card and can detect removal of a reader.
1861 if (handle->ep_intr >= 0)
1863 if (handle->id_vendor != VENDOR_SCM)
1867 * For card reader with interrupt transfer support, ideally,
1868 * removal is detected by intr_cb, but some card reader
1869 * (e.g. SPR532) has a possible case of missing report to
1870 * intr_cb, and another case of valid report to intr_cb.
1872 * For such a reader, the removal should be able to be detected
1873 * by PC_to_RDR_GetSlotStatus, too. Thus, calls to
1874 * ccid_slot_status should go on wire even if "on_wire" is not
1878 if (handle->transfer == NULL)
1882 /* Libusb actually detects the removal of USB device in use.
1883 However, there is no good API to handle the removal (yet),
1884 cleanly and with good portability.
1886 There is libusb_set_pollfd_notifiers function, but it doesn't
1887 offer libusb_device_handle* data to its callback. So, when it
1888 watches multiple devices, there is no way to know which device is
1891 Once, we will have a good programming interface of libusb, we can
1892 list tokens (with no interrupt transfer support, but always with
1893 card inserted) here to return 0, so that scdaemon can submit
1894 minimum packet on wire.
1900 send_power_off (ccid_driver_t handle)
1903 unsigned char msg[100];
1905 unsigned char seqno;
1907 msg[0] = PC_to_RDR_IccPowerOff;
1908 msg[5] = 0; /* slot */
1909 msg[6] = seqno = handle->seqno++;
1910 msg[7] = 0; /* RFU */
1911 msg[8] = 0; /* RFU */
1912 msg[9] = 0; /* RFU */
1913 set_msg_len (msg, 0);
1916 rc = bulk_out (handle, msg, msglen, 0);
1918 bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1924 do_close_reader (ccid_driver_t handle)
1928 if (!handle->powered_off)
1929 send_power_off (handle);
1931 if (handle->transfer)
1933 if (!handle->powered_off)
1935 DEBUGOUT ("libusb_cancel_transfer\n");
1937 rc = libusb_cancel_transfer (handle->transfer);
1938 if (rc != LIBUSB_ERROR_NOT_FOUND)
1939 while (!handle->powered_off)
1941 DEBUGOUT ("libusb_handle_events_completed\n");
1945 libusb_handle_events_completed (NULL, &handle->powered_off);
1952 libusb_free_transfer (handle->transfer);
1953 handle->transfer = NULL;
1956 DEBUGOUT ("libusb_release_interface and libusb_close\n");
1957 libusb_release_interface (handle->idev, handle->ifc_no);
1958 --ccid_usb_thread_is_alive;
1959 libusb_close (handle->idev);
1960 handle->idev = NULL;
1965 ccid_set_progress_cb (ccid_driver_t handle,
1966 void (*cb)(void *, const char *, int, int, int),
1970 return CCID_DRIVER_ERR_INV_VALUE;
1972 handle->progress_cb = cb;
1973 handle->progress_cb_arg = cb_arg;
1979 ccid_set_prompt_cb (ccid_driver_t handle,
1980 void (*cb)(void *, int), void *cb_arg)
1983 return CCID_DRIVER_ERR_INV_VALUE;
1985 handle->prompt_cb = cb;
1986 handle->prompt_cb_arg = cb_arg;
1991 /* Close the reader HANDLE. */
1993 ccid_close_reader (ccid_driver_t handle)
1998 do_close_reader (handle);
2004 /* Return False if a card is present and powered. */
2006 ccid_check_card_presence (ccid_driver_t handle)
2008 (void)handle; /* Not yet implemented. */
2013 /* Write a MSG of length MSGLEN to the designated bulk out endpoint.
2014 Returns 0 on success. */
2016 bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
2022 /* No need to continue and clutter the log with USB write error
2023 messages after we got the first ENODEV. */
2024 if (handle->enodev_seen)
2025 return CCID_DRIVER_ERR_NO_READER;
2027 if (debug_level && (!no_debug || debug_level >= 3))
2029 switch (msglen? msg[0]:0)
2031 case PC_to_RDR_IccPowerOn:
2032 print_p2r_iccpoweron (msg, msglen);
2034 case PC_to_RDR_IccPowerOff:
2035 print_p2r_iccpoweroff (msg, msglen);
2037 case PC_to_RDR_GetSlotStatus:
2038 print_p2r_getslotstatus (msg, msglen);
2040 case PC_to_RDR_XfrBlock:
2041 print_p2r_xfrblock (msg, msglen);
2043 case PC_to_RDR_GetParameters:
2044 print_p2r_getparameters (msg, msglen);
2046 case PC_to_RDR_ResetParameters:
2047 print_p2r_resetparameters (msg, msglen);
2049 case PC_to_RDR_SetParameters:
2050 print_p2r_setparameters (msg, msglen);
2052 case PC_to_RDR_Escape:
2053 print_p2r_escape (msg, msglen);
2055 case PC_to_RDR_IccClock:
2056 print_p2r_iccclock (msg, msglen);
2058 case PC_to_RDR_T0APDU:
2059 print_p2r_to0apdu (msg, msglen);
2061 case PC_to_RDR_Secure:
2062 print_p2r_secure (msg, msglen);
2064 case PC_to_RDR_Mechanical:
2065 print_p2r_mechanical (msg, msglen);
2067 case PC_to_RDR_Abort:
2068 print_p2r_abort (msg, msglen);
2070 case PC_to_RDR_SetDataRate:
2071 print_p2r_setdatarate (msg, msglen);
2074 print_p2r_unknown (msg, msglen);
2082 rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_out,
2083 msg, msglen, &transferred,
2084 5000 /* ms timeout */);
2088 if (rc == 0 && transferred == msglen)
2093 DEBUGOUT_1 ("usb_bulk_write error: %s\n", libusb_error_name (rc));
2094 if (rc == LIBUSB_ERROR_NO_DEVICE)
2096 handle->enodev_seen = 1;
2097 return CCID_DRIVER_ERR_NO_READER;
2105 /* Read a maximum of LENGTH bytes from the bulk in endpoint into
2106 BUFFER and return the actual read number if bytes in NREAD. SEQNO
2107 is the sequence number used to send the request and EXPECTED_TYPE
2108 the type of message we expect. Does checks on the ccid
2109 header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to
2110 avoid debug messages in case of no error; this can be overridden
2111 with a glibal debug level of at least 3. Returns 0 on success. */
2113 bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
2114 size_t *nread, int expected_type, int seqno, int timeout,
2122 /* Fixme: The next line for the current Valgrind without support
2124 memset (buffer, 0, length);
2130 rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_in,
2131 buffer, length, &msglen, bwi*timeout);
2137 DEBUGOUT_1 ("usb_bulk_read error: %s\n", libusb_error_name (rc));
2138 if (rc == LIBUSB_ERROR_NO_DEVICE)
2139 handle->enodev_seen = 1;
2141 return map_libusb_error (rc);
2144 return CCID_DRIVER_ERR_INV_VALUE; /* Faulty libusb. */
2149 DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen);
2150 abort_cmd (handle, seqno, 0);
2151 return CCID_DRIVER_ERR_INV_VALUE;
2155 DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]);
2156 return CCID_DRIVER_ERR_INV_VALUE;
2158 if (buffer[6] != seqno)
2160 DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n",
2162 /* Retry until we are synced again. */
2166 /* We need to handle the time extension request before we check that
2167 we got the expected message type. This is in particular required
2168 for the Cherry keyboard which sends a time extension request for
2170 if (!(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80)
2172 /* Card present and active, time extension requested. */
2173 DEBUGOUT_2 ("time extension requested (%02X,%02X)\n",
2174 buffer[7], buffer[8]);
2177 if (buffer[8] != 0 && buffer[8] != 0xff)
2180 /* Gnuk enhancement to prompt user input by ack button */
2181 if (buffer[8] == 0xff && !notified)
2184 handle->prompt_cb (handle->prompt_cb_arg, 1);
2191 handle->prompt_cb (handle->prompt_cb_arg, 0);
2193 if (buffer[0] != expected_type && buffer[0] != RDR_to_PC_SlotStatus)
2195 DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]);
2196 abort_cmd (handle, seqno, 0);
2197 return CCID_DRIVER_ERR_INV_VALUE;
2200 if (debug_level && (!no_debug || debug_level >= 3))
2204 case RDR_to_PC_DataBlock:
2205 print_r2p_datablock (buffer, msglen);
2207 case RDR_to_PC_SlotStatus:
2208 print_r2p_slotstatus (buffer, msglen);
2210 case RDR_to_PC_Parameters:
2211 print_r2p_parameters (buffer, msglen);
2213 case RDR_to_PC_Escape:
2214 print_r2p_escape (buffer, msglen);
2216 case RDR_to_PC_DataRate:
2217 print_r2p_datarate (buffer, msglen);
2220 print_r2p_unknown (buffer, msglen);
2224 if (CCID_COMMAND_FAILED (buffer))
2228 ec = CCID_ERROR_CODE (buffer);
2229 print_command_failed (buffer);
2231 return CCID_DRIVER_ERR_UI_CANCELLED;
2232 else if (ec == 0xF0)
2233 return CCID_DRIVER_ERR_UI_TIMEOUT;
2236 /* Check whether a card is at all available. Note: If you add new
2237 error codes here, check whether they need to be ignored in
2239 switch ((buffer[7] & 0x03))
2241 case 0: /* no error */ break;
2242 case 1: rc = CCID_DRIVER_ERR_CARD_INACTIVE; break;
2243 case 2: rc = CCID_DRIVER_ERR_NO_CARD; break;
2244 case 3: /* RFU */ break;
2250 * Communication failure by device side.
2251 * Possibly, it was forcibly suspended and resumed.
2253 if (handle->ep_intr < 0)
2255 DEBUGOUT ("CCID: card inactive/removed\n");
2256 handle->powered_off = 1;
2259 #if defined(GNUPG_MAJOR_VERSION)
2260 scd_kick_the_loop ();
2269 /* Send an abort sequence and wait until everything settled. */
2271 abort_cmd (ccid_driver_t handle, int seqno, int init)
2274 unsigned char dummybuf[8];
2275 unsigned char msg[100];
2279 DEBUGOUT_1 ("sending abort sequence for seqno %d\n", seqno);
2280 /* Send the abort command to the control pipe. Note that we don't
2281 need to keep track of sent abort commands because there should
2282 never be another thread using the same slot concurrently. */
2286 rc = libusb_control_transfer (handle->idev,
2287 0x21,/* bmRequestType: host-to-device,
2288 class specific, to interface. */
2290 (seqno << 8 | 0 /* slot */),
2293 1000 /* ms timeout */);
2299 DEBUGOUT_1 ("usb_control_msg error: %s\n", libusb_error_name (rc));
2301 return map_libusb_error (rc);
2304 /* Now send the abort command to the bulk out pipe using the same
2305 SEQNO and SLOT. Do this in a loop to so that all seqno are
2307 seqno--; /* Adjust for next increment. */
2313 msg[0] = PC_to_RDR_Abort;
2314 msg[5] = 0; /* slot */
2316 msg[7] = 0; /* RFU */
2317 msg[8] = 0; /* RFU */
2318 msg[9] = 0; /* RFU */
2320 set_msg_len (msg, 0);
2325 rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_out,
2326 msg, msglen, &transferred,
2327 init? 100: 5000 /* ms timeout */);
2331 if (rc == 0 && transferred == msglen)
2334 DEBUGOUT_1 ("usb_bulk_write error in abort_cmd: %s\n",
2335 libusb_error_name (rc));
2338 return map_libusb_error (rc);
2343 rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_in,
2344 msg, sizeof msg, &msglen,
2345 init? 100: 5000 /*ms timeout*/);
2351 DEBUGOUT_1 ("usb_bulk_read error in abort_cmd: %s\n",
2352 libusb_error_name (rc));
2353 if (init && rc == LIBUSB_ERROR_TIMEOUT)
2356 return map_libusb_error (rc);
2361 DEBUGOUT_1 ("bulk-in msg in abort_cmd too short (%u)\n",
2362 (unsigned int)msglen);
2363 return CCID_DRIVER_ERR_INV_VALUE;
2367 DEBUGOUT_1 ("unexpected bulk-in slot (%d) in abort_cmd\n", msg[5]);
2368 return CCID_DRIVER_ERR_INV_VALUE;
2371 DEBUGOUT_3 ("status: %02X error: %02X octet[9]: %02X\n",
2372 msg[7], msg[8], msg[9]);
2373 if (CCID_COMMAND_FAILED (msg))
2374 print_command_failed (msg);
2376 while (rc == LIBUSB_ERROR_TIMEOUT
2377 || (msg[0] != RDR_to_PC_SlotStatus && msg[5] != 0 && msg[6] != seqno));
2379 handle->seqno = ((seqno + 1) & 0xff);
2380 DEBUGOUT ("sending abort sequence succeeded\n");
2386 /* Note that this function won't return the error codes NO_CARD or
2387 CARD_INACTIVE. IF RESULT is not NULL, the result from the
2388 operation will get returned in RESULT and its length in RESULTLEN.
2389 If the response is larger than RESULTMAX, an error is returned and
2390 the required buffer length returned in RESULTLEN. */
2392 send_escape_cmd (ccid_driver_t handle,
2393 const unsigned char *data, size_t datalen,
2394 unsigned char *result, size_t resultmax, size_t *resultlen)
2397 unsigned char msg[100];
2399 unsigned char seqno;
2404 if (datalen > sizeof msg - 10)
2405 return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large. */
2407 msg[0] = PC_to_RDR_Escape;
2408 msg[5] = 0; /* slot */
2409 msg[6] = seqno = handle->seqno++;
2410 msg[7] = 0; /* RFU */
2411 msg[8] = 0; /* RFU */
2412 msg[9] = 0; /* RFU */
2413 memcpy (msg+10, data, datalen);
2414 msglen = 10 + datalen;
2415 set_msg_len (msg, datalen);
2417 rc = bulk_out (handle, msg, msglen, 0);
2420 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape,
2425 /* We need to ignore certain errorcode here. */
2427 case CCID_DRIVER_ERR_CARD_INACTIVE:
2428 case CCID_DRIVER_ERR_NO_CARD:
2430 if (msglen > resultmax)
2431 rc = CCID_DRIVER_ERR_INV_VALUE; /* Response too large. */
2434 memcpy (result, msg, msglen);
2436 *resultlen = msglen;
2450 ccid_transceive_escape (ccid_driver_t handle,
2451 const unsigned char *data, size_t datalen,
2452 unsigned char *resp, size_t maxresplen, size_t *nresp)
2454 return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp);
2461 ccid_poll (ccid_driver_t handle)
2464 unsigned char msg[10];
2468 rc = libusb_interrupt_transfer (handle->idev, handle->ep_intr,
2469 msg, sizeof msg, &msglen,
2470 0 /* ms timeout */ );
2471 if (rc == LIBUSB_ERROR_TIMEOUT)
2476 DEBUGOUT_1 ("usb_intr_read error: %s\n", libusb_error_name (rc));
2477 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2482 DEBUGOUT ("intr-in msg too short\n");
2483 return CCID_DRIVER_ERR_INV_VALUE;
2486 if (msg[0] == RDR_to_PC_NotifySlotChange)
2488 DEBUGOUT ("notify slot change:");
2489 for (i=1; i < msglen; i++)
2490 for (j=0; j < 4; j++)
2491 DEBUGOUT_CONT_3 (" %d:%c%c",
2493 (msg[i] & (1<<(j*2)))? 'p':'-',
2494 (msg[i] & (2<<(j*2)))? '*':' ');
2497 else if (msg[0] == RDR_to_PC_HardwareError)
2499 DEBUGOUT ("hardware error occurred\n");
2503 DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]);
2510 /* Note that this function won't return the error codes NO_CARD or
2513 ccid_slot_status (ccid_driver_t handle, int *statusbits, int on_wire)
2516 unsigned char msg[100];
2518 unsigned char seqno;
2521 if (handle->powered_off)
2522 return CCID_DRIVER_ERR_NO_READER;
2524 /* If the card (with its lower-level driver) doesn't require
2525 GET_STATUS on wire (because it supports INTERRUPT transfer for
2526 status change, or it's a token which has a card always inserted),
2527 no need to send on wire. */
2528 if (!on_wire && !ccid_require_get_status (handle))
2530 /* Setup interrupt transfer at the initial call of slot_status
2531 with ON_WIRE == 0 */
2532 if (handle->transfer == NULL)
2533 ccid_setup_intr (handle);
2540 msg[0] = PC_to_RDR_GetSlotStatus;
2541 msg[5] = 0; /* slot */
2542 msg[6] = seqno = handle->seqno++;
2543 msg[7] = 0; /* RFU */
2544 msg[8] = 0; /* RFU */
2545 msg[9] = 0; /* RFU */
2546 set_msg_len (msg, 0);
2548 rc = bulk_out (handle, msg, 10, 1);
2551 /* Note that we set the NO_DEBUG flag here, so that the logs won't
2552 get cluttered up by a ticker function checking for the slot
2553 status and debugging enabled. */
2554 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
2555 seqno, retries? 1000 : 200, 1);
2556 if ((rc == CCID_DRIVER_ERR_CARD_IO_ERROR || rc == CCID_DRIVER_ERR_USB_TIMEOUT)
2561 DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n");
2565 libusb_clear_halt (handle->idev, handle->ep_bulk_in);
2566 libusb_clear_halt (handle->idev, handle->ep_bulk_out);
2572 DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n");
2576 if (rc && rc != CCID_DRIVER_ERR_NO_CARD && rc != CCID_DRIVER_ERR_CARD_INACTIVE)
2578 *statusbits = (msg[7] & 3);
2584 /* Parse ATR string (of ATRLEN) and update parameters at PARAM.
2585 Calling this routine, it should prepare default values at PARAM
2586 beforehand. This routine assumes that card is accessed by T=1
2587 protocol. It doesn't analyze historical bytes at all.
2589 Returns < 0 value on error:
2590 -1 for parse error or integrity check error
2591 -2 for card doesn't support T=1 protocol
2592 -3 for parameters are nod explicitly defined by ATR
2593 -4 for this driver doesn't support CRC
2595 Returns >= 0 on success:
2596 0 for card is negotiable mode
2597 1 for card is specific mode (and not negotiable)
2600 update_param_by_atr (unsigned char *param, unsigned char *atr, size_t atrlen)
2604 int historical_bytes_num, negotiable = 1;
2606 #define NEXTBYTE() do { i++; if (atrlen <= i) return -1; } while (0)
2611 param[1] |= 0x02; /* Convention is inverse. */
2615 historical_bytes_num = atr[i] & 0x0f;
2620 param[0] = atr[i]; /* TA1 - Fi & Di */
2625 NEXTBYTE (); /* TB1 - ignore */
2629 param[2] = atr[i]; /* TC1 - Guard Time */
2635 y = (atr[i] >> 4); /* TD1 */
2640 { /* TA2 - PPS mode */
2641 if ((atr[i] & 0x0f) != 1)
2642 return -2; /* Wrong card protocol (!= 1). */
2644 if ((atr[i] & 0x10) != 0x10)
2645 return -3; /* Transmission parameters are implicitly defined. */
2647 negotiable = 0; /* TA2 means specific mode. */
2652 NEXTBYTE (); /* TB2 - ignore */
2655 NEXTBYTE (); /* TC2 - ignore */
2659 y = (atr[i] >> 4); /* TD2 */
2671 param[5] = atr[i]; /* IFSC */
2673 /* XXX: check voltage? */
2674 param[4] = (atr[i] >> 6); /* ClockStop */
2682 param[3] = atr[i]; /* TBx - BWI & CWI */
2689 param[1] |= (atr[i] & 0x01); /* TCx - LRC/CRC */
2692 if (param[1] & 0x01)
2693 return -4; /* CRC not supported yet. */
2698 y = (atr[i] >> 4); /* TDx */
2707 i += historical_bytes_num - 1;
2729 /* Return the ATR of the card. This is not a cached value and thus an
2730 actual reset is done. */
2732 ccid_get_atr (ccid_driver_t handle,
2733 unsigned char *atr, size_t maxatrlen, size_t *atrlen)
2737 unsigned char msg[100];
2738 unsigned char *tpdu;
2739 size_t msglen, tpdulen;
2740 unsigned char seqno;
2745 unsigned char param[7] = { /* For Protocol T=1 */
2746 0x11, /* bmFindexDindex */
2747 0x10, /* bmTCCKST1 */
2748 0x00, /* bGuardTimeT1 */
2749 0x4d, /* bmWaitingIntegersT1 */
2750 0x00, /* bClockStop */
2752 0x00 /* bNadValue */
2755 /* First check whether a card is available. */
2756 rc = ccid_slot_status (handle, &statusbits, 1);
2759 if (statusbits == 2)
2760 return CCID_DRIVER_ERR_NO_CARD;
2763 * In the first invocation of ccid_slot_status, card reader may
2764 * return CCID_DRIVER_ERR_CARD_INACTIVE and handle->powered_off may
2765 * become 1. Because inactive card is no problem (we are turning it
2766 * ON here), clear the flag.
2768 handle->powered_off = 0;
2770 /* For an inactive and also for an active card, issue the PowerOn
2771 command to get the ATR. */
2773 msg[0] = PC_to_RDR_IccPowerOn;
2774 msg[5] = 0; /* slot */
2775 msg[6] = seqno = handle->seqno++;
2776 /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */
2777 msg[7] = handle->auto_voltage ? 0 : 1;
2778 msg[8] = 0; /* RFU */
2779 msg[9] = 0; /* RFU */
2780 set_msg_len (msg, 0);
2783 rc = bulk_out (handle, msg, msglen, 0);
2786 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2790 if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb
2791 && ((handle->id_vendor == VENDOR_CHERRY
2792 && handle->id_product == 0x0005)
2793 || (handle->id_vendor == VENDOR_GEMPC
2794 && handle->id_product == 0x4433)
2798 /* Try switching to ISO mode. */
2799 if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2,
2803 else if (statusbits == 0 && CCID_COMMAND_FAILED (msg))
2805 /* Card was active already, and something went wrong with
2806 PC_to_RDR_IccPowerOn command. It may be baud-rate mismatch
2807 between the card and the reader. To recover from this state,
2808 send PC_to_RDR_IccPowerOff command to reset the card and try
2811 rc = send_power_off (handle);
2818 else if (CCID_COMMAND_FAILED (msg))
2819 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2822 handle->powered_off = 0;
2826 size_t n = msglen - 10;
2830 memcpy (atr, msg+10, n);
2834 param[6] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2835 rc = update_param_by_atr (param, msg+10, msglen - 10);
2838 DEBUGOUT_1 ("update_param_by_atr failed: %d\n", rc);
2839 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2844 if (handle->auto_param)
2846 msg[0] = PC_to_RDR_GetParameters;
2847 msg[5] = 0; /* slot */
2848 msg[6] = seqno = handle->seqno++;
2849 msg[7] = 0; /* RFU */
2850 msg[8] = 0; /* RFU */
2851 msg[9] = 0; /* RFU */
2852 set_msg_len (msg, 0);
2854 rc = bulk_out (handle, msg, msglen, 0);
2856 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2859 DEBUGOUT ("GetParameters failed\n");
2860 else if (msglen == 17 && msg[9] == 1)
2863 else if (handle->auto_pps)
2865 else if (rc == 1) /* It's negotiable, send PPS. */
2867 msg[0] = PC_to_RDR_XfrBlock;
2868 msg[5] = 0; /* slot */
2869 msg[6] = seqno = handle->seqno++;
2873 msg[10] = 0xff; /* PPSS */
2874 msg[11] = 0x11; /* PPS0: PPS1, Protocol T=1 */
2875 msg[12] = param[0]; /* PPS1: Fi / Di */
2876 msg[13] = 0xff ^ 0x11 ^ param[0]; /* PCK */
2877 set_msg_len (msg, 4);
2880 rc = bulk_out (handle, msg, msglen, 0);
2884 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2889 if (msglen != 10 + 4)
2891 DEBUGOUT_1 ("Setting PPS failed: %zu\n", msglen);
2892 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2895 if (msg[10] != 0xff || msg[11] != 0x11 || msg[12] != param[0])
2897 DEBUGOUT_1 ("Setting PPS failed: 0x%02x\n", param[0]);
2898 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2902 /* Setup parameters to select T=1. */
2903 msg[0] = PC_to_RDR_SetParameters;
2904 msg[5] = 0; /* slot */
2905 msg[6] = seqno = handle->seqno++;
2906 msg[7] = 1; /* Select T=1. */
2907 msg[8] = 0; /* RFU */
2908 msg[9] = 0; /* RFU */
2911 memcpy (&msg[10], param, 7);
2912 set_msg_len (msg, 7);
2915 rc = bulk_out (handle, msg, msglen, 0);
2918 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2921 DEBUGOUT ("SetParameters failed (ignored)\n");
2923 if (!rc && msglen > 15 && msg[15] >= 16 && msg[15] <= 254 )
2924 handle->ifsc = msg[15];
2926 handle->ifsc = 128; /* Something went wrong, assume 128 bytes. */
2928 if (handle->nonnull_nad && msglen > 16 && msg[16] == 0)
2930 DEBUGOUT ("Use Null-NAD, clearing handle->nonnull_nad.\n");
2931 handle->nonnull_nad = 0;
2937 /* Send an S-Block with our maximum IFSD to the CCID. */
2938 if (!handle->apdu_level && !handle->auto_ifsd)
2941 /* NAD: DAD=1, SAD=0 */
2942 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2943 tpdu[1] = (0xc0 | 0 | 1); /* S-block request: change IFSD */
2945 tpdu[3] = handle->max_ifsd? handle->max_ifsd : 32;
2947 edc = compute_edc (tpdu, tpdulen, use_crc);
2949 tpdu[tpdulen++] = (edc >> 8);
2950 tpdu[tpdulen++] = edc;
2952 msg[0] = PC_to_RDR_XfrBlock;
2953 msg[5] = 0; /* slot */
2954 msg[6] = seqno = handle->seqno++;
2956 msg[8] = 0; /* RFU */
2957 msg[9] = 0; /* RFU */
2958 set_msg_len (msg, tpdulen);
2959 msglen = 10 + tpdulen;
2961 if (debug_level > 1)
2962 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
2963 ((msg[11] & 0xc0) == 0x80)? 'R' :
2964 (msg[11] & 0x80)? 'S' : 'I',
2965 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2966 : !!(msg[11] & 0x40)),
2967 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2969 rc = bulk_out (handle, msg, msglen, 0);
2974 rc = bulk_in (handle, msg, sizeof msg, &msglen,
2975 RDR_to_PC_DataBlock, seqno, 5000, 0);
2980 tpdulen = msglen - 10;
2983 return CCID_DRIVER_ERR_ABORTED;
2985 if (debug_level > 1)
2986 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2987 ((msg[11] & 0xc0) == 0x80)? 'R' :
2988 (msg[11] & 0x80)? 'S' : 'I',
2989 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2990 : !!(msg[11] & 0x40)),
2991 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2992 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2994 if ((tpdu[1] & 0xe0) != 0xe0 || tpdu[2] != 1)
2996 DEBUGOUT ("invalid response for S-block (Change-IFSD)\n");
2999 DEBUGOUT_1 ("IFSD has been set to %d\n", tpdu[3]);
3002 ccid_vendor_specific_setup (handle);
3010 compute_edc (const unsigned char *data, size_t datalen, int use_crc)
3014 return 0x42; /* Not yet implemented. */
3018 unsigned char crc = 0;
3020 for (; datalen; datalen--)
3027 /* Return true if APDU is an extended length one. */
3029 is_exlen_apdu (const unsigned char *apdu, size_t apdulen)
3031 if (apdulen < 7 || apdu[4])
3032 return 0; /* Too short or no Z byte. */
3037 /* Helper for ccid_transceive used for APDU level exchanges. */
3039 ccid_transceive_apdu_level (ccid_driver_t handle,
3040 const unsigned char *apdu_buf, size_t apdu_len,
3041 unsigned char *resp, size_t maxresplen,
3045 unsigned char msg[CCID_MAX_BUF];
3046 const unsigned char *apdu_p;
3047 size_t apdu_part_len;
3049 unsigned char seqno;
3051 unsigned char chain = 0;
3053 if (apdu_len == 0 || apdu_len > sizeof (msg) - 10)
3054 return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
3059 apdu_part_len = apdu_len;
3060 if (apdu_part_len > handle->max_ccid_msglen - 10)
3062 apdu_part_len = handle->max_ccid_msglen - 10;
3066 msg[0] = PC_to_RDR_XfrBlock;
3067 msg[5] = 0; /* slot */
3068 msg[6] = seqno = handle->seqno++;
3072 memcpy (msg+10, apdu_p, apdu_part_len);
3073 set_msg_len (msg, apdu_part_len);
3074 msglen = 10 + apdu_part_len;
3076 rc = bulk_out (handle, msg, msglen, 0);
3080 apdu_p += apdu_part_len;
3081 apdu_len -= apdu_part_len;
3083 rc = bulk_in (handle, msg, sizeof msg, &msglen,
3084 RDR_to_PC_DataBlock, seqno, CCID_CMD_TIMEOUT, 0);
3088 if (!(chain & 0x01))
3097 apdu_part_len = msglen - 10;
3098 if (resp && apdu_len + apdu_part_len <= maxresplen)
3099 memcpy (resp + apdu_len, msg+10, apdu_part_len);
3100 apdu_len += apdu_part_len;
3102 if (!(msg[9] & 0x01))
3105 msg[0] = PC_to_RDR_XfrBlock;
3106 msg[5] = 0; /* slot */
3107 msg[6] = seqno = handle->seqno++;
3109 msg[8] = 0x10; /* Request next data block */
3111 set_msg_len (msg, 0);
3114 rc = bulk_out (handle, msg, msglen, 0);
3118 rc = bulk_in (handle, msg, sizeof msg, &msglen,
3119 RDR_to_PC_DataBlock, seqno, CCID_CMD_TIMEOUT, 0);
3126 if (apdu_len > maxresplen)
3128 DEBUGOUT_2 ("provided buffer too short for received data "
3130 (unsigned int)apdu_len, (unsigned int)maxresplen);
3131 return CCID_DRIVER_ERR_INV_VALUE;
3143 Protocol T=1 overview
3147 1 byte Node Address (NAD)
3148 1 byte Protocol Control Byte (PCB)
3151 0-254 byte APDU or Control Information (INF)
3153 1 byte Error Detection Code (EDC)
3157 bit 4..6 Destination Node Address (DAD)
3159 bit 2..0 Source Node Address (SAD)
3161 If node addresses are not used, SAD and DAD should be set to 0 on
3162 the first block sent to the card. If they are used they should
3163 have different values (0 for one is okay); that first block sets up
3164 the addresses of the nodes.
3167 Information Block (I-Block):
3169 bit 6 Sequence number (yep, that is modulo 2)
3172 Received-Ready Block (R-Block):
3176 bit 4 Sequence number
3177 bit 3..0 0 = no error
3178 1 = EDC or parity error
3180 other values are reserved
3181 Supervisory Block (S-Block):
3184 bit 5 clear=request,set=response
3185 bit 4..0 0 = resynchronization request
3186 1 = information field size request
3188 3 = extension of BWT request
3190 other values are reserved
3195 ccid_transceive (ccid_driver_t handle,
3196 const unsigned char *apdu_buf, size_t apdu_buflen,
3197 unsigned char *resp, size_t maxresplen, size_t *nresp)
3200 /* The size of the buffer used to be 10+259. For the via_escape
3201 hack we need one extra byte, thus 11+259. */
3202 unsigned char send_buffer[11+259], recv_buffer[11+259];
3203 const unsigned char *apdu;
3205 unsigned char *msg, *tpdu, *p;
3206 size_t msglen, tpdulen, last_tpdulen, n;
3207 unsigned char seqno;
3221 nresp = &dummy_nresp;
3224 /* Smarter readers allow sending APDUs directly; divert here. */
3225 if (handle->apdu_level)
3227 /* We employ a hack for Omnikey readers which are able to send
3228 TPDUs using an escape sequence. There is no documentation
3229 but the Windows driver does it this way. Tested using a
3230 CM6121. This method works also for the Cherry XX44
3231 keyboards; however there are problems with the
3232 ccid_transceive_secure which leads to a loss of sync on the
3233 CCID level. If Cherry wants to make their keyboard work
3234 again, they should hand over some docs. */
3235 if ((handle->id_vendor == VENDOR_OMNIKEY)
3236 && handle->apdu_level < 2
3237 && is_exlen_apdu (apdu_buf, apdu_buflen))
3240 return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen,
3241 resp, maxresplen, nresp);
3244 /* The other readers we support require sending TPDUs. */
3246 tpdulen = 0; /* Avoid compiler warning about no initialization. */
3248 hdrlen = via_escape? 11 : 10;
3250 /* NAD: DAD=1, SAD=0 */
3251 nad_byte = handle->nonnull_nad? ((1 << 4) | 0): 0;
3255 last_tpdulen = 0; /* Avoid gcc warning (controlled by RESYNCING). */
3263 apdulen = apdu_buflen;
3264 log_assert (apdulen);
3266 /* Construct an I-Block. */
3267 tpdu = msg + hdrlen;
3269 tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */
3270 if (apdulen > handle->ifsc )
3272 apdulen = handle->ifsc;
3273 apdu_buf += handle->ifsc;
3274 apdu_buflen -= handle->ifsc;
3275 tpdu[1] |= (1 << 5); /* Set more bit. */
3278 memcpy (tpdu+3, apdu, apdulen);
3279 tpdulen = 3 + apdulen;
3280 edc = compute_edc (tpdu, tpdulen, use_crc);
3282 tpdu[tpdulen++] = (edc >> 8);
3283 tpdu[tpdulen++] = edc;
3288 msg[0] = PC_to_RDR_Escape;
3289 msg[5] = 0; /* slot */
3290 msg[6] = seqno = handle->seqno++;
3291 msg[7] = 0; /* RFU */
3292 msg[8] = 0; /* RFU */
3293 msg[9] = 0; /* RFU */
3294 msg[10] = 0x1a; /* Omnikey command to send a TPDU. */
3295 set_msg_len (msg, 1 + tpdulen);
3299 msg[0] = PC_to_RDR_XfrBlock;
3300 msg[5] = 0; /* slot */
3301 msg[6] = seqno = handle->seqno++;
3302 msg[7] = wait_more; /* bBWI */
3303 msg[8] = 0; /* RFU */
3304 msg[9] = 0; /* RFU */
3305 set_msg_len (msg, tpdulen);
3307 msglen = hdrlen + tpdulen;
3309 last_tpdulen = tpdulen;
3312 if (debug_level > 1)
3313 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
3314 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
3315 (msg[pcboff] & 0x80)? 'S' : 'I',
3316 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
3317 : !!(msg[pcboff] & 0x40)),
3318 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
3321 rc = bulk_out (handle, msg, msglen, 0);
3326 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3327 via_escape? RDR_to_PC_Escape : RDR_to_PC_DataBlock, seqno,
3328 (wait_more ? wait_more : 1) * CCID_CMD_TIMEOUT, 0);
3332 tpdu = msg + hdrlen;
3333 tpdulen = msglen - hdrlen;
3341 libusb_clear_halt (handle->idev, handle->ep_bulk_in);
3345 return CCID_DRIVER_ERR_ABORTED;
3348 if (debug_level > 1)
3349 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3350 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
3351 (msg[pcboff] & 0x80)? 'S' : 'I',
3352 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
3353 : !!(msg[pcboff] & 0x40)),
3354 ((msg[pcboff] & 0xc0) == 0x80)? (msg[pcboff] & 0x0f) : 0,
3355 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
3359 if (!(tpdu[1] & 0x80))
3360 { /* This is an I-block. */
3363 { /* last block sent was successful. */
3368 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3369 { /* Response does not match our sequence number. */
3371 tpdu = msg + hdrlen;
3373 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */
3376 edc = compute_edc (tpdu, tpdulen, use_crc);
3378 tpdu[tpdulen++] = (edc >> 8);
3379 tpdu[tpdulen++] = edc;
3386 p = tpdu + 3; /* Skip the prologue field. */
3387 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3388 /* fixme: verify the checksum. */
3393 DEBUGOUT_2 ("provided buffer too short for received data "
3395 (unsigned int)n, (unsigned int)maxresplen);
3396 return CCID_DRIVER_ERR_INV_VALUE;
3399 memcpy (resp, p, n);
3405 if (!(tpdu[1] & 0x20))
3406 return 0; /* No chaining requested - ready. */
3409 tpdu = msg + hdrlen;
3411 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */
3414 edc = compute_edc (tpdu, tpdulen, use_crc);
3416 tpdu[tpdulen++] = (edc >> 8);
3417 tpdu[tpdulen++] = edc;
3419 else if ((tpdu[1] & 0xc0) == 0x80)
3420 { /* This is a R-block. */
3421 if ( (tpdu[1] & 0x0f))
3424 if (via_escape && retries == 1 && (msg[pcboff] & 0x0f))
3426 /* Error probably due to switching to TPDU. Send a
3427 resync request. We use the recv_buffer so that
3428 we don't corrupt the send_buffer. */
3430 tpdu = msg + hdrlen;
3432 tpdu[1] = 0xc0; /* S-block resync request. */
3435 edc = compute_edc (tpdu, tpdulen, use_crc);
3437 tpdu[tpdulen++] = (edc >> 8);
3438 tpdu[tpdulen++] = edc;
3440 DEBUGOUT ("T=1: requesting resync\n");
3442 else if (retries > 3)
3444 DEBUGOUT ("T=1: 3 failed retries\n");
3445 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3449 /* Error: repeat last block */
3451 tpdulen = last_tpdulen;
3454 else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns)
3455 { /* Response does not match our sequence number. */
3456 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3457 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3460 { /* Send next chunk. */
3468 DEBUGOUT ("unexpected ACK R-block received\n");
3469 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3473 { /* This is a S-block. */
3475 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d\n",
3476 (tpdu[1] & 0x20)? "response": "request",
3478 if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 1 && tpdu[2] == 1)
3480 /* Information field size request. */
3481 unsigned char ifsc = tpdu[3];
3483 if (ifsc < 16 || ifsc > 254)
3484 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3487 tpdu = msg + hdrlen;
3489 tpdu[1] = (0xc0 | 0x20 | 1); /* S-block response */
3493 edc = compute_edc (tpdu, tpdulen, use_crc);
3495 tpdu[tpdulen++] = (edc >> 8);
3496 tpdu[tpdulen++] = edc;
3497 DEBUGOUT_1 ("T=1: requesting an ifsc=%d\n", ifsc);
3499 else if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2])
3501 /* Wait time extension request. */
3502 unsigned char bwi = tpdu[3];
3507 tpdu = msg + hdrlen;
3509 tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */
3513 edc = compute_edc (tpdu, tpdulen, use_crc);
3515 tpdu[tpdulen++] = (edc >> 8);
3516 tpdu[tpdulen++] = edc;
3517 DEBUGOUT_1 ("T=1: waittime extension of bwi=%d\n", bwi);
3518 print_progress (handle);
3520 else if ( (tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 0 && !tpdu[2])
3522 DEBUGOUT ("T=1: resync ack from reader\n");
3523 /* Repeat previous block. */
3525 tpdulen = last_tpdulen;
3528 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3530 } /* end T=1 protocol loop. */
3536 /* Send the CCID Secure command to the reader. APDU_BUF should
3537 contain the APDU template. PIN_MODE defines how the pin gets
3540 1 := The PIN is ASCII encoded and of variable length. The
3541 length of the PIN entered will be put into Lc by the reader.
3542 The APDU should me made up of 4 bytes without Lc.
3544 PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0
3545 may be used t enable reasonable defaults.
3547 When called with RESP and NRESP set to NULL, the function will
3548 merely check whether the reader supports the secure command for the
3549 given APDU and PIN_MODE. */
3551 ccid_transceive_secure (ccid_driver_t handle,
3552 const unsigned char *apdu_buf, size_t apdu_buflen,
3554 unsigned char *resp, size_t maxresplen, size_t *nresp)
3557 unsigned char send_buffer[10+259], recv_buffer[10+259];
3558 unsigned char *msg, *tpdu, *p;
3559 size_t msglen, tpdulen, n;
3560 unsigned char seqno;
3563 int cherry_mode = 0;
3565 int enable_varlen = 0;
3567 testmode = !resp && !nresp;
3570 nresp = &dummy_nresp;
3573 if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1))
3575 else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2))
3578 return CCID_DRIVER_ERR_NO_PINPAD;
3580 if (!pininfo->minlen)
3581 pininfo->minlen = 1;
3582 if (!pininfo->maxlen)
3583 pininfo->maxlen = 15;
3585 /* Note that the 25 is the maximum value the SPR532 allows. */
3586 if (pininfo->minlen < 1 || pininfo->minlen > 25
3587 || pininfo->maxlen < 1 || pininfo->maxlen > 25
3588 || pininfo->minlen > pininfo->maxlen)
3589 return CCID_DRIVER_ERR_INV_VALUE;
3591 /* We have only tested a few readers so better don't risk anything
3592 and do not allow the use with other readers. */
3593 switch (handle->id_vendor)
3595 case VENDOR_SCM: /* Tested with SPR 532. */
3596 case VENDOR_KAAN: /* Tested with KAAN Advanced (1.02). */
3597 case VENDOR_FSIJ: /* Tested with Gnuk (0.21). */
3598 pininfo->maxlen = 25;
3601 case VENDOR_REINER:/* Tested with cyberJack go */
3602 case VENDOR_VASCO: /* Tested with DIGIPASS 920 */
3606 pininfo->maxlen = 15;
3608 /* The CHERRY XX44 keyboard echos an asterisk for each entered
3609 character on the keyboard channel. We use a special variant
3610 of PC_to_RDR_Secure which directs these characters to the
3611 smart card's bulk-in channel. We also need to append a zero
3612 Lc byte to the APDU. It seems that it will be replaced with
3613 the actual length instead of being appended before the APDU
3614 is send to the card. */
3616 if (handle->id_product != CHERRY_ST2000)
3620 if (handle->id_product == CRYPTOUCAN)
3622 pininfo->maxlen = 25;
3626 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3628 if (handle->id_product == GEMPC_PINPAD)
3631 pininfo->minlen = 4;
3632 pininfo->maxlen = 8;
3635 else if (handle->id_product == GEMPC_EZIO)
3637 pininfo->maxlen = 25;
3641 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3643 if ((handle->id_vendor == VENDOR_VEGA &&
3644 handle->id_product == VEGA_ALPHA))
3647 pininfo->minlen = 4;
3648 pininfo->maxlen = 8;
3651 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3655 pininfo->fixedlen = 0;
3658 return 0; /* Success */
3660 if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
3661 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3663 ccid_vendor_specific_pinpad_setup (handle);
3666 msg[0] = cherry_mode? 0x89 : PC_to_RDR_Secure;
3667 msg[5] = 0; /* slot */
3668 msg[6] = seqno = handle->seqno++;
3669 msg[7] = 0; /* bBWI */
3670 msg[8] = 0; /* RFU */
3671 msg[9] = 0; /* RFU */
3672 msg[10] = apdu_buf[1] == 0x20 ? 0 : 1;
3673 /* Perform PIN verification or PIN modification. */
3674 msg[11] = 0; /* Timeout in seconds. */
3675 msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
3676 if (handle->id_vendor == VENDOR_SCM)
3678 /* For the SPR532 the next 2 bytes need to be zero. We do this
3679 for all SCM products. Kudos to Martin Paljak for this
3681 msg[13] = msg[14] = 0;
3685 msg[13] = pininfo->fixedlen; /* bmPINBlockString:
3686 0 bits of pin length to insert.
3687 PIN block size by fixedlen. */
3688 msg[14] = 0x00; /* bmPINLengthFormat:
3689 Units are bytes, position is 0. */
3693 if (apdu_buf[1] == 0x24)
3695 msg[msglen++] = 0; /* bInsertionOffsetOld */
3696 msg[msglen++] = pininfo->fixedlen; /* bInsertionOffsetNew */
3699 /* The following is a little endian word. */
3700 msg[msglen++] = pininfo->maxlen; /* wPINMaxExtraDigit-Maximum. */
3701 msg[msglen++] = pininfo->minlen; /* wPINMaxExtraDigit-Minimum. */
3703 if (apdu_buf[1] == 0x24)
3704 msg[msglen++] = apdu_buf[2] == 0 ? 0x03 : 0x01;
3706 * 0x00: new PIN once
3707 * 0x01: new PIN twice (confirmation)
3708 * 0x02: old PIN and new PIN once
3709 * 0x03: old PIN and new PIN twice (confirmation)
3712 msg[msglen] = 0x02; /* bEntryValidationCondition:
3713 Validation key pressed */
3714 if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
3715 msg[msglen] |= 0x01; /* Max size reached. */
3718 if (apdu_buf[1] == 0x20)
3719 msg[msglen++] = 0x01; /* bNumberMessage. */
3721 msg[msglen++] = 0x03; /* bNumberMessage. */
3723 msg[msglen++] = 0x09; /* wLangId-Low: English FIXME: use the first entry. */
3724 msg[msglen++] = 0x04; /* wLangId-High. */
3726 if (apdu_buf[1] == 0x20)
3727 msg[msglen++] = 0; /* bMsgIndex. */
3730 msg[msglen++] = 0; /* bMsgIndex1. */
3731 msg[msglen++] = 1; /* bMsgIndex2. */
3732 msg[msglen++] = 2; /* bMsgIndex3. */
3736 n = pininfo->fixedlen;
3737 if (apdu_buf[1] == 0x24)
3738 n += pininfo->fixedlen;
3740 /* bTeoProlog follows: */
3741 msg[msglen++] = handle->nonnull_nad? ((1 << 4) | 0): 0;
3742 msg[msglen++] = ((handle->t1_ns & 1) << 6); /* I-block */
3744 msg[msglen++] = n + 5; /* apdulen should be filled for fixed length. */
3746 msg[msglen++] = 0; /* The apdulen will be filled in by the reader. */
3748 msg[msglen++] = apdu_buf[0]; /* CLA */
3749 msg[msglen++] = apdu_buf[1]; /* INS */
3750 msg[msglen++] = apdu_buf[2]; /* P1 */
3751 msg[msglen++] = apdu_buf[3]; /* P2 */
3754 else if (pininfo->fixedlen != 0)
3757 memset (&msg[msglen], 0xff, n);
3760 /* An EDC is not required. */
3761 set_msg_len (msg, msglen - 10);
3763 rc = bulk_out (handle, msg, msglen, 0);
3768 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3769 RDR_to_PC_DataBlock, seqno, 30000, 0);
3774 tpdulen = msglen - 10;
3776 if (handle->apdu_level)
3780 if (tpdulen > maxresplen)
3782 DEBUGOUT_2 ("provided buffer too short for received data "
3784 (unsigned int)tpdulen, (unsigned int)maxresplen);
3785 return CCID_DRIVER_ERR_INV_VALUE;
3788 memcpy (resp, tpdu, tpdulen);
3799 libusb_clear_halt (handle->idev, handle->ep_bulk_in);
3803 return CCID_DRIVER_ERR_ABORTED;
3805 if (debug_level > 1)
3806 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3807 ((msg[11] & 0xc0) == 0x80)? 'R' :
3808 (msg[11] & 0x80)? 'S' : 'I',
3809 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
3810 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
3811 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
3813 if (!(tpdu[1] & 0x80))
3814 { /* This is an I-block. */
3815 /* Last block sent was successful. */
3818 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3819 { /* Response does not match our sequence number. */
3820 DEBUGOUT ("I-block with wrong seqno received\n");
3821 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3826 p = tpdu + 3; /* Skip the prologue field. */
3827 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3828 /* fixme: verify the checksum. */
3833 DEBUGOUT_2 ("provided buffer too short for received data "
3835 (unsigned int)n, (unsigned int)maxresplen);
3836 return CCID_DRIVER_ERR_INV_VALUE;
3839 memcpy (resp, p, n);
3843 if (!(tpdu[1] & 0x20))
3844 return 0; /* No chaining requested - ready. */
3846 DEBUGOUT ("chaining requested but not supported for Secure operation\n");
3847 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3849 else if ((tpdu[1] & 0xc0) == 0x80)
3850 { /* This is a R-block. */
3851 if ( (tpdu[1] & 0x0f))
3852 { /* Error: repeat last block */
3853 DEBUGOUT ("No retries supported for Secure operation\n");
3854 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3856 else if (!!(tpdu[1] & 0x10) == handle->t1_ns)
3857 { /* Response does not match our sequence number. */
3858 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3859 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3862 { /* Send next chunk. */
3863 DEBUGOUT ("chaining not supported on Secure operation\n");
3864 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3868 { /* This is a S-block. */
3869 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d for Secure operation\n",
3870 (tpdu[1] & 0x20)? "response": "request",
3872 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3885 print_error (int err)
3892 case 0: p = "success"; break;
3893 case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break;
3894 case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break;
3895 case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break;
3896 case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break;
3897 case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break;
3898 case CCID_DRIVER_ERR_BUSY: p = "busy"; break;
3899 case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break;
3900 case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break;
3901 case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break;
3902 case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break;
3903 case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break;
3904 case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break;
3905 default: sprintf (buf, "0x%05x", err); p = buf; break;
3907 fprintf (stderr, "operation failed: %s\n", p);
3912 print_data (const unsigned char *data, size_t length)
3916 fprintf (stderr, "operation status: %02X%02X\n",
3917 data[length-2], data[length-1]);
3922 fputs (" returned data:", stderr);
3923 for (; length; length--, data++)
3924 fprintf (stderr, " %02X", *data);
3925 putc ('\n', stderr);
3930 print_result (int rc, const unsigned char *data, size_t length)
3935 print_data (data, length);
3939 main (int argc, char **argv)
3944 unsigned char result[512];
3947 int verify_123456 = 0;
3951 struct ccid_dev_table *ccid_table;
3961 if ( !strcmp (*argv, "--list"))
3964 p = ccid_get_reader_list ();
3971 else if ( !strcmp (*argv, "--debug"))
3973 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
3976 else if ( !strcmp (*argv, "--no-poll"))
3981 else if ( !strcmp (*argv, "--no-pinpad"))
3986 else if ( !strcmp (*argv, "--verify-123456"))
3995 err = ccid_dev_scan (&idx_max, &ccid_table);
4002 err = ccid_open_reader (argc? *argv:NULL, 0, ccid_table, &ccid, NULL);
4006 ccid_dev_scan_finish (ccid_table, idx_max);
4010 fputs ("getting ATR ...\n", stderr);
4011 err = ccid_get_atr (ccid, NULL, 0, NULL);
4020 fputs ("getting slot status ...\n", stderr);
4021 err = ccid_slot_status (ccid, &slotstat, 1);
4031 fputs ("selecting application OpenPGP ....\n", stderr);
4033 static unsigned char apdu[] = {
4034 0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01};
4035 err = ccid_transceive (ccid,
4037 result, sizeof result, &resultlen);
4038 print_result (err, result, resultlen);
4045 fputs ("getting OpenPGP DO 0x65 ....\n", stderr);
4047 static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 };
4048 err = ccid_transceive (ccid, apdu, sizeof apdu,
4049 result, sizeof result, &resultlen);
4050 print_result (err, result, resultlen);
4059 static unsigned char apdu[] = { 0, 0x20, 0, 0x81 };
4060 pininfo_t pininfo = { 0, 0, 0 };
4062 if (ccid_transceive_secure (ccid, apdu, sizeof apdu, &pininfo,
4064 fputs ("can't verify using a PIN-Pad reader\n", stderr);
4067 fputs ("verifying CHV1 using the PINPad ....\n", stderr);
4069 err = ccid_transceive_secure (ccid, apdu, sizeof apdu, &pininfo,
4070 result, sizeof result, &resultlen);
4071 print_result (err, result, resultlen);
4076 if (verify_123456 && !did_verify)
4078 fputs ("verifying that CHV1 is 123456....\n", stderr);
4080 static unsigned char apdu[] = {0, 0x20, 0, 0x81,
4081 6, '1','2','3','4','5','6'};
4082 err = ccid_transceive (ccid, apdu, sizeof apdu,
4083 result, sizeof result, &resultlen);
4084 print_result (err, result, resultlen);
4090 fputs ("getting OpenPGP DO 0x5E ....\n", stderr);
4092 static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 };
4093 err = ccid_transceive (ccid, apdu, sizeof apdu,
4094 result, sizeof result, &resultlen);
4095 print_result (err, result, resultlen);
4099 ccid_close_reader (ccid);
4105 * Disabled Local Variables:
4106 * 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"
4110 #endif /*HAVE_LIBUSB*/