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: 2005-09-09 13:18:08 +0200 (Fri, 09 Sep 2005) $
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.
74 #include <librfid/rfid.h>
76 #ifndef LIBRFID_FIRMWARE
82 #if defined(HAVE_LIBUSB) || defined(TEST)
92 #include "ccid-driver.h"
94 #define DRVNAME "ccid-driver: "
97 /* Depending on how this source is used we either define our error
98 output to go to stderr or to the jnlib based logging functions. We
99 use the latter when GNUPG_MAJOR_VERSION is defines or when both,
100 GNUPG_SCD_MAIN_HEADER and HAVE_JNLIB_LOGGING are defined.
102 #if defined(GNUPG_MAJOR_VERSION) \
103 || (defined(GNUPG_SCD_MAIN_HEADER) && defined(HAVE_JNLIB_LOGGING))
105 #if defined(GNUPG_SCD_MAIN_HEADER)
106 # include GNUPG_SCD_MAIN_HEADER
107 #elif GNUPG_MAJOR_VERSION == 1 /* GnuPG Version is < 1.9. */
108 # include "options.h"
111 # include "cardglue.h"
112 # else /* This is the modularized GnuPG 1.9 or later. */
113 # include "scdaemon.h"
117 # define DEBUGOUT(t) do { if (debug_level) \
118 log_debug (DRVNAME t); } while (0)
119 # define DEBUGOUT_1(t,a) do { if (debug_level) \
120 log_debug (DRVNAME t,(a)); } while (0)
121 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
122 log_debug (DRVNAME t,(a),(b)); } while (0)
123 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
124 log_debug (DRVNAME t,(a),(b),(c));} while (0)
125 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
126 log_debug (DRVNAME t,(a),(b),(c),(d));} while (0)
127 # define DEBUGOUT_CONT(t) do { if (debug_level) \
128 log_printf (t); } while (0)
129 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
130 log_printf (t,(a)); } while (0)
131 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
132 log_printf (t,(a),(b)); } while (0)
133 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
134 log_printf (t,(a),(b),(c)); } while (0)
135 # define DEBUGOUT_LF() do { if (debug_level) \
136 log_printf ("\n"); } while (0)
138 #else /* Other usage of this source - don't use gnupg specifics. */
140 # define DEBUGOUT(t) do { if (debug_level) \
141 fprintf (stderr, DRVNAME t); } while (0)
142 # define DEBUGOUT_1(t,a) do { if (debug_level) \
143 fprintf (stderr, DRVNAME t, (a)); } while (0)
144 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
145 fprintf (stderr, DRVNAME t, (a), (b)); } while (0)
146 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
147 fprintf (stderr, DRVNAME t, (a), (b), (c)); } while (0)
148 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
149 fprintf (stderr, DRVNAME t, (a), (b), (c), (d));} while(0)
150 # define DEBUGOUT_CONT(t) do { if (debug_level) \
151 fprintf (stderr, t); } while (0)
152 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
153 fprintf (stderr, t, (a)); } while (0)
154 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
155 fprintf (stderr, t, (a), (b)); } while (0)
156 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
157 fprintf (stderr, t, (a), (b), (c)); } while (0)
158 # define DEBUGOUT_LF() do { if (debug_level) \
159 putc ('\n', stderr); } while (0)
161 #endif /* This source not used by scdaemon. */
166 RDR_to_PC_NotifySlotChange= 0x50,
167 RDR_to_PC_HardwareError = 0x51,
169 PC_to_RDR_SetParameters = 0x61,
170 PC_to_RDR_IccPowerOn = 0x62,
171 PC_to_RDR_IccPowerOff = 0x63,
172 PC_to_RDR_GetSlotStatus = 0x65,
173 PC_to_RDR_Secure = 0x69,
174 PC_to_RDR_T0APDU = 0x6a,
175 PC_to_RDR_Escape = 0x6b,
176 PC_to_RDR_GetParameters = 0x6c,
177 PC_to_RDR_ResetParameters = 0x6d,
178 PC_to_RDR_IccClock = 0x6e,
179 PC_to_RDR_XfrBlock = 0x6f,
180 PC_to_RDR_Mechanical = 0x71,
181 PC_to_RDR_Abort = 0x72,
182 PC_to_RDR_SetDataRate = 0x73,
184 RDR_to_PC_DataBlock = 0x80,
185 RDR_to_PC_SlotStatus = 0x81,
186 RDR_to_PC_Parameters = 0x82,
187 RDR_to_PC_Escape = 0x83,
188 RDR_to_PC_DataRate = 0x84
192 /* Two macro to detect whether a CCID command has failed and to get
193 the error code. These macros assume that we can access the
194 mandatory first 10 bytes of a CCID message in BUF. */
195 #define CCID_COMMAND_FAILED(buf) ((buf)[7] & 0x40)
196 #define CCID_ERROR_CODE(buf) (((unsigned char *)(buf))[8])
199 /* We need to know the vendor to do some hacks. */
202 VENDOR_CHERRY = 0x046a,
203 VENDOR_OMNIKEY= 0x076b,
204 VENDOR_GEMPC = 0x08e6
208 /* Store information on the driver's state. A pointer to such a
209 structure is used as handle for most functions. */
212 usb_dev_handle *idev;
214 unsigned short id_vendor;
215 unsigned short id_product;
216 unsigned short bcd_device;
230 int apdu_level; /* Reader supports short APDU level exchange. */
234 static int initialized_usb; /* Tracks whether USB has been initialized. */
235 static int debug_level; /* Flag to control the debug output.
238 2 = T=1 protocol tracing
242 static unsigned int compute_edc (const unsigned char *data, size_t datalen,
244 static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen);
245 static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
246 size_t *nread, int expected_type, int seqno, int timeout,
249 /* Convert a little endian stored 4 byte value into an unsigned
252 convert_le_u32 (const unsigned char *buf)
254 return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
258 set_msg_len (unsigned char *msg, unsigned int length)
261 msg[2] = length >> 8;
262 msg[3] = length >> 16;
263 msg[4] = length >> 24;
267 /* Pint an error message for a failed CCID command including a textual
268 error code. MSG is shall be the CCID message of at least 10 bytes. */
270 print_command_failed (const unsigned char *msg)
279 ec = CCID_ERROR_CODE (msg);
282 case 0x00: t = "Command not supported"; break;
284 case 0xE0: t = "Slot busy"; break;
285 case 0xEF: t = "PIN cancelled"; break;
286 case 0xF0: t = "PIN timeout"; break;
288 case 0xF2: t = "Automatic sequence ongoing"; break;
289 case 0xF3: t = "Deactivated Protocol"; break;
290 case 0xF4: t = "Procedure byte conflict"; break;
291 case 0xF5: t = "ICC class not supported"; break;
292 case 0xF6: t = "ICC protocol not supported"; break;
293 case 0xF7: t = "Bad checksum in ATR"; break;
294 case 0xF8: t = "Bad TS in ATR"; break;
296 case 0xFB: t = "An all inclusive hardware error occurred"; break;
297 case 0xFC: t = "Overrun error while talking to the ICC"; break;
298 case 0xFD: t = "Parity error while talking to the ICC"; break;
299 case 0xFE: t = "CCID timed out while talking to the ICC"; break;
300 case 0xFF: t = "Host aborted the current activity"; break;
303 if (ec > 0 && ec < 128)
304 sprintf (buffer, "Parameter error at offset %d", ec);
306 sprintf (buffer, "Error code %02X", ec);
310 DEBUGOUT_1 ("CCID command failed: %s\n", t);
316 /* Parse a CCID descriptor, optionally print all available features
317 and test whether this reader is usable by this driver. Returns 0
320 Note, that this code is based on the one in lsusb.c of the
321 usb-utils package, I wrote on 2003-09-01. -wk. */
323 parse_ccid_descriptor (ccid_driver_t handle,
324 const unsigned char *buf, size_t buflen)
328 int have_t1 = 0, have_tpdu=0, have_auto_conf = 0;
331 handle->nonnull_nad = 0;
332 handle->auto_ifsd = 0;
333 handle->max_ifsd = 32;
335 handle->has_pinpad = 0;
336 handle->apdu_level = 0;
337 DEBUGOUT_3 ("idVendor: %04X idProduct: %04X bcdDevice: %04X\n",
338 handle->id_vendor, handle->id_product, handle->bcd_device);
339 if (buflen < 54 || buf[0] < 54)
341 DEBUGOUT ("CCID device descriptor is too short\n");
345 DEBUGOUT ("ChipCard Interface Descriptor:\n");
346 DEBUGOUT_1 (" bLength %5u\n", buf[0]);
347 DEBUGOUT_1 (" bDescriptorType %5u\n", buf[1]);
348 DEBUGOUT_2 (" bcdCCID %2x.%02x", buf[3], buf[2]);
349 if (buf[3] != 1 || buf[2] != 0)
350 DEBUGOUT_CONT(" (Warning: Only accurate for version 1.0)");
353 DEBUGOUT_1 (" nMaxSlotIndex %5u\n", buf[4]);
354 DEBUGOUT_2 (" bVoltageSupport %5u %s\n",
355 buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V"
356 : buf[5] == 3? "1.8V":"?"));
358 us = convert_le_u32 (buf+6);
359 DEBUGOUT_1 (" dwProtocols %5u ", us);
361 DEBUGOUT_CONT (" T=0");
364 DEBUGOUT_CONT (" T=1");
368 DEBUGOUT_CONT (" (Invalid values detected)");
371 us = convert_le_u32(buf+10);
372 DEBUGOUT_1 (" dwDefaultClock %5u\n", us);
373 us = convert_le_u32(buf+14);
374 DEBUGOUT_1 (" dwMaxiumumClock %5u\n", us);
375 DEBUGOUT_1 (" bNumClockSupported %5u\n", buf[18]);
376 us = convert_le_u32(buf+19);
377 DEBUGOUT_1 (" dwDataRate %7u bps\n", us);
378 us = convert_le_u32(buf+23);
379 DEBUGOUT_1 (" dwMaxDataRate %7u bps\n", us);
380 DEBUGOUT_1 (" bNumDataRatesSupp. %5u\n", buf[27]);
382 us = convert_le_u32(buf+28);
383 DEBUGOUT_1 (" dwMaxIFSD %5u\n", us);
384 handle->max_ifsd = us;
386 us = convert_le_u32(buf+32);
387 DEBUGOUT_1 (" dwSyncProtocols %08X ", us);
389 DEBUGOUT_CONT ( " 2-wire");
391 DEBUGOUT_CONT ( " 3-wire");
393 DEBUGOUT_CONT ( " I2C");
396 us = convert_le_u32(buf+36);
397 DEBUGOUT_1 (" dwMechanical %08X ", us);
399 DEBUGOUT_CONT (" accept");
401 DEBUGOUT_CONT (" eject");
403 DEBUGOUT_CONT (" capture");
405 DEBUGOUT_CONT (" lock");
408 us = convert_le_u32(buf+40);
409 DEBUGOUT_1 (" dwFeatures %08X\n", us);
412 DEBUGOUT (" Auto configuration based on ATR\n");
416 DEBUGOUT (" Auto activation on insert\n");
418 DEBUGOUT (" Auto voltage selection\n");
420 DEBUGOUT (" Auto clock change\n");
422 DEBUGOUT (" Auto baud rate change\n");
424 DEBUGOUT (" Auto parameter negotation made by CCID\n");
425 else if ((us & 0x0080))
426 DEBUGOUT (" Auto PPS made by CCID\n");
427 else if ((us & (0x0040 | 0x0080)))
428 DEBUGOUT (" WARNING: conflicting negotation features\n");
431 DEBUGOUT (" CCID can set ICC in clock stop mode\n");
434 DEBUGOUT (" NAD value other than 0x00 accepted\n");
435 handle->nonnull_nad = 1;
439 DEBUGOUT (" Auto IFSD exchange\n");
440 handle->auto_ifsd = 1;
443 if ((us & 0x00010000))
445 DEBUGOUT (" TPDU level exchange\n");
448 else if ((us & 0x00020000))
450 DEBUGOUT (" Short APDU level exchange\n");
451 handle->apdu_level = 1;
453 else if ((us & 0x00040000))
455 DEBUGOUT (" Short and extended APDU level exchange\n");
456 handle->apdu_level = 1;
458 else if ((us & 0x00070000))
459 DEBUGOUT (" WARNING: conflicting exchange levels\n");
461 us = convert_le_u32(buf+44);
462 DEBUGOUT_1 (" dwMaxCCIDMsgLen %5u\n", us);
464 DEBUGOUT ( " bClassGetResponse ");
466 DEBUGOUT_CONT ("echo\n");
468 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
470 DEBUGOUT ( " bClassEnvelope ");
472 DEBUGOUT_CONT ("echo\n");
474 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
476 DEBUGOUT ( " wlcdLayout ");
477 if (!buf[50] && !buf[51])
478 DEBUGOUT_CONT ("none\n");
480 DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]);
482 DEBUGOUT_1 (" bPINSupport %5u ", buf[52]);
485 DEBUGOUT_CONT ( " verification");
486 handle->has_pinpad |= 1;
490 DEBUGOUT_CONT ( " modification");
491 handle->has_pinpad |= 2;
495 DEBUGOUT_1 (" bMaxCCIDBusySlots %5u\n", buf[53]);
499 for (i=54; i < buf[0]-54; i++)
500 DEBUGOUT_CONT_1 (" %02X", buf[i]);
504 if (!have_t1 || !(have_tpdu || handle->apdu_level) || !have_auto_conf)
506 DEBUGOUT ("this drivers requires that the reader supports T=1, "
507 "TPDU or APDU level exchange and auto configuration - "
508 "this is not available\n");
513 /* SCM drivers get stuck in their internal USB stack if they try to
514 send a frame of n*wMaxPacketSize back to us. Given that
515 wMaxPacketSize is 64 for these readers we set the IFSD to a value
517 64 - 10 CCID header - 4 T1frame - 2 reserved = 48
524 if (handle->id_vendor == VENDOR_SCM
525 && handle->max_ifsd > 48
526 && ( (handle->id_product == 0xe001 && handle->bcd_device < 0x0516)
527 ||(handle->id_product == 0x5111 && handle->bcd_device < 0x0620)
528 ||(handle->id_product == 0x5115 && handle->bcd_device < 0x0514)
529 ||(handle->id_product == 0xe003 && handle->bcd_device < 0x0504)
532 DEBUGOUT ("enabling workaround for buggy SCM readers\n");
533 handle->max_ifsd = 48;
542 get_escaped_usb_string (usb_dev_handle *idev, int idx,
543 const char *prefix, const char *suffix)
546 unsigned char buf[280];
555 /* Fixme: The next line is for the current Valgrid without support
557 memset (buf, 0, sizeof buf);
559 /* First get the list of supported languages and use the first one.
560 If we do don't find it we try to use English. Note that this is
561 all in a 2 bute Unicode encoding using little endian. */
562 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
563 (USB_DT_STRING << 8), 0,
564 (char*)buf, sizeof buf, 1000 /* ms timeout */);
566 langid = 0x0409; /* English. */
568 langid = (buf[3] << 8) | buf[2];
570 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
571 (USB_DT_STRING << 8) + idx, langid,
572 (char*)buf, sizeof buf, 1000 /* ms timeout */);
573 if (rc < 2 || buf[1] != USB_DT_STRING)
574 return NULL; /* Error or not a string. */
577 return NULL; /* Larger than our buffer. */
579 for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2)
582 n++; /* High byte set. */
583 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
589 result = malloc (strlen (prefix) + n + strlen (suffix) + 1);
593 strcpy (result, prefix);
595 for (s=buf+2, i=2; i+1 < len; i += 2, s += 2)
598 result[n++] = '\xff'; /* High byte set. */
599 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
601 sprintf (result+n, "%%%02X", *s);
607 strcpy (result+n, suffix);
612 /* This function creates an reader id to be used to find the same
613 physical reader after a reset. It returns an allocated and possibly
614 percent escaped string or NULL if not enough memory is available. */
616 make_reader_id (usb_dev_handle *idev,
617 unsigned int vendor, unsigned int product,
618 unsigned char serialno_index)
623 sprintf (prefix, "%04X:%04X:", (vendor & 0xfff), (product & 0xffff));
624 rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0");
627 rid = malloc (strlen (prefix) + 3 + 1);
630 strcpy (rid, prefix);
637 /* Helper to find the endpoint from an interface descriptor. */
639 find_endpoint (struct usb_interface_descriptor *ifcdesc, int mode)
642 int want_bulk_in = 0;
646 for (no=0; no < ifcdesc->bNumEndpoints; no++)
648 struct usb_endpoint_descriptor *ep = ifcdesc->endpoint + no;
649 if (ep->bDescriptorType != USB_DT_ENDPOINT)
652 && ((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
653 == USB_ENDPOINT_TYPE_INTERRUPT)
654 && (ep->bEndpointAddress & 0x80))
655 return (ep->bEndpointAddress & 0x0f);
656 else if (((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
657 == USB_ENDPOINT_TYPE_BULK)
658 && (ep->bEndpointAddress & 0x80) == want_bulk_in)
659 return (ep->bEndpointAddress & 0x0f);
661 /* Should never happen. */
662 return mode == 2? 0x83 : mode == 1? 0x82 :1;
667 /* Combination function to either scan all CCID devices or to find and
668 open one specific device.
670 With READERNO = -1 and READERID is NULL, scan mode is used and
671 R_RID should be the address where to store the list of reader_ids
672 we found. If on return this list is empty, no CCID device has been
673 found; otherwise it points to an allocated linked list of reader
674 IDs. Note that in this mode the function always returns NULL.
676 With READERNO >= 0 or READERID is not NULL find mode is used. This
677 uses the same algorithm as the scan mode but stops and returns at
678 the entry number READERNO and return the handle for the the opened
679 USB device. If R_ID is not NULL it will receive the reader ID of
680 that device. If R_DEV is not NULL it will the device pointer of
681 that device. If IFCDESC_EXTRA is NOT NULL it will receive a
682 malloced copy of the interfaces "extra: data filed;
683 IFCDESC_EXTRA_LEN receive the lengtyh of this field. If there is
684 no reader with number READERNO or that reader is not usable by our
685 implementation NULL will be returned. The caller must close a
686 returned USB device handle and free (if not passed as NULL) the
687 returned reader ID info as well as the IFCDESC_EXTRA. On error
688 NULL will get stored at R_RID, R_DEV, IFCDESC_EXTRA and
689 IFCDESC_EXTRA_LEN. With READERID being -1 the function stops if
690 the READERID was found.
692 Note that the first entry of the returned reader ID list in scan mode
693 corresponds with a READERNO of 0 in find mode.
695 static usb_dev_handle *
696 scan_or_find_devices (int readerno, const char *readerid,
698 struct usb_device **r_dev,
699 unsigned char **ifcdesc_extra,
700 size_t *ifcdesc_extra_len,
701 int *interface_number,
702 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr)
704 char *rid_list = NULL;
706 struct usb_bus *busses, *bus;
707 struct usb_device *dev = NULL;
708 usb_dev_handle *idev = NULL;
709 int scan_mode = (readerno == -1 && !readerid);
711 /* Set return values to a default. */
717 *ifcdesc_extra = NULL;
718 if (ifcdesc_extra_len)
719 *ifcdesc_extra_len = 0;
720 if (interface_number)
721 *interface_number = 0;
723 /* See whether we want scan or find mode. */
732 #ifdef HAVE_USB_GET_BUSSES
733 busses = usb_get_busses();
738 for (bus = busses; bus; bus = bus->next)
740 for (dev = bus->devices; dev; dev = dev->next)
744 for (cfg_no=0; cfg_no < dev->descriptor.bNumConfigurations; cfg_no++)
746 struct usb_config_descriptor *config = dev->config + cfg_no;
752 for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
754 struct usb_interface *interface
755 = config->interface + ifc_no;
761 for (set_no=0; set_no < interface->num_altsetting; set_no++)
763 struct usb_interface_descriptor *ifcdesc
764 = interface->altsetting + set_no;
767 /* The second condition is for some SCM Micro
768 SPR 532 which does not know about the
769 assigned CCID class. Instead of trying to
770 interpret the strings we simply look at the
772 if (ifcdesc && ifcdesc->extra
773 && ( (ifcdesc->bInterfaceClass == 11
774 && ifcdesc->bInterfaceSubClass == 0
775 && ifcdesc->bInterfaceProtocol == 0)
776 || (ifcdesc->bInterfaceClass == 255
777 && dev->descriptor.idVendor == 0x04e6
778 && dev->descriptor.idProduct == 0xe003)))
780 idev = usb_open (dev);
783 DEBUGOUT_1 ("usb_open failed: %s\n",
788 rid = make_reader_id (idev,
789 dev->descriptor.idVendor,
790 dev->descriptor.idProduct,
791 dev->descriptor.iSerialNumber);
798 /* We are collecting infos about all
799 available CCID readers. Store
800 them and continue. */
801 DEBUGOUT_2 ("found CCID reader %d "
804 if ((p = malloc ((rid_list?
812 strcat (p, rid_list);
819 else /* Out of memory. */
827 && !strcmp (readerid, rid)))
829 /* We found the requested reader. */
830 if (ifcdesc_extra && ifcdesc_extra_len)
832 *ifcdesc_extra = malloc (ifcdesc
838 return NULL; /* Out of core. */
840 memcpy (*ifcdesc_extra, ifcdesc->extra,
842 *ifcdesc_extra_len = ifcdesc->extralen;
844 if (interface_number)
845 *interface_number = (ifcdesc->
848 *ep_bulk_out = find_endpoint (ifcdesc, 0);
850 *ep_bulk_in = find_endpoint (ifcdesc, 1);
852 *ep_intr = find_endpoint (ifcdesc, 2);
864 return idev; /* READY. */
868 /* This is not yet the reader we
869 want. fixme: We could avoid the
870 extra usb_open in this case. */
896 /* Set the level of debugging to to usea dn return the old level. -1
897 just returns the old level. A level of 0 disables debugging, 1
898 enables debugging, 2 enables additional tracing of the T=1
899 protocol, other values are not yet defined. */
901 ccid_set_debug_level (int level)
903 int old = debug_level;
911 ccid_get_reader_list (void)
915 if (!initialized_usb)
921 scan_or_find_devices (-1, NULL, &reader_list, NULL, NULL, NULL, NULL,
927 /* Open the reader with the internal number READERNO and return a
928 pointer to be used as handle in HANDLE. Returns 0 on success. */
930 ccid_open_reader (ccid_driver_t *handle, const char *readerid)
933 struct usb_device *dev = NULL;
934 usb_dev_handle *idev = NULL;
936 unsigned char *ifcdesc_extra = NULL;
937 size_t ifcdesc_extra_len;
939 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
943 if (!initialized_usb)
949 /* See whether we want to use the reader ID string or a reader
950 number. A readerno of -1 indicates that the reader ID string is
952 if (readerid && strchr (readerid, ':'))
953 readerno = -1; /* We want to use the readerid. */
956 readerno = atoi (readerid);
959 DEBUGOUT ("no CCID readers found\n");
960 rc = CCID_DRIVER_ERR_NO_READER;
965 readerno = 0; /* Default. */
967 idev = scan_or_find_devices (readerno, readerid, &rid, &dev,
968 &ifcdesc_extra, &ifcdesc_extra_len,
969 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr);
973 DEBUGOUT_1 ("no CCID reader with ID %s\n", readerid );
975 DEBUGOUT_1 ("no CCID reader with number %d\n", readerno );
976 rc = CCID_DRIVER_ERR_NO_READER;
980 /* Okay, this is a CCID reader. */
981 *handle = calloc (1, sizeof **handle);
984 DEBUGOUT ("out of memory\n");
985 rc = CCID_DRIVER_ERR_OUT_OF_CORE;
988 (*handle)->idev = idev;
989 (*handle)->rid = rid;
990 (*handle)->id_vendor = dev->descriptor.idVendor;
991 (*handle)->id_product = dev->descriptor.idProduct;
992 (*handle)->bcd_device = dev->descriptor.bcdDevice;
993 (*handle)->ifc_no = ifc_no;
994 (*handle)->ep_bulk_out = ep_bulk_out;
995 (*handle)->ep_bulk_in = ep_bulk_in;
996 (*handle)->ep_intr = ep_intr;
998 DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n", readerno, rid );
1001 if (parse_ccid_descriptor (*handle, ifcdesc_extra, ifcdesc_extra_len))
1003 DEBUGOUT ("device not supported\n");
1004 rc = CCID_DRIVER_ERR_NO_READER;
1008 rc = usb_claim_interface (idev, ifc_no);
1011 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1012 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1017 free (ifcdesc_extra);
1032 do_close_reader (ccid_driver_t handle)
1035 unsigned char msg[100];
1037 unsigned char seqno;
1039 if (!handle->powered_off)
1041 msg[0] = PC_to_RDR_IccPowerOff;
1042 msg[5] = 0; /* slot */
1043 msg[6] = seqno = handle->seqno++;
1044 msg[7] = 0; /* RFU */
1045 msg[8] = 0; /* RFU */
1046 msg[9] = 0; /* RFU */
1047 set_msg_len (msg, 0);
1050 rc = bulk_out (handle, msg, msglen);
1052 bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1054 handle->powered_off = 1;
1058 usb_release_interface (handle->idev, handle->ifc_no);
1059 usb_close (handle->idev);
1060 handle->idev = NULL;
1065 /* Reset a reader on HANDLE. This is useful in case a reader has been
1066 plugged of and inserted at a different port. By resetting the
1067 handle, the same reader will be get used. Note, that on error the
1068 handle won't get released.
1070 This does not return an ATR, so ccid_get_atr should be called right
1074 ccid_shutdown_reader (ccid_driver_t handle)
1077 struct usb_device *dev = NULL;
1078 usb_dev_handle *idev = NULL;
1079 unsigned char *ifcdesc_extra = NULL;
1080 size_t ifcdesc_extra_len;
1081 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1083 if (!handle || !handle->rid)
1084 return CCID_DRIVER_ERR_INV_VALUE;
1086 do_close_reader (handle);
1088 idev = scan_or_find_devices (-1, handle->rid, NULL, &dev,
1089 &ifcdesc_extra, &ifcdesc_extra_len,
1090 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr);
1093 DEBUGOUT_1 ("no CCID reader with ID %s\n", handle->rid);
1094 return CCID_DRIVER_ERR_NO_READER;
1098 handle->idev = idev;
1099 handle->ifc_no = ifc_no;
1100 handle->ep_bulk_out = ep_bulk_out;
1101 handle->ep_bulk_in = ep_bulk_in;
1102 handle->ep_intr = ep_intr;
1104 if (parse_ccid_descriptor (handle, ifcdesc_extra, ifcdesc_extra_len))
1106 DEBUGOUT ("device not supported\n");
1107 rc = CCID_DRIVER_ERR_NO_READER;
1111 rc = usb_claim_interface (idev, ifc_no);
1114 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1115 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1120 free (ifcdesc_extra);
1123 usb_close (handle->idev);
1124 handle->idev = NULL;
1132 /* Close the reader HANDLE. */
1134 ccid_close_reader (ccid_driver_t handle)
1136 if (!handle || !handle->idev)
1139 do_close_reader (handle);
1146 /* Return False if a card is present and powered. */
1148 ccid_check_card_presence (ccid_driver_t handle)
1155 /* Write a MSG of length MSGLEN to the designated bulk out endpoint.
1156 Returns 0 on success. */
1158 bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen)
1162 rc = usb_bulk_write (handle->idev,
1163 handle->ep_bulk_out,
1165 1000 /* ms timeout */);
1170 DEBUGOUT_1 ("usb_bulk_write error: %s\n", strerror (errno));
1172 DEBUGOUT_1 ("usb_bulk_write failed: %d\n", rc);
1173 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1177 /* Read a maximum of LENGTH bytes from the bulk in endpoint into
1178 BUFFER and return the actual read number if bytes in NREAD. SEQNO
1179 is the sequence number used to send the request and EXPECTED_TYPE
1180 the type of message we expect. Does checks on the ccid
1181 header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to
1182 avoid debug messages in case of no error. Returns 0 on success. */
1184 bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
1185 size_t *nread, int expected_type, int seqno, int timeout,
1191 /* Fixme: The next line for the current Valgrind without support
1193 memset (buffer, 0, length);
1195 rc = usb_bulk_read (handle->idev,
1197 (char*)buffer, length,
1201 DEBUGOUT_1 ("usb_bulk_read error: %s\n", strerror (errno));
1202 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1205 *nread = msglen = rc;
1209 DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen);
1210 return CCID_DRIVER_ERR_INV_VALUE;
1212 if (buffer[0] != expected_type)
1214 DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]);
1215 return CCID_DRIVER_ERR_INV_VALUE;
1219 DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]);
1220 return CCID_DRIVER_ERR_INV_VALUE;
1222 if (buffer[6] != seqno)
1224 DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n",
1226 return CCID_DRIVER_ERR_INV_VALUE;
1229 if ( !(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80)
1231 /* Card present and active, time extension requested. */
1232 DEBUGOUT_2 ("time extension requested (%02X,%02X)\n",
1233 buffer[7], buffer[8]);
1239 DEBUGOUT_3 ("status: %02X error: %02X octet[9]: %02X\n"
1240 " data:", buffer[7], buffer[8], buffer[9] );
1241 for (i=10; i < msglen; i++)
1242 DEBUGOUT_CONT_1 (" %02X", buffer[i]);
1245 if (CCID_COMMAND_FAILED (buffer))
1246 print_command_failed (buffer);
1248 /* Check whether a card is at all available. Note: If you add new
1249 error codes here, check whether they need to be ignored in
1251 switch ((buffer[7] & 0x03))
1253 case 0: /* no error */ break;
1254 case 1: return CCID_DRIVER_ERR_CARD_INACTIVE;
1255 case 2: return CCID_DRIVER_ERR_NO_CARD;
1256 case 3: /* RFU */ break;
1262 /* Note that this function won't return the error codes NO_CARD or
1263 CARD_INACTIVE. IF RESULT is not NULL, the result from the
1264 operation will get returned in RESULT and its length in RESULTLEN.
1265 If the response is larger than RESULTMAX, an error is returned and
1266 the required buffer length returned in RESULTLEN. */
1268 send_escape_cmd (ccid_driver_t handle,
1269 const unsigned char *data, size_t datalen,
1270 unsigned char *result, size_t resultmax, size_t *resultlen)
1273 unsigned char msg[100];
1275 unsigned char seqno;
1280 if (datalen > sizeof msg - 10)
1281 return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large. */
1283 msg[0] = PC_to_RDR_Escape;
1284 msg[5] = 0; /* slot */
1285 msg[6] = seqno = handle->seqno++;
1286 msg[7] = 0; /* RFU */
1287 msg[8] = 0; /* RFU */
1288 msg[9] = 0; /* RFU */
1289 memcpy (msg+10, data, datalen);
1290 msglen = 10 + datalen;
1291 set_msg_len (msg, datalen);
1293 DEBUGOUT ("sending");
1294 for (i=0; i < msglen; i++)
1295 DEBUGOUT_CONT_1 (" %02X", msg[i]);
1297 rc = bulk_out (handle, msg, msglen);
1300 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape,
1305 /* We need to ignore certain errorcode here. */
1307 case CCID_DRIVER_ERR_CARD_INACTIVE:
1308 case CCID_DRIVER_ERR_NO_CARD:
1310 if (msglen < 10 || (msglen-10) > resultmax )
1311 rc = CCID_DRIVER_ERR_INV_VALUE; /* Invalid length of response. */
1314 memcpy (result, msg+10, msglen-10);
1315 *resultlen = msglen-10;
1329 ccid_transceive_escape (ccid_driver_t handle,
1330 const unsigned char *data, size_t datalen,
1331 unsigned char *resp, size_t maxresplen, size_t *nresp)
1333 return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp);
1340 ccid_poll (ccid_driver_t handle)
1343 unsigned char msg[10];
1347 rc = usb_bulk_read (handle->idev,
1349 (char*)msg, sizeof msg,
1350 0 /* ms timeout */ );
1351 if (rc < 0 && errno == ETIMEDOUT)
1356 DEBUGOUT_1 ("usb_intr_read error: %s\n", strerror (errno));
1357 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1365 DEBUGOUT ("intr-in msg too short\n");
1366 return CCID_DRIVER_ERR_INV_VALUE;
1369 if (msg[0] == RDR_to_PC_NotifySlotChange)
1371 DEBUGOUT ("notify slot change:");
1372 for (i=1; i < msglen; i++)
1373 for (j=0; j < 4; j++)
1374 DEBUGOUT_CONT_3 (" %d:%c%c",
1376 (msg[i] & (1<<(j*2)))? 'p':'-',
1377 (msg[i] & (2<<(j*2)))? '*':' ');
1380 else if (msg[0] == RDR_to_PC_HardwareError)
1382 DEBUGOUT ("hardware error occured\n");
1386 DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]);
1393 /* Note that this fucntion won't return the error codes NO_CARD or
1396 ccid_slot_status (ccid_driver_t handle, int *statusbits)
1399 unsigned char msg[100];
1401 unsigned char seqno;
1405 msg[0] = PC_to_RDR_GetSlotStatus;
1406 msg[5] = 0; /* slot */
1407 msg[6] = seqno = handle->seqno++;
1408 msg[7] = 0; /* RFU */
1409 msg[8] = 0; /* RFU */
1410 msg[9] = 0; /* RFU */
1411 set_msg_len (msg, 0);
1413 rc = bulk_out (handle, msg, 10);
1416 /* Note that we set the NO_DEBUG flag here, so that the logs won't
1417 get cluttered up by a ticker function checking for the slot
1418 status and debugging enabled. */
1419 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1420 seqno, retries? 1000 : 200, 1);
1421 if (rc == CCID_DRIVER_ERR_CARD_IO_ERROR && retries < 3)
1425 DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n");
1426 usb_clear_halt (handle->idev, handle->ep_bulk_in);
1427 usb_clear_halt (handle->idev, handle->ep_bulk_out);
1430 DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n");
1434 if (rc && rc != CCID_DRIVER_ERR_NO_CARD
1435 && rc != CCID_DRIVER_ERR_CARD_INACTIVE)
1437 *statusbits = (msg[7] & 3);
1444 ccid_get_atr (ccid_driver_t handle,
1445 unsigned char *atr, size_t maxatrlen, size_t *atrlen)
1449 unsigned char msg[100];
1450 unsigned char *tpdu;
1451 size_t msglen, tpdulen;
1452 unsigned char seqno;
1458 /* First check whether a card is available. */
1459 rc = ccid_slot_status (handle, &statusbits);
1462 if (statusbits == 2)
1463 return CCID_DRIVER_ERR_NO_CARD;
1465 /* For an inactive and also for an active card, issue the PowerOn
1466 command to get the ATR. */
1468 msg[0] = PC_to_RDR_IccPowerOn;
1469 msg[5] = 0; /* slot */
1470 msg[6] = seqno = handle->seqno++;
1471 msg[7] = 0; /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */
1472 msg[8] = 0; /* RFU */
1473 msg[9] = 0; /* RFU */
1474 set_msg_len (msg, 0);
1477 rc = bulk_out (handle, msg, msglen);
1480 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
1484 if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb
1485 && ((handle->id_vendor == VENDOR_CHERRY
1486 && handle->id_product == 0x0005)
1487 || (handle->id_vendor == VENDOR_GEMPC
1488 && handle->id_product == 0x4433)
1492 /* Try switching to ISO mode. */
1493 if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2,
1497 else if (CCID_COMMAND_FAILED (msg))
1498 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1501 handle->powered_off = 0;
1505 size_t n = msglen - 10;
1509 memcpy (atr, msg+10, n);
1513 /* Setup parameters to select T=1. */
1514 msg[0] = PC_to_RDR_SetParameters;
1515 msg[5] = 0; /* slot */
1516 msg[6] = seqno = handle->seqno++;
1517 msg[7] = 1; /* Select T=1. */
1518 msg[8] = 0; /* RFU */
1519 msg[9] = 0; /* RFU */
1521 /* FIXME: Get those values from the ATR. */
1522 msg[10]= 0x01; /* Fi/Di */
1523 msg[11]= 0x10; /* LRC, direct convention. */
1524 msg[12]= 0; /* Extra guardtime. */
1525 msg[13]= 0x41; /* BWI/CWI */
1526 msg[14]= 0; /* No clock stoppping. */
1527 msg[15]= 254; /* IFSC */
1528 msg[16]= 0; /* Does not support non default NAD values. */
1529 set_msg_len (msg, 7);
1532 DEBUGOUT ("sending");
1533 for (i=0; i < msglen; i++)
1534 DEBUGOUT_CONT_1 (" %02X", msg[i]);
1537 rc = bulk_out (handle, msg, msglen);
1540 /* Note that we ignore the error code on purpose. */
1541 bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
1547 /* Send an S-Block with our maximun IFSD to the CCID. */
1548 if (!handle->auto_ifsd)
1551 /* NAD: DAD=1, SAD=0 */
1552 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
1553 tpdu[1] = (0xc0 | 0 | 1); /* S-block request: change IFSD */
1555 tpdu[3] = handle->max_ifsd? handle->max_ifsd : 32;
1557 edc = compute_edc (tpdu, tpdulen, use_crc);
1559 tpdu[tpdulen++] = (edc >> 8);
1560 tpdu[tpdulen++] = edc;
1562 msg[0] = PC_to_RDR_XfrBlock;
1563 msg[5] = 0; /* slot */
1564 msg[6] = seqno = handle->seqno++;
1566 msg[8] = 0; /* RFU */
1567 msg[9] = 0; /* RFU */
1568 set_msg_len (msg, tpdulen);
1569 msglen = 10 + tpdulen;
1571 DEBUGOUT ("sending");
1572 for (i=0; i < msglen; i++)
1573 DEBUGOUT_CONT_1 (" %02X", msg[i]);
1576 if (debug_level > 1)
1577 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
1578 ((msg[11] & 0xc0) == 0x80)? 'R' :
1579 (msg[11] & 0x80)? 'S' : 'I',
1580 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
1581 : !!(msg[11] & 0x40)),
1582 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
1584 rc = bulk_out (handle, msg, msglen);
1589 rc = bulk_in (handle, msg, sizeof msg, &msglen,
1590 RDR_to_PC_DataBlock, seqno, 5000, 0);
1595 tpdulen = msglen - 10;
1598 return CCID_DRIVER_ERR_ABORTED;
1600 if (debug_level > 1)
1601 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
1602 ((msg[11] & 0xc0) == 0x80)? 'R' :
1603 (msg[11] & 0x80)? 'S' : 'I',
1604 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
1605 : !!(msg[11] & 0x40)),
1606 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
1607 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
1609 if ((tpdu[1] & 0xe0) != 0xe0 || tpdu[2] != 1)
1611 DEBUGOUT ("invalid response for S-block (Change-IFSD)\n");
1614 DEBUGOUT_1 ("IFSD has been set to %d\n", tpdu[3]);
1624 compute_edc (const unsigned char *data, size_t datalen, int use_crc)
1628 return 0x42; /* Not yet implemented. */
1632 unsigned char crc = 0;
1634 for (; datalen; datalen--)
1641 /* Helper for ccid_transceive used for APDU level exchanges. */
1643 ccid_transceive_apdu_level (ccid_driver_t handle,
1644 const unsigned char *apdu_buf, size_t apdu_buflen,
1645 unsigned char *resp, size_t maxresplen,
1649 unsigned char send_buffer[10+259], recv_buffer[10+259];
1650 const unsigned char *apdu;
1654 unsigned char seqno;
1660 apdulen = apdu_buflen;
1664 return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
1666 msg[0] = PC_to_RDR_XfrBlock;
1667 msg[5] = 0; /* slot */
1668 msg[6] = seqno = handle->seqno++;
1669 msg[7] = 4; /* bBWI */
1670 msg[8] = 0; /* RFU */
1671 msg[9] = 0; /* RFU */
1672 memcpy (msg+10, apdu, apdulen);
1673 set_msg_len (msg, apdulen);
1674 msglen = 10 + apdulen;
1676 DEBUGOUT ("sending");
1677 for (i=0; i < msglen; i++)
1678 DEBUGOUT_CONT_1 (" %02X", msg[i]);
1681 rc = bulk_out (handle, msg, msglen);
1686 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
1687 RDR_to_PC_DataBlock, seqno, 5000, 0);
1692 apdulen = msglen - 10;
1696 if (apdulen > maxresplen)
1698 DEBUGOUT_2 ("provided buffer too short for received data "
1700 (unsigned int)apdulen, (unsigned int)maxresplen);
1701 return CCID_DRIVER_ERR_INV_VALUE;
1704 memcpy (resp, apdu, apdulen);
1714 Protocol T=1 overview
1718 1 byte Node Address (NAD)
1719 1 byte Protocol Control Byte (PCB)
1722 0-254 byte APDU or Control Information (INF)
1724 1 byte Error Detection Code (EDC)
1728 bit 4..6 Destination Node Address (DAD)
1730 bit 2..0 Source Node Address (SAD)
1732 If node adresses are not used, SAD and DAD should be set to 0 on
1733 the first block sent to the card. If they are used they should
1734 have different values (0 for one is okay); that first block sets up
1735 the addresses of the nodes.
1738 Information Block (I-Block):
1740 bit 6 Sequence number (yep, that is modulo 2)
1743 Received-Ready Block (R-Block):
1747 bit 4 Sequence number
1748 bit 3..0 0 = no error
1749 1 = EDC or parity error
1751 other values are reserved
1752 Supervisory Block (S-Block):
1755 bit 5 clear=request,set=response
1756 bit 4..0 0 = resyncronisation request
1757 1 = information field size request
1759 3 = extension of BWT request
1761 other values are reserved
1766 ccid_transceive (ccid_driver_t handle,
1767 const unsigned char *apdu_buf, size_t apdu_buflen,
1768 unsigned char *resp, size_t maxresplen, size_t *nresp)
1771 unsigned char send_buffer[10+259], recv_buffer[10+259];
1772 const unsigned char *apdu;
1774 unsigned char *msg, *tpdu, *p;
1775 size_t msglen, tpdulen, last_tpdulen, n;
1776 unsigned char seqno;
1786 nresp = &dummy_nresp;
1789 /* Smarter readers allow to send APDUs directly; divert here. */
1790 if (handle->apdu_level)
1791 return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen,
1792 resp, maxresplen, nresp);
1794 /* The other readers we support require sending TPDUs. */
1796 tpdulen = 0; /* Avoid compiler warning about no initialization. */
1805 apdulen = apdu_buflen;
1808 /* Construct an I-Block. */
1810 return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
1813 /* NAD: DAD=1, SAD=0 */
1814 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
1815 tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */
1816 if (apdulen > 128 /* fixme: replace by ifsc */)
1821 tpdu[1] |= (1 << 5); /* Set more bit. */
1824 memcpy (tpdu+3, apdu, apdulen);
1825 tpdulen = 3 + apdulen;
1826 edc = compute_edc (tpdu, tpdulen, use_crc);
1828 tpdu[tpdulen++] = (edc >> 8);
1829 tpdu[tpdulen++] = edc;
1832 msg[0] = PC_to_RDR_XfrBlock;
1833 msg[5] = 0; /* slot */
1834 msg[6] = seqno = handle->seqno++;
1835 msg[7] = 4; /* bBWI */
1836 msg[8] = 0; /* RFU */
1837 msg[9] = 0; /* RFU */
1838 set_msg_len (msg, tpdulen);
1839 msglen = 10 + tpdulen;
1840 last_tpdulen = tpdulen;
1842 DEBUGOUT ("sending");
1843 for (i=0; i < msglen; i++)
1844 DEBUGOUT_CONT_1 (" %02X", msg[i]);
1847 if (debug_level > 1)
1848 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
1849 ((msg[11] & 0xc0) == 0x80)? 'R' :
1850 (msg[11] & 0x80)? 'S' : 'I',
1851 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
1852 : !!(msg[11] & 0x40)),
1853 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
1855 rc = bulk_out (handle, msg, msglen);
1860 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
1861 RDR_to_PC_DataBlock, seqno, 5000, 0);
1866 tpdulen = msglen - 10;
1870 usb_clear_halt (handle->idev, handle->ep_bulk_in);
1871 return CCID_DRIVER_ERR_ABORTED;
1874 if (debug_level > 1)
1875 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
1876 ((msg[11] & 0xc0) == 0x80)? 'R' :
1877 (msg[11] & 0x80)? 'S' : 'I',
1878 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
1879 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
1880 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
1882 if (!(tpdu[1] & 0x80))
1883 { /* This is an I-block. */
1886 { /* last block sent was successful. */
1891 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
1892 { /* Reponse does not match our sequence number. */
1895 /* NAD: DAD=1, SAD=0 */
1896 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
1897 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */
1900 edc = compute_edc (tpdu, tpdulen, use_crc);
1902 tpdu[tpdulen++] = (edc >> 8);
1903 tpdu[tpdulen++] = edc;
1910 p = tpdu + 3; /* Skip the prologue field. */
1911 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
1912 /* fixme: verify the checksum. */
1917 DEBUGOUT_2 ("provided buffer too short for received data "
1919 (unsigned int)n, (unsigned int)maxresplen);
1920 return CCID_DRIVER_ERR_INV_VALUE;
1923 memcpy (resp, p, n);
1929 if (!(tpdu[1] & 0x20))
1930 return 0; /* No chaining requested - ready. */
1934 /* NAD: DAD=1, SAD=0 */
1935 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
1936 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */
1939 edc = compute_edc (tpdu, tpdulen, use_crc);
1941 tpdu[tpdulen++] = (edc >> 8);
1942 tpdu[tpdulen++] = edc;
1944 else if ((tpdu[1] & 0xc0) == 0x80)
1945 { /* This is a R-block. */
1946 if ( (tpdu[1] & 0x0f))
1947 { /* Error: repeat last block */
1950 DEBUGOUT ("3 failed retries\n");
1951 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1954 tpdulen = last_tpdulen;
1956 else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns)
1957 { /* Response does not match our sequence number. */
1958 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
1959 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1962 { /* Send next chunk. */
1970 DEBUGOUT ("unexpected ACK R-block received\n");
1971 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1975 { /* This is a S-block. */
1977 DEBUGOUT_2 ("T=1 S-block %s received cmd=%d\n",
1978 (tpdu[1] & 0x20)? "response": "request",
1980 if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2])
1981 { /* Wait time extension request. */
1982 unsigned char bwi = tpdu[3];
1985 /* NAD: DAD=1, SAD=0 */
1986 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
1987 tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */
1991 edc = compute_edc (tpdu, tpdulen, use_crc);
1993 tpdu[tpdulen++] = (edc >> 8);
1994 tpdu[tpdulen++] = edc;
1995 DEBUGOUT_1 ("T=1 waittime extension of bwi=%d\n", bwi);
1998 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2000 } /* end T=1 protocol loop. */
2006 /* Send the CCID Secure command to the reader. APDU_BUF should
2007 contain the APDU template. PIN_MODE defines how the pin gets
2010 1 := The PIN is ASCII encoded and of variable length. The
2011 length of the PIN entered will be put into Lc by the reader.
2012 The APDU should me made up of 4 bytes without Lc.
2014 PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0
2015 may be used t enable reasonable defaults. PIN_PADLEN should be 0.
2017 When called with RESP and NRESP set to NULL, the function will
2018 merely check whether the reader supports the secure command for the
2019 given APDU and PIN_MODE. */
2021 ccid_transceive_secure (ccid_driver_t handle,
2022 const unsigned char *apdu_buf, size_t apdu_buflen,
2023 int pin_mode, int pinlen_min, int pinlen_max,
2025 unsigned char *resp, size_t maxresplen, size_t *nresp)
2028 unsigned char send_buffer[10+259], recv_buffer[10+259];
2029 unsigned char *msg, *tpdu, *p;
2030 size_t msglen, tpdulen, n;
2031 unsigned char seqno;
2036 testmode = !resp && !nresp;
2039 nresp = &dummy_nresp;
2042 if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1))
2044 else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2))
2045 return CCID_DRIVER_ERR_NOT_SUPPORTED; /* Not yet by our code. */
2047 return CCID_DRIVER_ERR_NO_KEYPAD;
2050 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2052 if (pin_padlen != 0)
2053 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2060 /* Note that the 25 is the maximum value the SPR532 allows. */
2061 if (pinlen_min < 1 || pinlen_min > 25
2062 || pinlen_max < 1 || pinlen_max > 25
2063 || pinlen_min > pinlen_max)
2064 return CCID_DRIVER_ERR_INV_VALUE;
2066 /* We have only tested this with an SCM reader so better don't risk
2067 anything and do not allow the use with other readers. */
2068 if (handle->id_vendor != VENDOR_SCM)
2069 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2072 return 0; /* Success */
2075 if (handle->id_vendor == VENDOR_SCM)
2077 DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n");
2078 rc = send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3,
2084 msg[0] = PC_to_RDR_Secure;
2085 msg[5] = 0; /* slot */
2086 msg[6] = seqno = handle->seqno++;
2087 msg[7] = 4; /* bBWI */
2088 msg[8] = 0; /* RFU */
2089 msg[9] = 0; /* RFU */
2090 msg[10] = 0; /* Perform PIN verification. */
2091 msg[11] = 0; /* Timeout in seconds. */
2092 msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
2093 if (handle->id_vendor == VENDOR_SCM)
2095 /* For the SPR532 the next 2 bytes need to be zero. We do this
2096 for all SCM product. Kudos to Martin Paljak for this
2098 msg[13] = msg[14] = 0;
2102 msg[13] = 0x00; /* bmPINBlockString:
2103 0 bits of pin length to insert.
2104 0 bytes of PIN block size. */
2105 msg[14] = 0x00; /* bmPINLengthFormat:
2106 Units are bytes, position is 0. */
2108 msg[15] = pinlen_min; /* wPINMaxExtraDigit-Minimum. */
2109 msg[16] = pinlen_max; /* wPINMaxExtraDigit-Maximum. */
2110 msg[17] = 0x02; /* bEntryValidationCondition:
2111 Validation key pressed */
2112 if (pinlen_min && pinlen_max && pinlen_min == pinlen_max)
2113 msg[17] |= 0x01; /* Max size reached. */
2114 msg[18] = 0xff; /* bNumberMessage: Default. */
2115 msg[19] = 0x04; /* wLangId-High. */
2116 msg[20] = 0x09; /* wLangId-Low: English FIXME: use the first entry. */
2117 msg[21] = 0; /* bMsgIndex. */
2118 /* bTeoProlog follows: */
2119 msg[22] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2120 msg[23] = ((handle->t1_ns & 1) << 6); /* I-block */
2121 msg[24] = 4; /* apdulen. */
2123 msg[25] = apdu_buf[0]; /* CLA */
2124 msg[26] = apdu_buf[1]; /* INS */
2125 msg[27] = apdu_buf[2]; /* P1 */
2126 msg[28] = apdu_buf[3]; /* P2 */
2128 set_msg_len (msg, msglen - 10);
2130 DEBUGOUT ("sending");
2131 for (i=0; i < msglen; i++)
2132 DEBUGOUT_CONT_1 (" %02X", msg[i]);
2135 rc = bulk_out (handle, msg, msglen);
2140 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2141 RDR_to_PC_DataBlock, seqno, 5000, 0);
2146 tpdulen = msglen - 10;
2150 usb_clear_halt (handle->idev, handle->ep_bulk_in);
2151 return CCID_DRIVER_ERR_ABORTED;
2153 if (debug_level > 1)
2154 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2155 ((msg[11] & 0xc0) == 0x80)? 'R' :
2156 (msg[11] & 0x80)? 'S' : 'I',
2157 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
2158 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2159 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2161 if (!(tpdu[1] & 0x80))
2162 { /* This is an I-block. */
2163 /* Last block sent was successful. */
2166 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
2167 { /* Reponse does not match our sequence number. */
2168 DEBUGOUT ("I-block with wrong seqno received\n");
2169 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2174 p = tpdu + 3; /* Skip the prologue field. */
2175 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
2176 /* fixme: verify the checksum. */
2181 DEBUGOUT_2 ("provided buffer too short for received data "
2183 (unsigned int)n, (unsigned int)maxresplen);
2184 return CCID_DRIVER_ERR_INV_VALUE;
2187 memcpy (resp, p, n);
2193 if (!(tpdu[1] & 0x20))
2194 return 0; /* No chaining requested - ready. */
2196 DEBUGOUT ("chaining requested but not supported for Secure operation\n");
2197 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2199 else if ((tpdu[1] & 0xc0) == 0x80)
2200 { /* This is a R-block. */
2201 if ( (tpdu[1] & 0x0f))
2202 { /* Error: repeat last block */
2203 DEBUGOUT ("No retries supported for Secure operation\n");
2204 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2206 else if (!!(tpdu[1] & 0x10) == handle->t1_ns)
2207 { /* Reponse does not match our sequence number. */
2208 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
2209 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2212 { /* Send next chunk. */
2213 DEBUGOUT ("chaining not supported on Secure operation\n");
2214 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2218 { /* This is a S-block. */
2219 DEBUGOUT_2 ("T=1 S-block %s received cmd=%d for Secure operation\n",
2220 (tpdu[1] & 0x20)? "response": "request",
2222 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2235 print_error (int err)
2242 case 0: p = "success";
2243 case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break;
2244 case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break;
2245 case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break;
2246 case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break;
2247 case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break;
2248 case CCID_DRIVER_ERR_BUSY: p = "busy"; break;
2249 case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break;
2250 case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break;
2251 case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break;
2252 case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break;
2253 case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break;
2254 case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break;
2255 default: sprintf (buf, "0x%05x", err); p = buf; break;
2257 fprintf (stderr, "operation failed: %s\n", p);
2261 print_data (const unsigned char *data, size_t length)
2265 fprintf (stderr, "operation status: %02X%02X\n",
2266 data[length-2], data[length-1]);
2271 fputs (" returned data:", stderr);
2272 for (; length; length--, data++)
2273 fprintf (stderr, " %02X", *data);
2274 putc ('\n', stderr);
2279 print_result (int rc, const unsigned char *data, size_t length)
2284 print_data (data, length);
2288 main (int argc, char **argv)
2292 unsigned int slotstat;
2293 unsigned char result[512];
2296 int verify_123456 = 0;
2308 if ( !strcmp (*argv, "--list"))
2311 p = ccid_get_reader_list ();
2318 else if ( !strcmp (*argv, "--debug"))
2320 ccid_set_debug_level (1);
2323 else if ( !strcmp (*argv, "--no-poll"))
2328 else if ( !strcmp (*argv, "--no-pinpad"))
2333 else if ( !strcmp (*argv, "--verify-123456"))
2342 rc = ccid_open_reader (&ccid, argc? *argv:NULL);
2348 fputs ("getting ATR ...\n", stderr);
2349 rc = ccid_get_atr (ccid, NULL, 0, NULL);
2358 fputs ("getting slot status ...\n", stderr);
2359 rc = ccid_slot_status (ccid, &slotstat);
2369 fputs ("selecting application OpenPGP ....\n", stderr);
2371 static unsigned char apdu[] = {
2372 0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01};
2373 rc = ccid_transceive (ccid,
2375 result, sizeof result, &resultlen);
2376 print_result (rc, result, resultlen);
2383 fputs ("getting OpenPGP DO 0x65 ....\n", stderr);
2385 static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 };
2386 rc = ccid_transceive (ccid, apdu, sizeof apdu,
2387 result, sizeof result, &resultlen);
2388 print_result (rc, result, resultlen);
2397 static unsigned char apdu[] = { 0, 0x20, 0, 0x81 };
2400 if (ccid_transceive_secure (ccid,
2404 fputs ("can't verify using a PIN-Pad reader\n", stderr);
2407 fputs ("verifying CHV1 using the PINPad ....\n", stderr);
2409 rc = ccid_transceive_secure (ccid,
2412 result, sizeof result, &resultlen);
2413 print_result (rc, result, resultlen);
2418 if (verify_123456 && !did_verify)
2420 fputs ("verifying that CHV1 is 123456....\n", stderr);
2422 static unsigned char apdu[] = {0, 0x20, 0, 0x81,
2423 6, '1','2','3','4','5','6'};
2424 rc = ccid_transceive (ccid, apdu, sizeof apdu,
2425 result, sizeof result, &resultlen);
2426 print_result (rc, result, resultlen);
2432 fputs ("getting OpenPGP DO 0x5E ....\n", stderr);
2434 static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 };
2435 rc = ccid_transceive (ccid, apdu, sizeof apdu,
2436 result, sizeof result, &resultlen);
2437 print_result (rc, result, resultlen);
2441 ccid_close_reader (ccid);
2448 * compile-command: "gcc -DTEST -Wall -I/usr/local/include -lusb -g ccid-driver.c"
2452 #endif /*HAVE_LIBUSB*/
2454 #endif /* LIBRFID_FIRMWARE */