1 /* ccid-driver.c - USB ChipCardInterfaceDevices driver
2 * Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
3 * Written by Werner Koch.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
22 * ALTERNATIVELY, this file may be distributed under the terms of the
23 * following license, in which case the provisions of this license are
24 * required INSTEAD OF the GNU General Public License. If you wish to
25 * allow use of your version of this file only under the terms of the
26 * GNU General Public License, and not to allow others to use your
27 * version of this file under the terms of the following license,
28 * indicate your decision by deleting this paragraph and the license
31 * Redistribution and use in source and binary forms, with or without
32 * modification, are permitted provided that the following conditions
34 * 1. Redistributions of source code must retain the above copyright
35 * notice, and the entire permission notice in its entirety,
36 * including the disclaimer of warranties.
37 * 2. Redistributions in binary form must reproduce the above copyright
38 * notice, this list of conditions and the following disclaimer in the
39 * documentation and/or other materials provided with the distribution.
40 * 3. The name of the author may not be used to endorse or promote
41 * products derived from this software without specific prior
44 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
45 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
46 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
47 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
48 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
49 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
50 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
51 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
52 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
53 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
54 * OF THE POSSIBILITY OF SUCH DAMAGE.
56 * $Date: 2006-01-19 23:21:46 $
60 /* CCID (ChipCardInterfaceDevices) is a specification for accessing
61 smartcard via a reader connected to the USB.
63 This is a limited driver allowing to use some CCID drivers directly
64 without any other specila drivers. This is a fallback driver to be
65 used when nothing else works or the system should be kept minimal
66 for security reasons. It makes use of the libusb library to gain
67 portable access to USB.
69 This driver has been tested with the SCM SCR335 and SPR532
70 smartcard readers and requires that a reader implements the TPDU
71 level exchange and does fully automatic initialization.
78 #if defined(HAVE_LIBUSB) || defined(TEST)
88 #include "ccid-driver.h"
90 #define DRVNAME "ccid-driver: "
93 /* Depending on how this source is used we either define our error
94 output to go to stderr or to the jnlib based logging functions. We
95 use the latter when GNUPG_MAJOR_VERSION is defines or when both,
96 GNUPG_SCD_MAIN_HEADER and HAVE_JNLIB_LOGGING are defined.
98 #if defined(GNUPG_MAJOR_VERSION) \
99 || (defined(GNUPG_SCD_MAIN_HEADER) && defined(HAVE_JNLIB_LOGGING))
101 #if defined(GNUPG_SCD_MAIN_HEADER)
102 # include GNUPG_SCD_MAIN_HEADER
103 #elif GNUPG_MAJOR_VERSION == 1 /* GnuPG Version is < 1.9. */
104 # include "options.h"
107 # include "cardglue.h"
108 # else /* This is the modularized GnuPG 1.9 or later. */
109 # include "scdaemon.h"
113 # define DEBUGOUT(t) do { if (debug_level) \
114 log_debug (DRVNAME t); } while (0)
115 # define DEBUGOUT_1(t,a) do { if (debug_level) \
116 log_debug (DRVNAME t,(a)); } while (0)
117 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
118 log_debug (DRVNAME t,(a),(b)); } while (0)
119 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
120 log_debug (DRVNAME t,(a),(b),(c));} while (0)
121 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
122 log_debug (DRVNAME t,(a),(b),(c),(d));} while (0)
123 # define DEBUGOUT_CONT(t) do { if (debug_level) \
124 log_printf (t); } while (0)
125 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
126 log_printf (t,(a)); } while (0)
127 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
128 log_printf (t,(a),(b)); } while (0)
129 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
130 log_printf (t,(a),(b),(c)); } while (0)
131 # define DEBUGOUT_LF() do { if (debug_level) \
132 log_printf ("\n"); } while (0)
134 #else /* Other usage of this source - don't use gnupg specifics. */
136 # define DEBUGOUT(t) do { if (debug_level) \
137 fprintf (stderr, DRVNAME t); } while (0)
138 # define DEBUGOUT_1(t,a) do { if (debug_level) \
139 fprintf (stderr, DRVNAME t, (a)); } while (0)
140 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
141 fprintf (stderr, DRVNAME t, (a), (b)); } while (0)
142 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
143 fprintf (stderr, DRVNAME t, (a), (b), (c)); } while (0)
144 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
145 fprintf (stderr, DRVNAME t, (a), (b), (c), (d));} while(0)
146 # define DEBUGOUT_CONT(t) do { if (debug_level) \
147 fprintf (stderr, t); } while (0)
148 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
149 fprintf (stderr, t, (a)); } while (0)
150 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
151 fprintf (stderr, t, (a), (b)); } while (0)
152 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
153 fprintf (stderr, t, (a), (b), (c)); } while (0)
154 # define DEBUGOUT_LF() do { if (debug_level) \
155 putc ('\n', stderr); } while (0)
157 #endif /* This source not used by scdaemon. */
162 RDR_to_PC_NotifySlotChange= 0x50,
163 RDR_to_PC_HardwareError = 0x51,
165 PC_to_RDR_SetParameters = 0x61,
166 PC_to_RDR_IccPowerOn = 0x62,
167 PC_to_RDR_IccPowerOff = 0x63,
168 PC_to_RDR_GetSlotStatus = 0x65,
169 PC_to_RDR_Secure = 0x69,
170 PC_to_RDR_T0APDU = 0x6a,
171 PC_to_RDR_Escape = 0x6b,
172 PC_to_RDR_GetParameters = 0x6c,
173 PC_to_RDR_ResetParameters = 0x6d,
174 PC_to_RDR_IccClock = 0x6e,
175 PC_to_RDR_XfrBlock = 0x6f,
176 PC_to_RDR_Mechanical = 0x71,
177 PC_to_RDR_Abort = 0x72,
178 PC_to_RDR_SetDataRate = 0x73,
180 RDR_to_PC_DataBlock = 0x80,
181 RDR_to_PC_SlotStatus = 0x81,
182 RDR_to_PC_Parameters = 0x82,
183 RDR_to_PC_Escape = 0x83,
184 RDR_to_PC_DataRate = 0x84
188 /* Two macro to detect whether a CCID command has failed and to get
189 the error code. These macros assume that we can access the
190 mandatory first 10 bytes of a CCID message in BUF. */
191 #define CCID_COMMAND_FAILED(buf) ((buf)[7] & 0x40)
192 #define CCID_ERROR_CODE(buf) (((unsigned char *)(buf))[8])
195 /* We need to know the vendor to do some hacks. */
198 VENDOR_CHERRY = 0x046a,
199 VENDOR_OMNIKEY= 0x076b,
200 VENDOR_GEMPC = 0x08e6
204 /* Store information on the driver's state. A pointer to such a
205 structure is used as handle for most functions. */
208 usb_dev_handle *idev;
210 unsigned short id_vendor;
211 unsigned short id_product;
212 unsigned short bcd_device;
226 int apdu_level; /* Reader supports short APDU level exchange. */
230 static int initialized_usb; /* Tracks whether USB has been initialized. */
231 static int debug_level; /* Flag to control the debug output.
234 2 = T=1 protocol tracing
238 static unsigned int compute_edc (const unsigned char *data, size_t datalen,
240 static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen);
241 static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
242 size_t *nread, int expected_type, int seqno, int timeout,
245 /* Convert a little endian stored 4 byte value into an unsigned
248 convert_le_u32 (const unsigned char *buf)
250 return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
254 set_msg_len (unsigned char *msg, unsigned int length)
257 msg[2] = length >> 8;
258 msg[3] = length >> 16;
259 msg[4] = length >> 24;
263 /* Pint an error message for a failed CCID command including a textual
264 error code. MSG is shall be the CCID message of at least 10 bytes. */
266 print_command_failed (const unsigned char *msg)
275 ec = CCID_ERROR_CODE (msg);
278 case 0x00: t = "Command not supported"; break;
280 case 0xE0: t = "Slot busy"; break;
281 case 0xEF: t = "PIN cancelled"; break;
282 case 0xF0: t = "PIN timeout"; break;
284 case 0xF2: t = "Automatic sequence ongoing"; break;
285 case 0xF3: t = "Deactivated Protocol"; break;
286 case 0xF4: t = "Procedure byte conflict"; break;
287 case 0xF5: t = "ICC class not supported"; break;
288 case 0xF6: t = "ICC protocol not supported"; break;
289 case 0xF7: t = "Bad checksum in ATR"; break;
290 case 0xF8: t = "Bad TS in ATR"; break;
292 case 0xFB: t = "An all inclusive hardware error occurred"; break;
293 case 0xFC: t = "Overrun error while talking to the ICC"; break;
294 case 0xFD: t = "Parity error while talking to the ICC"; break;
295 case 0xFE: t = "CCID timed out while talking to the ICC"; break;
296 case 0xFF: t = "Host aborted the current activity"; break;
299 if (ec > 0 && ec < 128)
300 sprintf (buffer, "Parameter error at offset %d", ec);
302 sprintf (buffer, "Error code %02X", ec);
306 DEBUGOUT_1 ("CCID command failed: %s\n", t);
312 /* Parse a CCID descriptor, optionally print all available features
313 and test whether this reader is usable by this driver. Returns 0
316 Note, that this code is based on the one in lsusb.c of the
317 usb-utils package, I wrote on 2003-09-01. -wk. */
319 parse_ccid_descriptor (ccid_driver_t handle,
320 const unsigned char *buf, size_t buflen)
324 int have_t1 = 0, have_tpdu=0, have_auto_conf = 0;
327 handle->nonnull_nad = 0;
328 handle->auto_ifsd = 0;
329 handle->max_ifsd = 32;
331 handle->has_pinpad = 0;
332 handle->apdu_level = 0;
333 DEBUGOUT_3 ("idVendor: %04X idProduct: %04X bcdDevice: %04X\n",
334 handle->id_vendor, handle->id_product, handle->bcd_device);
335 if (buflen < 54 || buf[0] < 54)
337 DEBUGOUT ("CCID device descriptor is too short\n");
341 DEBUGOUT ("ChipCard Interface Descriptor:\n");
342 DEBUGOUT_1 (" bLength %5u\n", buf[0]);
343 DEBUGOUT_1 (" bDescriptorType %5u\n", buf[1]);
344 DEBUGOUT_2 (" bcdCCID %2x.%02x", buf[3], buf[2]);
345 if (buf[3] != 1 || buf[2] != 0)
346 DEBUGOUT_CONT(" (Warning: Only accurate for version 1.0)");
349 DEBUGOUT_1 (" nMaxSlotIndex %5u\n", buf[4]);
350 DEBUGOUT_2 (" bVoltageSupport %5u %s\n",
351 buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V"
352 : buf[5] == 3? "1.8V":"?"));
354 us = convert_le_u32 (buf+6);
355 DEBUGOUT_1 (" dwProtocols %5u ", us);
357 DEBUGOUT_CONT (" T=0");
360 DEBUGOUT_CONT (" T=1");
364 DEBUGOUT_CONT (" (Invalid values detected)");
367 us = convert_le_u32(buf+10);
368 DEBUGOUT_1 (" dwDefaultClock %5u\n", us);
369 us = convert_le_u32(buf+14);
370 DEBUGOUT_1 (" dwMaxiumumClock %5u\n", us);
371 DEBUGOUT_1 (" bNumClockSupported %5u\n", buf[18]);
372 us = convert_le_u32(buf+19);
373 DEBUGOUT_1 (" dwDataRate %7u bps\n", us);
374 us = convert_le_u32(buf+23);
375 DEBUGOUT_1 (" dwMaxDataRate %7u bps\n", us);
376 DEBUGOUT_1 (" bNumDataRatesSupp. %5u\n", buf[27]);
378 us = convert_le_u32(buf+28);
379 DEBUGOUT_1 (" dwMaxIFSD %5u\n", us);
380 handle->max_ifsd = us;
382 us = convert_le_u32(buf+32);
383 DEBUGOUT_1 (" dwSyncProtocols %08X ", us);
385 DEBUGOUT_CONT ( " 2-wire");
387 DEBUGOUT_CONT ( " 3-wire");
389 DEBUGOUT_CONT ( " I2C");
392 us = convert_le_u32(buf+36);
393 DEBUGOUT_1 (" dwMechanical %08X ", us);
395 DEBUGOUT_CONT (" accept");
397 DEBUGOUT_CONT (" eject");
399 DEBUGOUT_CONT (" capture");
401 DEBUGOUT_CONT (" lock");
404 us = convert_le_u32(buf+40);
405 DEBUGOUT_1 (" dwFeatures %08X\n", us);
408 DEBUGOUT (" Auto configuration based on ATR\n");
412 DEBUGOUT (" Auto activation on insert\n");
414 DEBUGOUT (" Auto voltage selection\n");
416 DEBUGOUT (" Auto clock change\n");
418 DEBUGOUT (" Auto baud rate change\n");
420 DEBUGOUT (" Auto parameter negotation made by CCID\n");
421 else if ((us & 0x0080))
422 DEBUGOUT (" Auto PPS made by CCID\n");
423 else if ((us & (0x0040 | 0x0080)))
424 DEBUGOUT (" WARNING: conflicting negotation features\n");
427 DEBUGOUT (" CCID can set ICC in clock stop mode\n");
430 DEBUGOUT (" NAD value other than 0x00 accepted\n");
431 handle->nonnull_nad = 1;
435 DEBUGOUT (" Auto IFSD exchange\n");
436 handle->auto_ifsd = 1;
439 if ((us & 0x00010000))
441 DEBUGOUT (" TPDU level exchange\n");
444 else if ((us & 0x00020000))
446 DEBUGOUT (" Short APDU level exchange\n");
447 handle->apdu_level = 1;
449 else if ((us & 0x00040000))
451 DEBUGOUT (" Short and extended APDU level exchange\n");
452 handle->apdu_level = 1;
454 else if ((us & 0x00070000))
455 DEBUGOUT (" WARNING: conflicting exchange levels\n");
457 us = convert_le_u32(buf+44);
458 DEBUGOUT_1 (" dwMaxCCIDMsgLen %5u\n", us);
460 DEBUGOUT ( " bClassGetResponse ");
462 DEBUGOUT_CONT ("echo\n");
464 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
466 DEBUGOUT ( " bClassEnvelope ");
468 DEBUGOUT_CONT ("echo\n");
470 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
472 DEBUGOUT ( " wlcdLayout ");
473 if (!buf[50] && !buf[51])
474 DEBUGOUT_CONT ("none\n");
476 DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]);
478 DEBUGOUT_1 (" bPINSupport %5u ", buf[52]);
481 DEBUGOUT_CONT ( " verification");
482 handle->has_pinpad |= 1;
486 DEBUGOUT_CONT ( " modification");
487 handle->has_pinpad |= 2;
491 DEBUGOUT_1 (" bMaxCCIDBusySlots %5u\n", buf[53]);
495 for (i=54; i < buf[0]-54; i++)
496 DEBUGOUT_CONT_1 (" %02X", buf[i]);
500 if (!have_t1 || !(have_tpdu || handle->apdu_level) || !have_auto_conf)
502 DEBUGOUT ("this drivers requires that the reader supports T=1, "
503 "TPDU or APDU level exchange and auto configuration - "
504 "this is not available\n");
509 /* SCM drivers get stuck in their internal USB stack if they try to
510 send a frame of n*wMaxPacketSize back to us. Given that
511 wMaxPacketSize is 64 for these readers we set the IFSD to a value
513 64 - 10 CCID header - 4 T1frame - 2 reserved = 48
520 if (handle->id_vendor == VENDOR_SCM
521 && handle->max_ifsd > 48
522 && ( (handle->id_product == 0xe001 && handle->bcd_device < 0x0516)
523 ||(handle->id_product == 0x5111 && handle->bcd_device < 0x0620)
524 ||(handle->id_product == 0x5115 && handle->bcd_device < 0x0514)
525 ||(handle->id_product == 0xe003 && handle->bcd_device < 0x0504)
528 DEBUGOUT ("enabling workaround for buggy SCM readers\n");
529 handle->max_ifsd = 48;
538 get_escaped_usb_string (usb_dev_handle *idev, int idx,
539 const char *prefix, const char *suffix)
542 unsigned char buf[280];
551 /* Fixme: The next line is for the current Valgrid without support
553 memset (buf, 0, sizeof buf);
555 /* First get the list of supported languages and use the first one.
556 If we do don't find it we try to use English. Note that this is
557 all in a 2 bute Unicode encoding using little endian. */
558 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
559 (USB_DT_STRING << 8), 0,
560 (char*)buf, sizeof buf, 1000 /* ms timeout */);
562 langid = 0x0409; /* English. */
564 langid = (buf[3] << 8) | buf[2];
566 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
567 (USB_DT_STRING << 8) + idx, langid,
568 (char*)buf, sizeof buf, 1000 /* ms timeout */);
569 if (rc < 2 || buf[1] != USB_DT_STRING)
570 return NULL; /* Error or not a string. */
573 return NULL; /* Larger than our buffer. */
575 for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2)
578 n++; /* High byte set. */
579 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
585 result = malloc (strlen (prefix) + n + strlen (suffix) + 1);
589 strcpy (result, prefix);
591 for (s=buf+2, i=2; i+1 < len; i += 2, s += 2)
594 result[n++] = '\xff'; /* High byte set. */
595 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
597 sprintf (result+n, "%%%02X", *s);
603 strcpy (result+n, suffix);
608 /* This function creates an reader id to be used to find the same
609 physical reader after a reset. It returns an allocated and possibly
610 percent escaped string or NULL if not enough memory is available. */
612 make_reader_id (usb_dev_handle *idev,
613 unsigned int vendor, unsigned int product,
614 unsigned char serialno_index)
619 sprintf (prefix, "%04X:%04X:", (vendor & 0xfff), (product & 0xffff));
620 rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0");
623 rid = malloc (strlen (prefix) + 3 + 1);
626 strcpy (rid, prefix);
633 /* Helper to find the endpoint from an interface descriptor. */
635 find_endpoint (struct usb_interface_descriptor *ifcdesc, int mode)
638 int want_bulk_in = 0;
642 for (no=0; no < ifcdesc->bNumEndpoints; no++)
644 struct usb_endpoint_descriptor *ep = ifcdesc->endpoint + no;
645 if (ep->bDescriptorType != USB_DT_ENDPOINT)
648 && ((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
649 == USB_ENDPOINT_TYPE_INTERRUPT)
650 && (ep->bEndpointAddress & 0x80))
651 return (ep->bEndpointAddress & 0x0f);
652 else if (((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
653 == USB_ENDPOINT_TYPE_BULK)
654 && (ep->bEndpointAddress & 0x80) == want_bulk_in)
655 return (ep->bEndpointAddress & 0x0f);
657 /* Should never happen. */
658 return mode == 2? 0x83 : mode == 1? 0x82 :1;
663 /* Combination function to either scan all CCID devices or to find and
664 open one specific device.
666 With READERNO = -1 and READERID is NULL, scan mode is used and
667 R_RID should be the address where to store the list of reader_ids
668 we found. If on return this list is empty, no CCID device has been
669 found; otherwise it points to an allocated linked list of reader
670 IDs. Note that in this mode the function always returns NULL.
672 With READERNO >= 0 or READERID is not NULL find mode is used. This
673 uses the same algorithm as the scan mode but stops and returns at
674 the entry number READERNO and return the handle for the the opened
675 USB device. If R_ID is not NULL it will receive the reader ID of
676 that device. If R_DEV is not NULL it will the device pointer of
677 that device. If IFCDESC_EXTRA is NOT NULL it will receive a
678 malloced copy of the interfaces "extra: data filed;
679 IFCDESC_EXTRA_LEN receive the lengtyh of this field. If there is
680 no reader with number READERNO or that reader is not usable by our
681 implementation NULL will be returned. The caller must close a
682 returned USB device handle and free (if not passed as NULL) the
683 returned reader ID info as well as the IFCDESC_EXTRA. On error
684 NULL will get stored at R_RID, R_DEV, IFCDESC_EXTRA and
685 IFCDESC_EXTRA_LEN. With READERID being -1 the function stops if
686 the READERID was found.
688 Note that the first entry of the returned reader ID list in scan mode
689 corresponds with a READERNO of 0 in find mode.
691 static usb_dev_handle *
692 scan_or_find_devices (int readerno, const char *readerid,
694 struct usb_device **r_dev,
695 unsigned char **ifcdesc_extra,
696 size_t *ifcdesc_extra_len,
697 int *interface_number,
698 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr)
700 char *rid_list = NULL;
702 struct usb_bus *busses, *bus;
703 struct usb_device *dev = NULL;
704 usb_dev_handle *idev = NULL;
705 int scan_mode = (readerno == -1 && !readerid);
707 /* Set return values to a default. */
713 *ifcdesc_extra = NULL;
714 if (ifcdesc_extra_len)
715 *ifcdesc_extra_len = 0;
716 if (interface_number)
717 *interface_number = 0;
719 /* See whether we want scan or find mode. */
728 #ifdef HAVE_USB_GET_BUSSES
729 busses = usb_get_busses();
734 for (bus = busses; bus; bus = bus->next)
736 for (dev = bus->devices; dev; dev = dev->next)
740 for (cfg_no=0; cfg_no < dev->descriptor.bNumConfigurations; cfg_no++)
742 struct usb_config_descriptor *config = dev->config + cfg_no;
748 for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
750 struct usb_interface *interface
751 = config->interface + ifc_no;
757 for (set_no=0; set_no < interface->num_altsetting; set_no++)
759 struct usb_interface_descriptor *ifcdesc
760 = interface->altsetting + set_no;
763 /* The second condition is for some SCM Micro
764 SPR 532 which does not know about the
765 assigned CCID class. Instead of trying to
766 interpret the strings we simply look at the
768 if (ifcdesc && ifcdesc->extra
769 && ( (ifcdesc->bInterfaceClass == 11
770 && ifcdesc->bInterfaceSubClass == 0
771 && ifcdesc->bInterfaceProtocol == 0)
772 || (ifcdesc->bInterfaceClass == 255
773 && dev->descriptor.idVendor == 0x04e6
774 && dev->descriptor.idProduct == 0xe003)))
776 idev = usb_open (dev);
779 DEBUGOUT_1 ("usb_open failed: %s\n",
784 rid = make_reader_id (idev,
785 dev->descriptor.idVendor,
786 dev->descriptor.idProduct,
787 dev->descriptor.iSerialNumber);
794 /* We are collecting infos about all
795 available CCID readers. Store
796 them and continue. */
797 DEBUGOUT_2 ("found CCID reader %d "
800 if ((p = malloc ((rid_list?
808 strcat (p, rid_list);
815 else /* Out of memory. */
823 && !strcmp (readerid, rid)))
825 /* We found the requested reader. */
826 if (ifcdesc_extra && ifcdesc_extra_len)
828 *ifcdesc_extra = malloc (ifcdesc
834 return NULL; /* Out of core. */
836 memcpy (*ifcdesc_extra, ifcdesc->extra,
838 *ifcdesc_extra_len = ifcdesc->extralen;
840 if (interface_number)
841 *interface_number = (ifcdesc->
844 *ep_bulk_out = find_endpoint (ifcdesc, 0);
846 *ep_bulk_in = find_endpoint (ifcdesc, 1);
848 *ep_intr = find_endpoint (ifcdesc, 2);
860 return idev; /* READY. */
864 /* This is not yet the reader we
865 want. fixme: We could avoid the
866 extra usb_open in this case. */
892 /* Set the level of debugging to to usea dn return the old level. -1
893 just returns the old level. A level of 0 disables debugging, 1
894 enables debugging, 2 enables additional tracing of the T=1
895 protocol, other values are not yet defined. */
897 ccid_set_debug_level (int level)
899 int old = debug_level;
907 ccid_get_reader_list (void)
911 if (!initialized_usb)
917 scan_or_find_devices (-1, NULL, &reader_list, NULL, NULL, NULL, NULL,
923 /* Open the reader with the internal number READERNO and return a
924 pointer to be used as handle in HANDLE. Returns 0 on success. */
926 ccid_open_reader (ccid_driver_t *handle, const char *readerid)
929 struct usb_device *dev = NULL;
930 usb_dev_handle *idev = NULL;
932 unsigned char *ifcdesc_extra = NULL;
933 size_t ifcdesc_extra_len;
935 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
939 if (!initialized_usb)
945 /* See whether we want to use the reader ID string or a reader
946 number. A readerno of -1 indicates that the reader ID string is
948 if (readerid && strchr (readerid, ':'))
949 readerno = -1; /* We want to use the readerid. */
952 readerno = atoi (readerid);
955 DEBUGOUT ("no CCID readers found\n");
956 rc = CCID_DRIVER_ERR_NO_READER;
961 readerno = 0; /* Default. */
963 idev = scan_or_find_devices (readerno, readerid, &rid, &dev,
964 &ifcdesc_extra, &ifcdesc_extra_len,
965 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr);
969 DEBUGOUT_1 ("no CCID reader with ID %s\n", readerid );
971 DEBUGOUT_1 ("no CCID reader with number %d\n", readerno );
972 rc = CCID_DRIVER_ERR_NO_READER;
976 /* Okay, this is a CCID reader. */
977 *handle = calloc (1, sizeof **handle);
980 DEBUGOUT ("out of memory\n");
981 rc = CCID_DRIVER_ERR_OUT_OF_CORE;
984 (*handle)->idev = idev;
985 (*handle)->rid = rid;
986 (*handle)->id_vendor = dev->descriptor.idVendor;
987 (*handle)->id_product = dev->descriptor.idProduct;
988 (*handle)->bcd_device = dev->descriptor.bcdDevice;
989 (*handle)->ifc_no = ifc_no;
990 (*handle)->ep_bulk_out = ep_bulk_out;
991 (*handle)->ep_bulk_in = ep_bulk_in;
992 (*handle)->ep_intr = ep_intr;
994 DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n", readerno, rid );
997 if (parse_ccid_descriptor (*handle, ifcdesc_extra, ifcdesc_extra_len))
999 DEBUGOUT ("device not supported\n");
1000 rc = CCID_DRIVER_ERR_NO_READER;
1004 rc = usb_claim_interface (idev, ifc_no);
1007 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1008 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1013 free (ifcdesc_extra);
1028 do_close_reader (ccid_driver_t handle)
1031 unsigned char msg[100];
1033 unsigned char seqno;
1035 if (!handle->powered_off)
1037 msg[0] = PC_to_RDR_IccPowerOff;
1038 msg[5] = 0; /* slot */
1039 msg[6] = seqno = handle->seqno++;
1040 msg[7] = 0; /* RFU */
1041 msg[8] = 0; /* RFU */
1042 msg[9] = 0; /* RFU */
1043 set_msg_len (msg, 0);
1046 rc = bulk_out (handle, msg, msglen);
1048 bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1050 handle->powered_off = 1;
1054 usb_release_interface (handle->idev, handle->ifc_no);
1055 usb_close (handle->idev);
1056 handle->idev = NULL;
1061 /* Reset a reader on HANDLE. This is useful in case a reader has been
1062 plugged of and inserted at a different port. By resetting the
1063 handle, the same reader will be get used. Note, that on error the
1064 handle won't get released.
1066 This does not return an ATR, so ccid_get_atr should be called right
1070 ccid_shutdown_reader (ccid_driver_t handle)
1073 struct usb_device *dev = NULL;
1074 usb_dev_handle *idev = NULL;
1075 unsigned char *ifcdesc_extra = NULL;
1076 size_t ifcdesc_extra_len;
1077 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1079 if (!handle || !handle->rid)
1080 return CCID_DRIVER_ERR_INV_VALUE;
1082 do_close_reader (handle);
1084 idev = scan_or_find_devices (-1, handle->rid, NULL, &dev,
1085 &ifcdesc_extra, &ifcdesc_extra_len,
1086 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr);
1089 DEBUGOUT_1 ("no CCID reader with ID %s\n", handle->rid);
1090 return CCID_DRIVER_ERR_NO_READER;
1094 handle->idev = idev;
1095 handle->ifc_no = ifc_no;
1096 handle->ep_bulk_out = ep_bulk_out;
1097 handle->ep_bulk_in = ep_bulk_in;
1098 handle->ep_intr = ep_intr;
1100 if (parse_ccid_descriptor (handle, ifcdesc_extra, ifcdesc_extra_len))
1102 DEBUGOUT ("device not supported\n");
1103 rc = CCID_DRIVER_ERR_NO_READER;
1107 rc = usb_claim_interface (idev, ifc_no);
1110 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1111 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1116 free (ifcdesc_extra);
1119 usb_close (handle->idev);
1120 handle->idev = NULL;
1128 /* Close the reader HANDLE. */
1130 ccid_close_reader (ccid_driver_t handle)
1132 if (!handle || !handle->idev)
1135 do_close_reader (handle);
1142 /* Return False if a card is present and powered. */
1144 ccid_check_card_presence (ccid_driver_t handle)
1151 /* Write a MSG of length MSGLEN to the designated bulk out endpoint.
1152 Returns 0 on success. */
1154 bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen)
1158 rc = usb_bulk_write (handle->idev,
1159 handle->ep_bulk_out,
1161 1000 /* ms timeout */);
1166 DEBUGOUT_1 ("usb_bulk_write error: %s\n", strerror (errno));
1168 DEBUGOUT_1 ("usb_bulk_write failed: %d\n", rc);
1169 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1173 /* Read a maximum of LENGTH bytes from the bulk in endpoint into
1174 BUFFER and return the actual read number if bytes in NREAD. SEQNO
1175 is the sequence number used to send the request and EXPECTED_TYPE
1176 the type of message we expect. Does checks on the ccid
1177 header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to
1178 avoid debug messages in case of no error. Returns 0 on success. */
1180 bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
1181 size_t *nread, int expected_type, int seqno, int timeout,
1187 /* Fixme: The next line for the current Valgrind without support
1189 memset (buffer, 0, length);
1191 rc = usb_bulk_read (handle->idev,
1193 (char*)buffer, length,
1197 DEBUGOUT_1 ("usb_bulk_read error: %s\n", strerror (errno));
1198 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1201 *nread = msglen = rc;
1205 DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen);
1206 return CCID_DRIVER_ERR_INV_VALUE;
1208 if (buffer[0] != expected_type)
1210 DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]);
1211 return CCID_DRIVER_ERR_INV_VALUE;
1215 DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]);
1216 return CCID_DRIVER_ERR_INV_VALUE;
1218 if (buffer[6] != seqno)
1220 DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n",
1222 return CCID_DRIVER_ERR_INV_VALUE;
1225 if ( !(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80)
1227 /* Card present and active, time extension requested. */
1228 DEBUGOUT_2 ("time extension requested (%02X,%02X)\n",
1229 buffer[7], buffer[8]);
1235 DEBUGOUT_3 ("status: %02X error: %02X octet[9]: %02X\n"
1236 " data:", buffer[7], buffer[8], buffer[9] );
1237 for (i=10; i < msglen; i++)
1238 DEBUGOUT_CONT_1 (" %02X", buffer[i]);
1241 if (CCID_COMMAND_FAILED (buffer))
1242 print_command_failed (buffer);
1244 /* Check whether a card is at all available. Note: If you add new
1245 error codes here, check whether they need to be ignored in
1247 switch ((buffer[7] & 0x03))
1249 case 0: /* no error */ break;
1250 case 1: return CCID_DRIVER_ERR_CARD_INACTIVE;
1251 case 2: return CCID_DRIVER_ERR_NO_CARD;
1252 case 3: /* RFU */ break;
1258 /* Note that this function won't return the error codes NO_CARD or
1259 CARD_INACTIVE. IF RESULT is not NULL, the result from the
1260 operation will get returned in RESULT and its length in RESULTLEN.
1261 If the response is larger than RESULTMAX, an error is returned and
1262 the required buffer length returned in RESULTLEN. */
1264 send_escape_cmd (ccid_driver_t handle,
1265 const unsigned char *data, size_t datalen,
1266 unsigned char *result, size_t resultmax, size_t *resultlen)
1269 unsigned char msg[100];
1271 unsigned char seqno;
1276 if (datalen > sizeof msg - 10)
1277 return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large. */
1279 msg[0] = PC_to_RDR_Escape;
1280 msg[5] = 0; /* slot */
1281 msg[6] = seqno = handle->seqno++;
1282 msg[7] = 0; /* RFU */
1283 msg[8] = 0; /* RFU */
1284 msg[9] = 0; /* RFU */
1285 memcpy (msg+10, data, datalen);
1286 msglen = 10 + datalen;
1287 set_msg_len (msg, datalen);
1289 DEBUGOUT ("sending");
1290 for (i=0; i < msglen; i++)
1291 DEBUGOUT_CONT_1 (" %02X", msg[i]);
1293 rc = bulk_out (handle, msg, msglen);
1296 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape,
1301 /* We need to ignore certain errorcode here. */
1303 case CCID_DRIVER_ERR_CARD_INACTIVE:
1304 case CCID_DRIVER_ERR_NO_CARD:
1306 if (msglen < 10 || (msglen-10) > resultmax )
1307 rc = CCID_DRIVER_ERR_INV_VALUE; /* Invalid length of response. */
1310 memcpy (result, msg+10, msglen-10);
1311 *resultlen = msglen-10;
1325 ccid_transceive_escape (ccid_driver_t handle,
1326 const unsigned char *data, size_t datalen,
1327 unsigned char *resp, size_t maxresplen, size_t *nresp)
1329 return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp);
1336 ccid_poll (ccid_driver_t handle)
1339 unsigned char msg[10];
1343 rc = usb_bulk_read (handle->idev,
1345 (char*)msg, sizeof msg,
1346 0 /* ms timeout */ );
1347 if (rc < 0 && errno == ETIMEDOUT)
1352 DEBUGOUT_1 ("usb_intr_read error: %s\n", strerror (errno));
1353 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1361 DEBUGOUT ("intr-in msg too short\n");
1362 return CCID_DRIVER_ERR_INV_VALUE;
1365 if (msg[0] == RDR_to_PC_NotifySlotChange)
1367 DEBUGOUT ("notify slot change:");
1368 for (i=1; i < msglen; i++)
1369 for (j=0; j < 4; j++)
1370 DEBUGOUT_CONT_3 (" %d:%c%c",
1372 (msg[i] & (1<<(j*2)))? 'p':'-',
1373 (msg[i] & (2<<(j*2)))? '*':' ');
1376 else if (msg[0] == RDR_to_PC_HardwareError)
1378 DEBUGOUT ("hardware error occured\n");
1382 DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]);
1389 /* Note that this fucntion won't return the error codes NO_CARD or
1392 ccid_slot_status (ccid_driver_t handle, int *statusbits)
1395 unsigned char msg[100];
1397 unsigned char seqno;
1401 msg[0] = PC_to_RDR_GetSlotStatus;
1402 msg[5] = 0; /* slot */
1403 msg[6] = seqno = handle->seqno++;
1404 msg[7] = 0; /* RFU */
1405 msg[8] = 0; /* RFU */
1406 msg[9] = 0; /* RFU */
1407 set_msg_len (msg, 0);
1409 rc = bulk_out (handle, msg, 10);
1412 /* Note that we set the NO_DEBUG flag here, so that the logs won't
1413 get cluttered up by a ticker function checking for the slot
1414 status and debugging enabled. */
1415 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1416 seqno, retries? 1000 : 200, 1);
1417 if (rc == CCID_DRIVER_ERR_CARD_IO_ERROR && retries < 3)
1421 DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n");
1422 usb_clear_halt (handle->idev, handle->ep_bulk_in);
1423 usb_clear_halt (handle->idev, handle->ep_bulk_out);
1426 DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n");
1430 if (rc && rc != CCID_DRIVER_ERR_NO_CARD
1431 && rc != CCID_DRIVER_ERR_CARD_INACTIVE)
1433 *statusbits = (msg[7] & 3);
1440 ccid_get_atr (ccid_driver_t handle,
1441 unsigned char *atr, size_t maxatrlen, size_t *atrlen)
1445 unsigned char msg[100];
1446 unsigned char *tpdu;
1447 size_t msglen, tpdulen;
1448 unsigned char seqno;
1454 /* First check whether a card is available. */
1455 rc = ccid_slot_status (handle, &statusbits);
1458 if (statusbits == 2)
1459 return CCID_DRIVER_ERR_NO_CARD;
1461 /* For an inactive and also for an active card, issue the PowerOn
1462 command to get the ATR. */
1464 msg[0] = PC_to_RDR_IccPowerOn;
1465 msg[5] = 0; /* slot */
1466 msg[6] = seqno = handle->seqno++;
1467 msg[7] = 0; /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */
1468 msg[8] = 0; /* RFU */
1469 msg[9] = 0; /* RFU */
1470 set_msg_len (msg, 0);
1473 rc = bulk_out (handle, msg, msglen);
1476 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
1480 if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb
1481 && ((handle->id_vendor == VENDOR_CHERRY
1482 && handle->id_product == 0x0005)
1483 || (handle->id_vendor == VENDOR_GEMPC
1484 && handle->id_product == 0x4433)
1488 /* Try switching to ISO mode. */
1489 if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2,
1493 else if (CCID_COMMAND_FAILED (msg))
1494 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1497 handle->powered_off = 0;
1501 size_t n = msglen - 10;
1505 memcpy (atr, msg+10, n);
1509 /* Setup parameters to select T=1. */
1510 msg[0] = PC_to_RDR_SetParameters;
1511 msg[5] = 0; /* slot */
1512 msg[6] = seqno = handle->seqno++;
1513 msg[7] = 1; /* Select T=1. */
1514 msg[8] = 0; /* RFU */
1515 msg[9] = 0; /* RFU */
1517 /* FIXME: Get those values from the ATR. */
1518 msg[10]= 0x01; /* Fi/Di */
1519 msg[11]= 0x10; /* LRC, direct convention. */
1520 msg[12]= 0; /* Extra guardtime. */
1521 msg[13]= 0x41; /* BWI/CWI */
1522 msg[14]= 0; /* No clock stoppping. */
1523 msg[15]= 254; /* IFSC */
1524 msg[16]= 0; /* Does not support non default NAD values. */
1525 set_msg_len (msg, 7);
1528 DEBUGOUT ("sending");
1529 for (i=0; i < msglen; i++)
1530 DEBUGOUT_CONT_1 (" %02X", msg[i]);
1533 rc = bulk_out (handle, msg, msglen);
1536 /* Note that we ignore the error code on purpose. */
1537 bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
1543 /* Send an S-Block with our maximun IFSD to the CCID. */
1544 if (!handle->auto_ifsd)
1547 /* NAD: DAD=1, SAD=0 */
1548 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
1549 tpdu[1] = (0xc0 | 0 | 1); /* S-block request: change IFSD */
1551 tpdu[3] = handle->max_ifsd? handle->max_ifsd : 32;
1553 edc = compute_edc (tpdu, tpdulen, use_crc);
1555 tpdu[tpdulen++] = (edc >> 8);
1556 tpdu[tpdulen++] = edc;
1558 msg[0] = PC_to_RDR_XfrBlock;
1559 msg[5] = 0; /* slot */
1560 msg[6] = seqno = handle->seqno++;
1562 msg[8] = 0; /* RFU */
1563 msg[9] = 0; /* RFU */
1564 set_msg_len (msg, tpdulen);
1565 msglen = 10 + tpdulen;
1567 DEBUGOUT ("sending");
1568 for (i=0; i < msglen; i++)
1569 DEBUGOUT_CONT_1 (" %02X", msg[i]);
1572 if (debug_level > 1)
1573 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
1574 ((msg[11] & 0xc0) == 0x80)? 'R' :
1575 (msg[11] & 0x80)? 'S' : 'I',
1576 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
1577 : !!(msg[11] & 0x40)),
1578 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
1580 rc = bulk_out (handle, msg, msglen);
1585 rc = bulk_in (handle, msg, sizeof msg, &msglen,
1586 RDR_to_PC_DataBlock, seqno, 5000, 0);
1591 tpdulen = msglen - 10;
1594 return CCID_DRIVER_ERR_ABORTED;
1596 if (debug_level > 1)
1597 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
1598 ((msg[11] & 0xc0) == 0x80)? 'R' :
1599 (msg[11] & 0x80)? 'S' : 'I',
1600 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
1601 : !!(msg[11] & 0x40)),
1602 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
1603 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
1605 if ((tpdu[1] & 0xe0) != 0xe0 || tpdu[2] != 1)
1607 DEBUGOUT ("invalid response for S-block (Change-IFSD)\n");
1610 DEBUGOUT_1 ("IFSD has been set to %d\n", tpdu[3]);
1620 compute_edc (const unsigned char *data, size_t datalen, int use_crc)
1624 return 0x42; /* Not yet implemented. */
1628 unsigned char crc = 0;
1630 for (; datalen; datalen--)
1637 /* Helper for ccid_transceive used for APDU level exchanges. */
1639 ccid_transceive_apdu_level (ccid_driver_t handle,
1640 const unsigned char *apdu_buf, size_t apdu_buflen,
1641 unsigned char *resp, size_t maxresplen,
1645 unsigned char send_buffer[10+259], recv_buffer[10+259];
1646 const unsigned char *apdu;
1650 unsigned char seqno;
1656 apdulen = apdu_buflen;
1660 return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
1662 msg[0] = PC_to_RDR_XfrBlock;
1663 msg[5] = 0; /* slot */
1664 msg[6] = seqno = handle->seqno++;
1665 msg[7] = 4; /* bBWI */
1666 msg[8] = 0; /* RFU */
1667 msg[9] = 0; /* RFU */
1668 memcpy (msg+10, apdu, apdulen);
1669 set_msg_len (msg, apdulen);
1670 msglen = 10 + apdulen;
1672 DEBUGOUT ("sending");
1673 for (i=0; i < msglen; i++)
1674 DEBUGOUT_CONT_1 (" %02X", msg[i]);
1677 rc = bulk_out (handle, msg, msglen);
1682 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
1683 RDR_to_PC_DataBlock, seqno, 5000, 0);
1688 apdulen = msglen - 10;
1692 if (apdulen > maxresplen)
1694 DEBUGOUT_2 ("provided buffer too short for received data "
1696 (unsigned int)apdulen, (unsigned int)maxresplen);
1697 return CCID_DRIVER_ERR_INV_VALUE;
1700 memcpy (resp, apdu, apdulen);
1710 Protocol T=1 overview
1714 1 byte Node Address (NAD)
1715 1 byte Protocol Control Byte (PCB)
1718 0-254 byte APDU or Control Information (INF)
1720 1 byte Error Detection Code (EDC)
1724 bit 4..6 Destination Node Address (DAD)
1726 bit 2..0 Source Node Address (SAD)
1728 If node adresses are not used, SAD and DAD should be set to 0 on
1729 the first block sent to the card. If they are used they should
1730 have different values (0 for one is okay); that first block sets up
1731 the addresses of the nodes.
1734 Information Block (I-Block):
1736 bit 6 Sequence number (yep, that is modulo 2)
1739 Received-Ready Block (R-Block):
1743 bit 4 Sequence number
1744 bit 3..0 0 = no error
1745 1 = EDC or parity error
1747 other values are reserved
1748 Supervisory Block (S-Block):
1751 bit 5 clear=request,set=response
1752 bit 4..0 0 = resyncronisation request
1753 1 = information field size request
1755 3 = extension of BWT request
1757 other values are reserved
1762 ccid_transceive (ccid_driver_t handle,
1763 const unsigned char *apdu_buf, size_t apdu_buflen,
1764 unsigned char *resp, size_t maxresplen, size_t *nresp)
1767 unsigned char send_buffer[10+259], recv_buffer[10+259];
1768 const unsigned char *apdu;
1770 unsigned char *msg, *tpdu, *p;
1771 size_t msglen, tpdulen, last_tpdulen, n;
1772 unsigned char seqno;
1782 nresp = &dummy_nresp;
1785 /* Smarter readers allow to send APDUs directly; divert here. */
1786 if (handle->apdu_level)
1787 return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen,
1788 resp, maxresplen, nresp);
1790 /* The other readers we support require sending TPDUs. */
1792 tpdulen = 0; /* Avoid compiler warning about no initialization. */
1801 apdulen = apdu_buflen;
1804 /* Construct an I-Block. */
1806 return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
1809 /* NAD: DAD=1, SAD=0 */
1810 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
1811 tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */
1812 if (apdulen > 128 /* fixme: replace by ifsc */)
1817 tpdu[1] |= (1 << 5); /* Set more bit. */
1820 memcpy (tpdu+3, apdu, apdulen);
1821 tpdulen = 3 + apdulen;
1822 edc = compute_edc (tpdu, tpdulen, use_crc);
1824 tpdu[tpdulen++] = (edc >> 8);
1825 tpdu[tpdulen++] = edc;
1828 msg[0] = PC_to_RDR_XfrBlock;
1829 msg[5] = 0; /* slot */
1830 msg[6] = seqno = handle->seqno++;
1831 msg[7] = 4; /* bBWI */
1832 msg[8] = 0; /* RFU */
1833 msg[9] = 0; /* RFU */
1834 set_msg_len (msg, tpdulen);
1835 msglen = 10 + tpdulen;
1836 last_tpdulen = tpdulen;
1838 DEBUGOUT ("sending");
1839 for (i=0; i < msglen; i++)
1840 DEBUGOUT_CONT_1 (" %02X", msg[i]);
1843 if (debug_level > 1)
1844 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
1845 ((msg[11] & 0xc0) == 0x80)? 'R' :
1846 (msg[11] & 0x80)? 'S' : 'I',
1847 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
1848 : !!(msg[11] & 0x40)),
1849 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
1851 rc = bulk_out (handle, msg, msglen);
1856 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
1857 RDR_to_PC_DataBlock, seqno, 5000, 0);
1862 tpdulen = msglen - 10;
1866 usb_clear_halt (handle->idev, handle->ep_bulk_in);
1867 return CCID_DRIVER_ERR_ABORTED;
1870 if (debug_level > 1)
1871 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
1872 ((msg[11] & 0xc0) == 0x80)? 'R' :
1873 (msg[11] & 0x80)? 'S' : 'I',
1874 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
1875 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
1876 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
1878 if (!(tpdu[1] & 0x80))
1879 { /* This is an I-block. */
1882 { /* last block sent was successful. */
1887 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
1888 { /* Reponse does not match our sequence number. */
1891 /* NAD: DAD=1, SAD=0 */
1892 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
1893 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */
1896 edc = compute_edc (tpdu, tpdulen, use_crc);
1898 tpdu[tpdulen++] = (edc >> 8);
1899 tpdu[tpdulen++] = edc;
1906 p = tpdu + 3; /* Skip the prologue field. */
1907 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
1908 /* fixme: verify the checksum. */
1913 DEBUGOUT_2 ("provided buffer too short for received data "
1915 (unsigned int)n, (unsigned int)maxresplen);
1916 return CCID_DRIVER_ERR_INV_VALUE;
1919 memcpy (resp, p, n);
1925 if (!(tpdu[1] & 0x20))
1926 return 0; /* No chaining requested - ready. */
1930 /* NAD: DAD=1, SAD=0 */
1931 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
1932 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */
1935 edc = compute_edc (tpdu, tpdulen, use_crc);
1937 tpdu[tpdulen++] = (edc >> 8);
1938 tpdu[tpdulen++] = edc;
1940 else if ((tpdu[1] & 0xc0) == 0x80)
1941 { /* This is a R-block. */
1942 if ( (tpdu[1] & 0x0f))
1943 { /* Error: repeat last block */
1946 DEBUGOUT ("3 failed retries\n");
1947 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1950 tpdulen = last_tpdulen;
1952 else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns)
1953 { /* Response does not match our sequence number. */
1954 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
1955 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1958 { /* Send next chunk. */
1966 DEBUGOUT ("unexpected ACK R-block received\n");
1967 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1971 { /* This is a S-block. */
1973 DEBUGOUT_2 ("T=1 S-block %s received cmd=%d\n",
1974 (tpdu[1] & 0x20)? "response": "request",
1976 if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2])
1977 { /* Wait time extension request. */
1978 unsigned char bwi = tpdu[3];
1981 /* NAD: DAD=1, SAD=0 */
1982 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
1983 tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */
1987 edc = compute_edc (tpdu, tpdulen, use_crc);
1989 tpdu[tpdulen++] = (edc >> 8);
1990 tpdu[tpdulen++] = edc;
1991 DEBUGOUT_1 ("T=1 waittime extension of bwi=%d\n", bwi);
1994 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1996 } /* end T=1 protocol loop. */
2002 /* Send the CCID Secure command to the reader. APDU_BUF should
2003 contain the APDU template. PIN_MODE defines how the pin gets
2006 1 := The PIN is ASCII encoded and of variable length. The
2007 length of the PIN entered will be put into Lc by the reader.
2008 The APDU should me made up of 4 bytes without Lc.
2010 PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0
2011 may be used t enable reasonable defaults. PIN_PADLEN should be 0.
2013 When called with RESP and NRESP set to NULL, the function will
2014 merely check whether the reader supports the secure command for the
2015 given APDU and PIN_MODE. */
2017 ccid_transceive_secure (ccid_driver_t handle,
2018 const unsigned char *apdu_buf, size_t apdu_buflen,
2019 int pin_mode, int pinlen_min, int pinlen_max,
2021 unsigned char *resp, size_t maxresplen, size_t *nresp)
2024 unsigned char send_buffer[10+259], recv_buffer[10+259];
2025 unsigned char *msg, *tpdu, *p;
2026 size_t msglen, tpdulen, n;
2027 unsigned char seqno;
2032 testmode = !resp && !nresp;
2035 nresp = &dummy_nresp;
2038 if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1))
2040 else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2))
2041 return CCID_DRIVER_ERR_NOT_SUPPORTED; /* Not yet by our code. */
2043 return CCID_DRIVER_ERR_NO_KEYPAD;
2046 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2048 if (pin_padlen != 0)
2049 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2056 /* Note that the 25 is the maximum value the SPR532 allows. */
2057 if (pinlen_min < 1 || pinlen_min > 25
2058 || pinlen_max < 1 || pinlen_max > 25
2059 || pinlen_min > pinlen_max)
2060 return CCID_DRIVER_ERR_INV_VALUE;
2062 /* We have only tested this with an SCM reader so better don't risk
2063 anything and do not allow the use with other readers. */
2064 if (handle->id_vendor != VENDOR_SCM)
2065 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2068 return 0; /* Success */
2071 if (handle->id_vendor == VENDOR_SCM)
2073 DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n");
2074 rc = send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3,
2080 msg[0] = PC_to_RDR_Secure;
2081 msg[5] = 0; /* slot */
2082 msg[6] = seqno = handle->seqno++;
2083 msg[7] = 4; /* bBWI */
2084 msg[8] = 0; /* RFU */
2085 msg[9] = 0; /* RFU */
2086 msg[10] = 0; /* Perform PIN verification. */
2087 msg[11] = 0; /* Timeout in seconds. */
2088 msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
2089 if (handle->id_vendor == VENDOR_SCM)
2091 /* For the SPR532 the next 2 bytes need to be zero. We do this
2092 for all SCM product. Kudos to Martin Paljak for this
2094 msg[13] = msg[14] = 0;
2098 msg[13] = 0x00; /* bmPINBlockString:
2099 0 bits of pin length to insert.
2100 0 bytes of PIN block size. */
2101 msg[14] = 0x00; /* bmPINLengthFormat:
2102 Units are bytes, position is 0. */
2104 msg[15] = pinlen_min; /* wPINMaxExtraDigit-Minimum. */
2105 msg[16] = pinlen_max; /* wPINMaxExtraDigit-Maximum. */
2106 msg[17] = 0x02; /* bEntryValidationCondition:
2107 Validation key pressed */
2108 if (pinlen_min && pinlen_max && pinlen_min == pinlen_max)
2109 msg[17] |= 0x01; /* Max size reached. */
2110 msg[18] = 0xff; /* bNumberMessage: Default. */
2111 msg[19] = 0x04; /* wLangId-High. */
2112 msg[20] = 0x09; /* wLangId-Low: English FIXME: use the first entry. */
2113 msg[21] = 0; /* bMsgIndex. */
2114 /* bTeoProlog follows: */
2115 msg[22] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2116 msg[23] = ((handle->t1_ns & 1) << 6); /* I-block */
2117 msg[24] = 4; /* apdulen. */
2119 msg[25] = apdu_buf[0]; /* CLA */
2120 msg[26] = apdu_buf[1]; /* INS */
2121 msg[27] = apdu_buf[2]; /* P1 */
2122 msg[28] = apdu_buf[3]; /* P2 */
2124 set_msg_len (msg, msglen - 10);
2126 DEBUGOUT ("sending");
2127 for (i=0; i < msglen; i++)
2128 DEBUGOUT_CONT_1 (" %02X", msg[i]);
2131 rc = bulk_out (handle, msg, msglen);
2136 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2137 RDR_to_PC_DataBlock, seqno, 5000, 0);
2142 tpdulen = msglen - 10;
2146 usb_clear_halt (handle->idev, handle->ep_bulk_in);
2147 return CCID_DRIVER_ERR_ABORTED;
2149 if (debug_level > 1)
2150 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2151 ((msg[11] & 0xc0) == 0x80)? 'R' :
2152 (msg[11] & 0x80)? 'S' : 'I',
2153 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
2154 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2155 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2157 if (!(tpdu[1] & 0x80))
2158 { /* This is an I-block. */
2159 /* Last block sent was successful. */
2162 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
2163 { /* Reponse does not match our sequence number. */
2164 DEBUGOUT ("I-block with wrong seqno received\n");
2165 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2170 p = tpdu + 3; /* Skip the prologue field. */
2171 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
2172 /* fixme: verify the checksum. */
2177 DEBUGOUT_2 ("provided buffer too short for received data "
2179 (unsigned int)n, (unsigned int)maxresplen);
2180 return CCID_DRIVER_ERR_INV_VALUE;
2183 memcpy (resp, p, n);
2189 if (!(tpdu[1] & 0x20))
2190 return 0; /* No chaining requested - ready. */
2192 DEBUGOUT ("chaining requested but not supported for Secure operation\n");
2193 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2195 else if ((tpdu[1] & 0xc0) == 0x80)
2196 { /* This is a R-block. */
2197 if ( (tpdu[1] & 0x0f))
2198 { /* Error: repeat last block */
2199 DEBUGOUT ("No retries supported for Secure operation\n");
2200 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2202 else if (!!(tpdu[1] & 0x10) == handle->t1_ns)
2203 { /* Reponse does not match our sequence number. */
2204 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
2205 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2208 { /* Send next chunk. */
2209 DEBUGOUT ("chaining not supported on Secure operation\n");
2210 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2214 { /* This is a S-block. */
2215 DEBUGOUT_2 ("T=1 S-block %s received cmd=%d for Secure operation\n",
2216 (tpdu[1] & 0x20)? "response": "request",
2218 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2231 print_error (int err)
2238 case 0: p = "success";
2239 case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break;
2240 case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break;
2241 case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break;
2242 case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break;
2243 case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break;
2244 case CCID_DRIVER_ERR_BUSY: p = "busy"; break;
2245 case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break;
2246 case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break;
2247 case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break;
2248 case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break;
2249 case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break;
2250 case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break;
2251 default: sprintf (buf, "0x%05x", err); p = buf; break;
2253 fprintf (stderr, "operation failed: %s\n", p);
2257 print_data (const unsigned char *data, size_t length)
2261 fprintf (stderr, "operation status: %02X%02X\n",
2262 data[length-2], data[length-1]);
2267 fputs (" returned data:", stderr);
2268 for (; length; length--, data++)
2269 fprintf (stderr, " %02X", *data);
2270 putc ('\n', stderr);
2275 print_result (int rc, const unsigned char *data, size_t length)
2280 print_data (data, length);
2284 main (int argc, char **argv)
2288 unsigned int slotstat;
2289 unsigned char result[512];
2292 int verify_123456 = 0;
2304 if ( !strcmp (*argv, "--list"))
2307 p = ccid_get_reader_list ();
2314 else if ( !strcmp (*argv, "--debug"))
2316 ccid_set_debug_level (1);
2319 else if ( !strcmp (*argv, "--no-poll"))
2324 else if ( !strcmp (*argv, "--no-pinpad"))
2329 else if ( !strcmp (*argv, "--verify-123456"))
2338 rc = ccid_open_reader (&ccid, argc? *argv:NULL);
2344 fputs ("getting ATR ...\n", stderr);
2345 rc = ccid_get_atr (ccid, NULL, 0, NULL);
2354 fputs ("getting slot status ...\n", stderr);
2355 rc = ccid_slot_status (ccid, &slotstat);
2365 fputs ("selecting application OpenPGP ....\n", stderr);
2367 static unsigned char apdu[] = {
2368 0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01};
2369 rc = ccid_transceive (ccid,
2371 result, sizeof result, &resultlen);
2372 print_result (rc, result, resultlen);
2379 fputs ("getting OpenPGP DO 0x65 ....\n", stderr);
2381 static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 };
2382 rc = ccid_transceive (ccid, apdu, sizeof apdu,
2383 result, sizeof result, &resultlen);
2384 print_result (rc, result, resultlen);
2393 static unsigned char apdu[] = { 0, 0x20, 0, 0x81 };
2396 if (ccid_transceive_secure (ccid,
2400 fputs ("can't verify using a PIN-Pad reader\n", stderr);
2403 fputs ("verifying CHV1 using the PINPad ....\n", stderr);
2405 rc = ccid_transceive_secure (ccid,
2408 result, sizeof result, &resultlen);
2409 print_result (rc, result, resultlen);
2414 if (verify_123456 && !did_verify)
2416 fputs ("verifying that CHV1 is 123456....\n", stderr);
2418 static unsigned char apdu[] = {0, 0x20, 0, 0x81,
2419 6, '1','2','3','4','5','6'};
2420 rc = ccid_transceive (ccid, apdu, sizeof apdu,
2421 result, sizeof result, &resultlen);
2422 print_result (rc, result, resultlen);
2428 fputs ("getting OpenPGP DO 0x5E ....\n", stderr);
2430 static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 };
2431 rc = ccid_transceive (ccid, apdu, sizeof apdu,
2432 result, sizeof result, &resultlen);
2433 print_result (rc, result, resultlen);
2437 ccid_close_reader (ccid);
2444 * compile-command: "gcc -DTEST -Wall -I/usr/local/include -lusb -g ccid-driver.c"
2448 #endif /*HAVE_LIBUSB*/