1 /* ccid-driver.c - USB ChipCardInterfaceDevices driver
2  * Copyright (C) 2003, 2004, 2005, 2006, 2007
3  *               2008, 2009, 2013  Free Software Foundation, Inc.
4  * Written by Werner Koch.
5  *
6  * This file is part of GnuPG.
7  *
8  * GnuPG is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuPG is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, see <https://www.gnu.org/licenses/>.
20  *
21  * ALTERNATIVELY, this file may be distributed under the terms of the
22  * following license, in which case the provisions of this license are
23  * required INSTEAD OF the GNU General Public License. If you wish to
24  * allow use of your version of this file only under the terms of the
25  * GNU General Public License, and not to allow others to use your
26  * version of this file under the terms of the following license,
27  * indicate your decision by deleting this paragraph and the license
28  * below.
29  *
30  * Redistribution and use in source and binary forms, with or without
31  * modification, are permitted provided that the following conditions
32  * are met:
33  * 1. Redistributions of source code must retain the above copyright
34  *    notice, and the entire permission notice in its entirety,
35  *    including the disclaimer of warranties.
36  * 2. Redistributions in binary form must reproduce the above copyright
37  *    notice, this list of conditions and the following disclaimer in the
38  *    documentation and/or other materials provided with the distribution.
39  * 3. The name of the author may not be used to endorse or promote
40  *    products derived from this software without specific prior
41  *    written permission.
42  *
43  * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
44  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
45  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
46  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
47  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
48  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
49  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
51  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
52  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
53  * OF THE POSSIBILITY OF SUCH DAMAGE.
54  */
55 
56 
57 /* CCID (ChipCardInterfaceDevices) is a specification for accessing
58    smartcard via a reader connected to the USB.
59 
60    This is a limited driver allowing to use some CCID drivers directly
61    without any other specila drivers. This is a fallback driver to be
62    used when nothing else works or the system should be kept minimal
63    for security reasons.  It makes use of the libusb library to gain
64    portable access to USB.
65 
66    This driver has been tested with the SCM SCR335 and SPR532
67    smartcard readers and requires that a reader implements APDU or
68    TPDU level exchange and does fully automatic initialization.
69 */
70 
71 #ifdef HAVE_CONFIG_H
72 # include <config.h>
73 #endif
74 
75 #if defined(HAVE_LIBUSB) || defined(TEST)
76 
77 #include <errno.h>
78 #include <stdio.h>
79 #include <stdlib.h>
80 #include <string.h>
81 #include <sys/types.h>
82 #include <sys/stat.h>
83 #include <fcntl.h>
84 #include <time.h>
85 #include <unistd.h>
86 #ifdef HAVE_NPTH
87 # include <npth.h>
88 #endif /*HAVE_NPTH*/
89 
90 #include <libusb.h>
91 
92 #include "scdaemon.h"
93 #include "iso7816.h"
94 #define CCID_DRIVER_INCLUDE_USB_IDS 1
95 #include "ccid-driver.h"
96 
97 #define DRVNAME "ccid-driver: "
98 
99 /* Max length of buffer with out CCID message header of 10-byte
100    Sending: 547 for RSA-4096 key import
101         APDU size = 540 (24+4+256+256)
102         command + lc + le = 4 + 3 + 0
103    Sending: write data object of cardholder certificate
104         APDU size = 2048
105         command + lc + le = 4 + 3 + 0
106    Receiving: 2048 for cardholder certificate
107 */
108 #define CCID_MAX_BUF (2048+7+10)
109 
110 /* CCID command timeout.  */
111 #define CCID_CMD_TIMEOUT (5*1000)
112 
113 /* Depending on how this source is used we either define our error
114  * output to go to stderr or to the GnuPG based logging functions.  We
115  * use the latter when GNUPG_MAJOR_VERSION is defined.  */
116 #if defined(GNUPG_MAJOR_VERSION)
117 #  include "scdaemon.h"
118 
119 # define DEBUGOUT(t)         do { if (debug_level) \
120                                   log_debug (DRVNAME t); } while (0)
121 # define DEBUGOUT_1(t,a)     do { if (debug_level) \
122                                   log_debug (DRVNAME t,(a)); } while (0)
123 # define DEBUGOUT_2(t,a,b)   do { if (debug_level) \
124                                   log_debug (DRVNAME t,(a),(b)); } while (0)
125 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
126                                   log_debug (DRVNAME t,(a),(b),(c));} while (0)
127 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
128                               log_debug (DRVNAME t,(a),(b),(c),(d));} while (0)
129 # define DEBUGOUT_CONT(t)    do { if (debug_level) \
130                                   log_printf (t); } while (0)
131 # define DEBUGOUT_CONT_1(t,a)  do { if (debug_level) \
132                                   log_printf (t,(a)); } while (0)
133 # define DEBUGOUT_CONT_2(t,a,b)   do { if (debug_level) \
134                                   log_printf (t,(a),(b)); } while (0)
135 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
136                                   log_printf (t,(a),(b),(c)); } while (0)
137 # define DEBUGOUT_LF()       do { if (debug_level) \
138                                   log_printf ("\n"); } while (0)
139 
140 #else /* Other usage of this source - don't use gnupg specifics. */
141 
142 # define DEBUGOUT(t)          do { if (debug_level) \
143                      fprintf (stderr, DRVNAME t); } while (0)
144 # define DEBUGOUT_1(t,a)      do { if (debug_level) \
145                      fprintf (stderr, DRVNAME t, (a)); } while (0)
146 # define DEBUGOUT_2(t,a,b)    do { if (debug_level) \
147                      fprintf (stderr, DRVNAME t, (a), (b)); } while (0)
148 # define DEBUGOUT_3(t,a,b,c)  do { if (debug_level) \
149                      fprintf (stderr, DRVNAME t, (a), (b), (c)); } while (0)
150 # define DEBUGOUT_4(t,a,b,c,d)  do { if (debug_level) \
151                      fprintf (stderr, DRVNAME t, (a), (b), (c), (d));} while(0)
152 # define DEBUGOUT_CONT(t)     do { if (debug_level) \
153                      fprintf (stderr, t); } while (0)
154 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
155                      fprintf (stderr, t, (a)); } while (0)
156 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
157                      fprintf (stderr, t, (a), (b)); } while (0)
158 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
159                      fprintf (stderr, t, (a), (b), (c)); } while (0)
160 # define DEBUGOUT_LF()        do { if (debug_level) \
161                      putc ('\n', stderr); } while (0)
162 
163 #endif /* This source is not used by scdaemon. */
164 
165 
166 #ifndef EAGAIN
167 #define EAGAIN  EWOULDBLOCK
168 #endif
169 
170 
171 
172 enum {
173   RDR_to_PC_NotifySlotChange= 0x50,
174   RDR_to_PC_HardwareError   = 0x51,
175 
176   PC_to_RDR_SetParameters   = 0x61,
177   PC_to_RDR_IccPowerOn      = 0x62,
178   PC_to_RDR_IccPowerOff     = 0x63,
179   PC_to_RDR_GetSlotStatus   = 0x65,
180   PC_to_RDR_Secure          = 0x69,
181   PC_to_RDR_T0APDU          = 0x6a,
182   PC_to_RDR_Escape          = 0x6b,
183   PC_to_RDR_GetParameters   = 0x6c,
184   PC_to_RDR_ResetParameters = 0x6d,
185   PC_to_RDR_IccClock        = 0x6e,
186   PC_to_RDR_XfrBlock        = 0x6f,
187   PC_to_RDR_Mechanical      = 0x71,
188   PC_to_RDR_Abort           = 0x72,
189   PC_to_RDR_SetDataRate     = 0x73,
190 
191   RDR_to_PC_DataBlock       = 0x80,
192   RDR_to_PC_SlotStatus      = 0x81,
193   RDR_to_PC_Parameters      = 0x82,
194   RDR_to_PC_Escape          = 0x83,
195   RDR_to_PC_DataRate        = 0x84
196 };
197 
198 
199 /* Two macro to detect whether a CCID command has failed and to get
200    the error code.  These macros assume that we can access the
201    mandatory first 10 bytes of a CCID message in BUF. */
202 #define CCID_COMMAND_FAILED(buf) ((buf)[7] & 0x40)
203 #define CCID_ERROR_CODE(buf)     (((unsigned char *)(buf))[8])
204 
205 
206 /* Store information on the driver's state.  A pointer to such a
207    structure is used as handle for most functions. */
208 struct ccid_driver_s
209 {
210   libusb_device_handle *idev;
211   unsigned int bai;
212   unsigned short id_vendor;
213   unsigned short id_product;
214   int ifc_no;
215   int ep_bulk_out;
216   int ep_bulk_in;
217   int ep_intr;
218   int seqno;
219   unsigned char t1_ns;
220   unsigned char t1_nr;
221   unsigned char nonnull_nad;
222   int max_ifsd;
223   int max_ccid_msglen;
224   int ifsc;
225   unsigned char apdu_level:2;     /* Reader supports short APDU level
226                                      exchange.  With a value of 2 short
227                                      and extended level is supported.*/
228   unsigned int auto_voltage:1;
229   unsigned int auto_param:1;
230   unsigned int auto_pps:1;
231   unsigned int auto_ifsd:1;
232   unsigned int has_pinpad:2;
233   unsigned int enodev_seen:1;
234   int powered_off;
235 
236   time_t last_progress; /* Last time we sent progress line.  */
237 
238   /* The progress callback and its first arg as supplied to
239      ccid_set_progress_cb.  */
240   void (*progress_cb)(void *, const char *, int, int, int);
241   void *progress_cb_arg;
242 
243   void (*prompt_cb)(void *, int);
244   void *prompt_cb_arg;
245 
246   unsigned char intr_buf[64];
247   struct libusb_transfer *transfer;
248 };
249 
250 
251 static int initialized_usb; /* Tracks whether USB has been initialized. */
252 static int debug_level;     /* Flag to control the debug output.
253                                0 = No debugging
254                                1 = USB I/O info
255                                2 = Level 1 + T=1 protocol tracing
256                                3 = Level 2 + USB/I/O tracing of SlotStatus.
257                               */
258 static int ccid_usb_thread_is_alive;
259 
260 
261 static unsigned int compute_edc (const unsigned char *data, size_t datalen,
262                                  int use_crc);
263 static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
264                      int no_debug);
265 static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
266                     size_t *nread, int expected_type, int seqno, int timeout,
267                     int no_debug);
268 static int abort_cmd (ccid_driver_t handle, int seqno, int init);
269 static int send_escape_cmd (ccid_driver_t handle, const unsigned char *data,
270                             size_t datalen, unsigned char *result,
271                             size_t resultmax, size_t *resultlen);
272 
273 
274 static int
map_libusb_error(int usberr)275 map_libusb_error (int usberr)
276 {
277   switch (usberr)
278     {
279     case 0:                     return 0;
280     case LIBUSB_ERROR_IO:       return CCID_DRIVER_ERR_USB_IO;
281     case LIBUSB_ERROR_ACCESS:   return CCID_DRIVER_ERR_USB_ACCESS;
282     case LIBUSB_ERROR_NO_DEVICE:return CCID_DRIVER_ERR_USB_NO_DEVICE;
283     case LIBUSB_ERROR_BUSY:     return CCID_DRIVER_ERR_USB_BUSY;
284     case LIBUSB_ERROR_TIMEOUT:  return CCID_DRIVER_ERR_USB_TIMEOUT;
285     case LIBUSB_ERROR_OVERFLOW: return CCID_DRIVER_ERR_USB_OVERFLOW;
286     }
287   return CCID_DRIVER_ERR_USB_OTHER;
288 }
289 
290 
291 /* Convert a little endian stored 4 byte value into an unsigned
292    integer. */
293 static unsigned int
convert_le_u32(const unsigned char * buf)294 convert_le_u32 (const unsigned char *buf)
295 {
296   return buf[0] | (buf[1] << 8) | (buf[2] << 16) | ((unsigned int)buf[3] << 24);
297 }
298 
299 
300 /* Convert a little endian stored 2 byte value into an unsigned
301    integer. */
302 static unsigned int
convert_le_u16(const unsigned char * buf)303 convert_le_u16 (const unsigned char *buf)
304 {
305   return buf[0] | (buf[1] << 8);
306 }
307 
308 static void
set_msg_len(unsigned char * msg,unsigned int length)309 set_msg_len (unsigned char *msg, unsigned int length)
310 {
311   msg[1] = length;
312   msg[2] = length >> 8;
313   msg[3] = length >> 16;
314   msg[4] = length >> 24;
315 }
316 
317 
318 static void
print_progress(ccid_driver_t handle)319 print_progress (ccid_driver_t handle)
320 {
321   time_t ct = time (NULL);
322 
323   /* We don't want to print progress lines too often. */
324   if (ct == handle->last_progress)
325     return;
326 
327   if (handle->progress_cb)
328     handle->progress_cb (handle->progress_cb_arg, "card_busy", 'w', 0, 0);
329 
330   handle->last_progress = ct;
331 }
332 
333 
334 
335 /* Pint an error message for a failed CCID command including a textual
336    error code.  MSG shall be the CCID message at a minimum of 10 bytes. */
337 static void
print_command_failed(const unsigned char * msg)338 print_command_failed (const unsigned char *msg)
339 {
340   const char *t;
341   char buffer[100];
342   int ec;
343 
344   if (!debug_level)
345     return;
346 
347   ec = CCID_ERROR_CODE (msg);
348   switch (ec)
349     {
350     case 0x00: t = "Command not supported"; break;
351 
352     case 0xE0: t = "Slot busy"; break;
353     case 0xEF: t = "PIN cancelled"; break;
354     case 0xF0: t = "PIN timeout"; break;
355 
356     case 0xF2: t = "Automatic sequence ongoing"; break;
357     case 0xF3: t = "Deactivated Protocol"; break;
358     case 0xF4: t = "Procedure byte conflict"; break;
359     case 0xF5: t = "ICC class not supported"; break;
360     case 0xF6: t = "ICC protocol not supported"; break;
361     case 0xF7: t = "Bad checksum in ATR"; break;
362     case 0xF8: t = "Bad TS in ATR"; break;
363 
364     case 0xFB: t = "An all inclusive hardware error occurred"; break;
365     case 0xFC: t = "Overrun error while talking to the ICC"; break;
366     case 0xFD: t = "Parity error while talking to the ICC"; break;
367     case 0xFE: t = "CCID timed out while talking to the ICC"; break;
368     case 0xFF: t = "Host aborted the current activity"; break;
369 
370     default:
371       if (ec > 0 && ec < 128)
372         sprintf (buffer, "Parameter error at offset %d", ec);
373       else
374         sprintf (buffer, "Error code %02X", ec);
375       t = buffer;
376       break;
377     }
378   DEBUGOUT_1 ("CCID command failed: %s\n", t);
379 }
380 
381 
382 static void
print_pr_data(const unsigned char * data,size_t datalen,size_t off)383 print_pr_data (const unsigned char *data, size_t datalen, size_t off)
384 {
385   int any = 0;
386 
387   for (; off < datalen; off++)
388     {
389       if (!any || !(off % 16))
390         {
391           if (any)
392             DEBUGOUT_LF ();
393           DEBUGOUT_1 ("  [%04lu] ", (unsigned long) off);
394         }
395       DEBUGOUT_CONT_1 (" %02X", data[off]);
396       any = 1;
397     }
398   if (any && (off % 16))
399     DEBUGOUT_LF ();
400 }
401 
402 
403 static void
print_p2r_header(const char * name,const unsigned char * msg,size_t msglen)404 print_p2r_header (const char *name, const unsigned char *msg, size_t msglen)
405 {
406   DEBUGOUT_1 ("%s:\n", name);
407   if (msglen < 7)
408     return;
409   DEBUGOUT_1 ("  dwLength ..........: %u\n", convert_le_u32 (msg+1));
410   DEBUGOUT_1 ("  bSlot .............: %u\n", msg[5]);
411   DEBUGOUT_1 ("  bSeq ..............: %u\n", msg[6]);
412 }
413 
414 
415 static void
print_p2r_iccpoweron(const unsigned char * msg,size_t msglen)416 print_p2r_iccpoweron (const unsigned char *msg, size_t msglen)
417 {
418   print_p2r_header ("PC_to_RDR_IccPowerOn", msg, msglen);
419   if (msglen < 10)
420     return;
421   DEBUGOUT_2 ("  bPowerSelect ......: 0x%02x (%s)\n", msg[7],
422               msg[7] == 0? "auto":
423               msg[7] == 1? "5.0 V":
424               msg[7] == 2? "3.0 V":
425               msg[7] == 3? "1.8 V":"");
426   print_pr_data (msg, msglen, 8);
427 }
428 
429 
430 static void
print_p2r_iccpoweroff(const unsigned char * msg,size_t msglen)431 print_p2r_iccpoweroff (const unsigned char *msg, size_t msglen)
432 {
433   print_p2r_header ("PC_to_RDR_IccPowerOff", msg, msglen);
434   print_pr_data (msg, msglen, 7);
435 }
436 
437 
438 static void
print_p2r_getslotstatus(const unsigned char * msg,size_t msglen)439 print_p2r_getslotstatus (const unsigned char *msg, size_t msglen)
440 {
441   print_p2r_header ("PC_to_RDR_GetSlotStatus", msg, msglen);
442   print_pr_data (msg, msglen, 7);
443 }
444 
445 
446 static void
print_p2r_xfrblock(const unsigned char * msg,size_t msglen)447 print_p2r_xfrblock (const unsigned char *msg, size_t msglen)
448 {
449   unsigned int val;
450 
451   print_p2r_header ("PC_to_RDR_XfrBlock", msg, msglen);
452   if (msglen < 10)
453     return;
454   DEBUGOUT_1 ("  bBWI ..............: 0x%02x\n", msg[7]);
455   val = convert_le_u16 (msg+8);
456   DEBUGOUT_2 ("  wLevelParameter ...: 0x%04x%s\n", val,
457               val == 1? " (continued)":
458               val == 2? " (continues+ends)":
459               val == 3? " (continues+continued)":
460               val == 16? " (DataBlock-expected)":"");
461   print_pr_data (msg, msglen, 10);
462 }
463 
464 
465 static void
print_p2r_getparameters(const unsigned char * msg,size_t msglen)466 print_p2r_getparameters (const unsigned char *msg, size_t msglen)
467 {
468   print_p2r_header ("PC_to_RDR_GetParameters", msg, msglen);
469   print_pr_data (msg, msglen, 7);
470 }
471 
472 
473 static void
print_p2r_resetparameters(const unsigned char * msg,size_t msglen)474 print_p2r_resetparameters (const unsigned char *msg, size_t msglen)
475 {
476   print_p2r_header ("PC_to_RDR_ResetParameters", msg, msglen);
477   print_pr_data (msg, msglen, 7);
478 }
479 
480 
481 static void
print_p2r_setparameters(const unsigned char * msg,size_t msglen)482 print_p2r_setparameters (const unsigned char *msg, size_t msglen)
483 {
484   print_p2r_header ("PC_to_RDR_SetParameters", msg, msglen);
485   if (msglen < 10)
486     return;
487   DEBUGOUT_1 ("  bProtocolNum ......: 0x%02x\n", msg[7]);
488   print_pr_data (msg, msglen, 8);
489 }
490 
491 
492 static void
print_p2r_escape(const unsigned char * msg,size_t msglen)493 print_p2r_escape (const unsigned char *msg, size_t msglen)
494 {
495   print_p2r_header ("PC_to_RDR_Escape", msg, msglen);
496   print_pr_data (msg, msglen, 7);
497 }
498 
499 
500 static void
print_p2r_iccclock(const unsigned char * msg,size_t msglen)501 print_p2r_iccclock (const unsigned char *msg, size_t msglen)
502 {
503   print_p2r_header ("PC_to_RDR_IccClock", msg, msglen);
504   if (msglen < 10)
505     return;
506   DEBUGOUT_1 ("  bClockCommand .....: 0x%02x\n", msg[7]);
507   print_pr_data (msg, msglen, 8);
508 }
509 
510 
511 static void
print_p2r_to0apdu(const unsigned char * msg,size_t msglen)512 print_p2r_to0apdu (const unsigned char *msg, size_t msglen)
513 {
514   print_p2r_header ("PC_to_RDR_T0APDU", msg, msglen);
515   if (msglen < 10)
516     return;
517   DEBUGOUT_1 ("  bmChanges .........: 0x%02x\n", msg[7]);
518   DEBUGOUT_1 ("  bClassGetResponse .: 0x%02x\n", msg[8]);
519   DEBUGOUT_1 ("  bClassEnvelope ....: 0x%02x\n", msg[9]);
520   print_pr_data (msg, msglen, 10);
521 }
522 
523 
524 static void
print_p2r_secure(const unsigned char * msg,size_t msglen)525 print_p2r_secure (const unsigned char *msg, size_t msglen)
526 {
527   unsigned int val;
528 
529   print_p2r_header ("PC_to_RDR_Secure", msg, msglen);
530   if (msglen < 10)
531     return;
532   DEBUGOUT_1 ("  bBMI ..............: 0x%02x\n", msg[7]);
533   val = convert_le_u16 (msg+8);
534   DEBUGOUT_2 ("  wLevelParameter ...: 0x%04x%s\n", val,
535               val == 1? " (continued)":
536               val == 2? " (continues+ends)":
537               val == 3? " (continues+continued)":
538               val == 16? " (DataBlock-expected)":"");
539   print_pr_data (msg, msglen, 10);
540 }
541 
542 
543 static void
print_p2r_mechanical(const unsigned char * msg,size_t msglen)544 print_p2r_mechanical (const unsigned char *msg, size_t msglen)
545 {
546   print_p2r_header ("PC_to_RDR_Mechanical", msg, msglen);
547   if (msglen < 10)
548     return;
549   DEBUGOUT_1 ("  bFunction .........: 0x%02x\n", msg[7]);
550   print_pr_data (msg, msglen, 8);
551 }
552 
553 
554 static void
print_p2r_abort(const unsigned char * msg,size_t msglen)555 print_p2r_abort (const unsigned char *msg, size_t msglen)
556 {
557   print_p2r_header ("PC_to_RDR_Abort", msg, msglen);
558   print_pr_data (msg, msglen, 7);
559 }
560 
561 
562 static void
print_p2r_setdatarate(const unsigned char * msg,size_t msglen)563 print_p2r_setdatarate (const unsigned char *msg, size_t msglen)
564 {
565   print_p2r_header ("PC_to_RDR_SetDataRate", msg, msglen);
566   if (msglen < 10)
567     return;
568   print_pr_data (msg, msglen, 7);
569 }
570 
571 
572 static void
print_p2r_unknown(const unsigned char * msg,size_t msglen)573 print_p2r_unknown (const unsigned char *msg, size_t msglen)
574 {
575   print_p2r_header ("Unknown PC_to_RDR command", msg, msglen);
576   if (msglen < 10)
577     return;
578   print_pr_data (msg, msglen, 0);
579 }
580 
581 
582 static void
print_r2p_header(const char * name,const unsigned char * msg,size_t msglen)583 print_r2p_header (const char *name, const unsigned char *msg, size_t msglen)
584 {
585   DEBUGOUT_1 ("%s:\n", name);
586   if (msglen < 9)
587     return;
588   DEBUGOUT_1 ("  dwLength ..........: %u\n", convert_le_u32 (msg+1));
589   DEBUGOUT_1 ("  bSlot .............: %u\n", msg[5]);
590   DEBUGOUT_1 ("  bSeq ..............: %u\n", msg[6]);
591   DEBUGOUT_1 ("  bStatus ...........: %u\n", msg[7]);
592   if (msg[8])
593     DEBUGOUT_1 ("  bError ............: %u\n", msg[8]);
594 }
595 
596 
597 static void
print_r2p_datablock(const unsigned char * msg,size_t msglen)598 print_r2p_datablock (const unsigned char *msg, size_t msglen)
599 {
600   print_r2p_header ("RDR_to_PC_DataBlock", msg, msglen);
601   if (msglen < 10)
602     return;
603   if (msg[9])
604     DEBUGOUT_2 ("  bChainParameter ...: 0x%02x%s\n", msg[9],
605                 msg[9] == 1? " (continued)":
606                 msg[9] == 2? " (continues+ends)":
607                 msg[9] == 3? " (continues+continued)":
608                 msg[9] == 16? " (XferBlock-expected)":"");
609   print_pr_data (msg, msglen, 10);
610 }
611 
612 
613 static void
print_r2p_slotstatus(const unsigned char * msg,size_t msglen)614 print_r2p_slotstatus (const unsigned char *msg, size_t msglen)
615 {
616   print_r2p_header ("RDR_to_PC_SlotStatus", msg, msglen);
617   if (msglen < 10)
618     return;
619   DEBUGOUT_2 ("  bClockStatus ......: 0x%02x%s\n", msg[9],
620               msg[9] == 0? " (running)":
621               msg[9] == 1? " (stopped-L)":
622               msg[9] == 2? " (stopped-H)":
623               msg[9] == 3? " (stopped)":"");
624   print_pr_data (msg, msglen, 10);
625 }
626 
627 
628 static void
print_r2p_parameters(const unsigned char * msg,size_t msglen)629 print_r2p_parameters (const unsigned char *msg, size_t msglen)
630 {
631   print_r2p_header ("RDR_to_PC_Parameters", msg, msglen);
632   if (msglen < 10)
633     return;
634 
635   DEBUGOUT_1 ("  protocol ..........: T=%d\n", msg[9]);
636   if (msglen == 17 && msg[9] == 1)
637     {
638       /* Protocol T=1.  */
639       DEBUGOUT_1 ("  bmFindexDindex ....: %02X\n", msg[10]);
640       DEBUGOUT_1 ("  bmTCCKST1 .........: %02X\n", msg[11]);
641       DEBUGOUT_1 ("  bGuardTimeT1 ......: %02X\n", msg[12]);
642       DEBUGOUT_1 ("  bmWaitingIntegersT1: %02X\n", msg[13]);
643       DEBUGOUT_1 ("  bClockStop ........: %02X\n", msg[14]);
644       DEBUGOUT_1 ("  bIFSC .............: %d\n", msg[15]);
645       DEBUGOUT_1 ("  bNadValue .........: %d\n", msg[16]);
646     }
647   else
648     print_pr_data (msg, msglen, 10);
649 }
650 
651 
652 static void
print_r2p_escape(const unsigned char * msg,size_t msglen)653 print_r2p_escape (const unsigned char *msg, size_t msglen)
654 {
655   print_r2p_header ("RDR_to_PC_Escape", msg, msglen);
656   if (msglen < 10)
657     return;
658   DEBUGOUT_1 ("  buffer[9] .........: %02X\n", msg[9]);
659   print_pr_data (msg, msglen, 10);
660 }
661 
662 
663 static void
print_r2p_datarate(const unsigned char * msg,size_t msglen)664 print_r2p_datarate (const unsigned char *msg, size_t msglen)
665 {
666   print_r2p_header ("RDR_to_PC_DataRate", msg, msglen);
667   if (msglen < 10)
668     return;
669   if (msglen >= 18)
670     {
671       DEBUGOUT_1 ("  dwClockFrequency ..: %u\n", convert_le_u32 (msg+10));
672       DEBUGOUT_1 ("  dwDataRate ..... ..: %u\n", convert_le_u32 (msg+14));
673       print_pr_data (msg, msglen, 18);
674     }
675   else
676     print_pr_data (msg, msglen, 10);
677 }
678 
679 
680 static void
print_r2p_unknown(const unsigned char * msg,size_t msglen)681 print_r2p_unknown (const unsigned char *msg, size_t msglen)
682 {
683   print_r2p_header ("Unknown RDR_to_PC command", msg, msglen);
684   if (msglen < 10)
685     return;
686   DEBUGOUT_1 ("  bMessageType ......: %02X\n", msg[0]);
687   DEBUGOUT_1 ("  buffer[9] .........: %02X\n", msg[9]);
688   print_pr_data (msg, msglen, 10);
689 }
690 
691 
692 /* Parse a CCID descriptor, optionally print all available features
693    and test whether this reader is usable by this driver.  Returns 0
694    if it is usable.
695 
696    Note, that this code is based on the one in lsusb.c of the
697    usb-utils package, I wrote on 2003-09-01. -wk. */
698 static int
parse_ccid_descriptor(ccid_driver_t handle,unsigned short bcd_device,const unsigned char * buf,size_t buflen)699 parse_ccid_descriptor (ccid_driver_t handle, unsigned short bcd_device,
700                        const unsigned char *buf, size_t buflen)
701 {
702   unsigned int i;
703   unsigned int us;
704   int have_t1 = 0, have_tpdu=0;
705 
706   handle->nonnull_nad = 0;
707   handle->auto_ifsd = 0;
708   handle->max_ifsd = 32;
709   handle->has_pinpad = 0;
710   handle->apdu_level = 0;
711   handle->auto_voltage = 0;
712   handle->auto_param = 0;
713   handle->auto_pps = 0;
714   DEBUGOUT_3 ("idVendor: %04X  idProduct: %04X  bcdDevice: %04X\n",
715               handle->id_vendor, handle->id_product, bcd_device);
716   if (buflen < 54 || buf[0] < 54)
717     {
718       DEBUGOUT ("CCID device descriptor is too short\n");
719       return -1;
720     }
721 
722   DEBUGOUT   ("ChipCard Interface Descriptor:\n");
723   DEBUGOUT_1 ("  bLength             %5u\n", buf[0]);
724   DEBUGOUT_1 ("  bDescriptorType     %5u\n", buf[1]);
725   DEBUGOUT_2 ("  bcdCCID             %2x.%02x", buf[3], buf[2]);
726     if (buf[3] != 1 || buf[2] != 0)
727       DEBUGOUT_CONT("  (Warning: Only accurate for version 1.0)");
728   DEBUGOUT_LF ();
729 
730   DEBUGOUT_1 ("  nMaxSlotIndex       %5u\n", buf[4]);
731   DEBUGOUT_2 ("  bVoltageSupport     %5u  %s\n",
732               buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V"
733                        : buf[5] == 3? "1.8V":"?"));
734 
735   us = convert_le_u32 (buf+6);
736   DEBUGOUT_1 ("  dwProtocols         %5u ", us);
737   if ((us & 1))
738     DEBUGOUT_CONT (" T=0");
739   if ((us & 2))
740     {
741       DEBUGOUT_CONT (" T=1");
742       have_t1 = 1;
743     }
744   if ((us & ~3))
745     DEBUGOUT_CONT (" (Invalid values detected)");
746   DEBUGOUT_LF ();
747 
748   us = convert_le_u32(buf+10);
749   DEBUGOUT_1 ("  dwDefaultClock      %5u\n", us);
750   us = convert_le_u32(buf+14);
751   DEBUGOUT_1 ("  dwMaxiumumClock     %5u\n", us);
752   DEBUGOUT_1 ("  bNumClockSupported  %5u\n", buf[18]);
753   us = convert_le_u32(buf+19);
754   DEBUGOUT_1 ("  dwDataRate        %7u bps\n", us);
755   us = convert_le_u32(buf+23);
756   DEBUGOUT_1 ("  dwMaxDataRate     %7u bps\n", us);
757   DEBUGOUT_1 ("  bNumDataRatesSupp.  %5u\n", buf[27]);
758 
759   us = convert_le_u32(buf+28);
760   DEBUGOUT_1 ("  dwMaxIFSD           %5u\n", us);
761   handle->max_ifsd = us;
762 
763   us = convert_le_u32(buf+32);
764   DEBUGOUT_1 ("  dwSyncProtocols  %08X ", us);
765   if ((us&1))
766     DEBUGOUT_CONT ( " 2-wire");
767   if ((us&2))
768     DEBUGOUT_CONT ( " 3-wire");
769   if ((us&4))
770     DEBUGOUT_CONT ( " I2C");
771   DEBUGOUT_LF ();
772 
773   us = convert_le_u32(buf+36);
774   DEBUGOUT_1 ("  dwMechanical     %08X ", us);
775   if ((us & 1))
776     DEBUGOUT_CONT (" accept");
777   if ((us & 2))
778     DEBUGOUT_CONT (" eject");
779   if ((us & 4))
780     DEBUGOUT_CONT (" capture");
781   if ((us & 8))
782     DEBUGOUT_CONT (" lock");
783   DEBUGOUT_LF ();
784 
785   us = convert_le_u32(buf+40);
786   DEBUGOUT_1 ("  dwFeatures       %08X\n", us);
787   if ((us & 0x0002))
788     {
789       DEBUGOUT ("    Auto configuration based on ATR (assumes auto voltage)\n");
790       handle->auto_voltage = 1;
791     }
792   if ((us & 0x0004))
793     DEBUGOUT ("    Auto activation on insert\n");
794   if ((us & 0x0008))
795     {
796       DEBUGOUT ("    Auto voltage selection\n");
797       handle->auto_voltage = 1;
798     }
799   if ((us & 0x0010))
800     DEBUGOUT ("    Auto clock change\n");
801   if ((us & 0x0020))
802     DEBUGOUT ("    Auto baud rate change\n");
803   if ((us & 0x0040))
804     {
805       DEBUGOUT ("    Auto parameter negotiation made by CCID\n");
806       handle->auto_param = 1;
807     }
808   else if ((us & 0x0080))
809     {
810       DEBUGOUT ("    Auto PPS made by CCID\n");
811       handle->auto_pps = 1;
812     }
813   if ((us & (0x0040 | 0x0080)) == (0x0040 | 0x0080))
814     DEBUGOUT ("    WARNING: conflicting negotiation features\n");
815 
816   if ((us & 0x0100))
817     DEBUGOUT ("    CCID can set ICC in clock stop mode\n");
818   if ((us & 0x0200))
819     {
820       DEBUGOUT ("    NAD value other than 0x00 accepted\n");
821       handle->nonnull_nad = 1;
822     }
823   if ((us & 0x0400))
824     {
825       DEBUGOUT ("    Auto IFSD exchange\n");
826       handle->auto_ifsd = 1;
827     }
828 
829   if ((us & 0x00010000))
830     {
831       DEBUGOUT ("    TPDU level exchange\n");
832       have_tpdu = 1;
833     }
834   else if ((us & 0x00020000))
835     {
836       DEBUGOUT ("    Short APDU level exchange\n");
837       handle->apdu_level = 1;
838     }
839   else if ((us & 0x00040000))
840     {
841       DEBUGOUT ("    Short and extended APDU level exchange\n");
842       handle->apdu_level = 2;
843     }
844   else if ((us & 0x00070000))
845     DEBUGOUT ("    WARNING: conflicting exchange levels\n");
846 
847   us = convert_le_u32(buf+44);
848   DEBUGOUT_1 ("  dwMaxCCIDMsgLen     %5u\n", us);
849   handle->max_ccid_msglen = us;
850 
851   DEBUGOUT (  "  bClassGetResponse    ");
852   if (buf[48] == 0xff)
853     DEBUGOUT_CONT ("echo\n");
854   else
855     DEBUGOUT_CONT_1 ("  %02X\n", buf[48]);
856 
857   DEBUGOUT (  "  bClassEnvelope       ");
858   if (buf[49] == 0xff)
859     DEBUGOUT_CONT ("echo\n");
860   else
861     DEBUGOUT_CONT_1 ("  %02X\n", buf[48]);
862 
863   DEBUGOUT (  "  wlcdLayout           ");
864   if (!buf[50] && !buf[51])
865     DEBUGOUT_CONT ("none\n");
866   else
867     DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]);
868 
869   DEBUGOUT_1 ("  bPINSupport         %5u ", buf[52]);
870   if ((buf[52] & 1))
871     {
872       DEBUGOUT_CONT ( " verification");
873       handle->has_pinpad |= 1;
874     }
875   if ((buf[52] & 2))
876     {
877       DEBUGOUT_CONT ( " modification");
878       handle->has_pinpad |= 2;
879     }
880   DEBUGOUT_LF ();
881 
882   DEBUGOUT_1 ("  bMaxCCIDBusySlots   %5u\n", buf[53]);
883 
884   if (buf[0] > 54)
885     {
886       DEBUGOUT ("  junk             ");
887       for (i=54; i < buf[0]-54; i++)
888         DEBUGOUT_CONT_1 (" %02X", buf[i]);
889       DEBUGOUT_LF ();
890     }
891 
892   if (!have_t1 || !(have_tpdu  || handle->apdu_level))
893     {
894       DEBUGOUT ("this drivers requires that the reader supports T=1, "
895                 "TPDU or APDU level exchange - this is not available\n");
896       return -1;
897     }
898 
899 
900   /* SCM drivers get stuck in their internal USB stack if they try to
901      send a frame of n*wMaxPacketSize back to us.  Given that
902      wMaxPacketSize is 64 for these readers we set the IFSD to a value
903      lower than that:
904         64 - 10 CCID header -  4 T1frame - 2 reserved = 48
905      Product Ids:
906          0xe001 - SCR 331
907          0x5111 - SCR 331-DI
908          0x5115 - SCR 335
909          0xe003 - SPR 532
910      The
911          0x5117 - SCR 3320 USB ID-000 reader
912      seems to be very slow but enabling this workaround boosts the
913      performance to a more or less acceptable level (tested by David).
914 
915   */
916   if (handle->id_vendor == VENDOR_SCM
917       && handle->max_ifsd > 48
918       && (  (handle->id_product == SCM_SCR331   && bcd_device < 0x0516)
919           ||(handle->id_product == SCM_SCR331DI && bcd_device < 0x0620)
920           ||(handle->id_product == SCM_SCR335   && bcd_device < 0x0514)
921           ||(handle->id_product == SCM_SPR532   && bcd_device < 0x0504)
922           ||(handle->id_product == SCM_SCR3320  && bcd_device < 0x0522)
923           ))
924     {
925       DEBUGOUT ("enabling workaround for buggy SCM readers\n");
926       handle->max_ifsd = 48;
927     }
928 
929   if (handle->id_vendor == VENDOR_GEMPC)
930     {
931       DEBUGOUT ("enabling product quirk: disable non-null NAD\n");
932       handle->nonnull_nad = 0;
933     }
934 
935   return 0;
936 }
937 
938 
939 static char *
get_escaped_usb_string(libusb_device_handle * idev,int idx,const char * prefix,const char * suffix)940 get_escaped_usb_string (libusb_device_handle *idev, int idx,
941                         const char *prefix, const char *suffix)
942 {
943   int rc;
944   unsigned char buf[280];
945   unsigned char *s;
946   unsigned int langid;
947   size_t i, n, len;
948   char *result;
949 
950   if (!idx)
951     return NULL;
952 
953   /* Fixme: The next line is for the current Valgrid without support
954      for USB IOCTLs. */
955   memset (buf, 0, sizeof buf);
956 
957   /* First get the list of supported languages and use the first one.
958      If we do don't find it we try to use English.  Note that this is
959      all in a 2 bute Unicode encoding using little endian. */
960 #ifdef USE_NPTH
961   npth_unprotect ();
962 #endif
963   rc = libusb_control_transfer (idev, LIBUSB_ENDPOINT_IN,
964                                 LIBUSB_REQUEST_GET_DESCRIPTOR,
965                                 (LIBUSB_DT_STRING << 8), 0,
966                                 buf, sizeof buf, 1000 /* ms timeout */);
967 #ifdef USE_NPTH
968   npth_protect ();
969 #endif
970   if (rc < 4)
971     langid = 0x0409; /* English.  */
972   else
973     langid = (buf[3] << 8) | buf[2];
974 
975 #ifdef USE_NPTH
976   npth_unprotect ();
977 #endif
978   rc = libusb_control_transfer (idev, LIBUSB_ENDPOINT_IN,
979                                 LIBUSB_REQUEST_GET_DESCRIPTOR,
980                                 (LIBUSB_DT_STRING << 8) + idx, langid,
981                                 buf, sizeof buf, 1000 /* ms timeout */);
982 #ifdef USE_NPTH
983   npth_protect ();
984 #endif
985   if (rc < 2 || buf[1] != LIBUSB_DT_STRING)
986     return NULL; /* Error or not a string. */
987   len = buf[0];
988   if (len > rc)
989     return NULL; /* Larger than our buffer. */
990 
991   for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2)
992     {
993       if (s[1])
994         n++; /* High byte set. */
995       else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
996         n += 3 ;
997       else
998         n++;
999     }
1000 
1001   result = malloc (strlen (prefix) + n + strlen (suffix) + 1);
1002   if (!result)
1003     return NULL;
1004 
1005   strcpy (result, prefix);
1006   n = strlen (prefix);
1007   for (s=buf+2, i=2; i+1 < len; i += 2, s += 2)
1008     {
1009       if (s[1])
1010         result[n++] = '\xff'; /* High byte set. */
1011       else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
1012         {
1013           sprintf (result+n, "%%%02X", *s);
1014           n += 3;
1015         }
1016       else
1017         result[n++] = *s;
1018     }
1019   strcpy (result+n, suffix);
1020 
1021   return result;
1022 }
1023 
1024 /* This function creates an reader id to be used to find the same
1025    physical reader after a reset.  It returns an allocated and possibly
1026    percent escaped string or NULL if not enough memory is available. */
1027 static char *
make_reader_id(libusb_device_handle * idev,unsigned int vendor,unsigned int product,unsigned char serialno_index)1028 make_reader_id (libusb_device_handle *idev,
1029                 unsigned int vendor, unsigned int product,
1030                 unsigned char serialno_index)
1031 {
1032   char *rid;
1033   char prefix[20];
1034 
1035   sprintf (prefix, "%04X:%04X:", (vendor & 0xffff), (product & 0xffff));
1036   rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0");
1037   if (!rid)
1038     {
1039       rid = malloc (strlen (prefix) + 3 + 1);
1040       if (!rid)
1041         return NULL;
1042       strcpy (rid, prefix);
1043       strcat (rid, "X:0");
1044     }
1045   return rid;
1046 }
1047 
1048 
1049 /* Helper to find the endpoint from an interface descriptor.  */
1050 static int
find_endpoint(const struct libusb_interface_descriptor * ifcdesc,int mode)1051 find_endpoint (const struct libusb_interface_descriptor *ifcdesc, int mode)
1052 {
1053   int no;
1054   int want_bulk_in = 0;
1055 
1056   if (mode == 1)
1057     want_bulk_in = 0x80;
1058   for (no=0; no < ifcdesc->bNumEndpoints; no++)
1059     {
1060       const struct libusb_endpoint_descriptor *ep = ifcdesc->endpoint + no;
1061       if (ep->bDescriptorType != LIBUSB_DT_ENDPOINT)
1062         ;
1063       else if (mode == 2
1064                && ((ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
1065                    == LIBUSB_TRANSFER_TYPE_INTERRUPT)
1066                && (ep->bEndpointAddress & 0x80))
1067         return ep->bEndpointAddress;
1068       else if ((mode == 0 || mode == 1)
1069                && ((ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
1070                    == LIBUSB_TRANSFER_TYPE_BULK)
1071                && (ep->bEndpointAddress & 0x80) == want_bulk_in)
1072         return ep->bEndpointAddress;
1073     }
1074 
1075   return -1;
1076 }
1077 
1078 
1079 /* Helper for scan_devices. This function returns true if a
1080    requested device has been found or the caller should stop scanning
1081    for other reasons. */
1082 static void
scan_usb_device(int * count,char ** rid_list,struct libusb_device * dev)1083 scan_usb_device (int *count, char **rid_list, struct libusb_device *dev)
1084 {
1085   int ifc_no;
1086   int set_no;
1087   const struct libusb_interface_descriptor *ifcdesc;
1088   char *rid;
1089   libusb_device_handle *idev = NULL;
1090   int err;
1091   struct libusb_config_descriptor *config;
1092   struct libusb_device_descriptor desc;
1093   char *p;
1094 
1095   err = libusb_get_device_descriptor (dev, &desc);
1096   if (err)
1097     return;
1098 
1099   err = libusb_get_active_config_descriptor (dev, &config);
1100   if (err)
1101     return;
1102 
1103   for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
1104     for (set_no=0; set_no < config->interface[ifc_no].num_altsetting; set_no++)
1105       {
1106         ifcdesc = (config->interface[ifc_no].altsetting + set_no);
1107         /* The second condition is for older SCM SPR 532 who did
1108            not know about the assigned CCID class.  The third
1109            condition does the same for a Cherry SmartTerminal
1110            ST-2000.  Instead of trying to interpret the strings
1111            we simply check the product ID. */
1112         if (ifcdesc && ifcdesc->extra
1113             && ((ifcdesc->bInterfaceClass == 11
1114                  && ifcdesc->bInterfaceSubClass == 0
1115                  && ifcdesc->bInterfaceProtocol == 0)
1116                 || (ifcdesc->bInterfaceClass == 255
1117                     && desc.idVendor == VENDOR_SCM
1118                     && desc.idProduct == SCM_SPR532)
1119                 || (ifcdesc->bInterfaceClass == 255
1120                     && desc.idVendor == VENDOR_CHERRY
1121                     && desc.idProduct == CHERRY_ST2000)))
1122           {
1123             ++*count;
1124 
1125             err = libusb_open (dev, &idev);
1126             if (err)
1127               {
1128                 DEBUGOUT_1 ("usb_open failed: %s\n", libusb_error_name (err));
1129                 continue; /* with next setting. */
1130               }
1131 
1132             rid = make_reader_id (idev, desc.idVendor, desc.idProduct,
1133                                   desc.iSerialNumber);
1134             if (!rid)
1135               {
1136                 libusb_free_config_descriptor (config);
1137                 return;
1138               }
1139 
1140             /* We are collecting infos about all available CCID
1141                readers.  Store them and continue.  */
1142             DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n", *count, rid);
1143             p = malloc ((*rid_list? strlen (*rid_list):0) + 1
1144                         + strlen (rid) + 1);
1145             if (p)
1146               {
1147                 *p = 0;
1148                 if (*rid_list)
1149                   {
1150                     strcat (p, *rid_list);
1151                     free (*rid_list);
1152                   }
1153                 strcat (p, rid);
1154                 strcat (p, "\n");
1155                 *rid_list = p;
1156               }
1157             else /* Out of memory. */
1158               {
1159                 libusb_free_config_descriptor (config);
1160                 free (rid);
1161                 return;
1162               }
1163 
1164             free (rid);
1165             libusb_close (idev);
1166             idev = NULL;
1167           }
1168       }
1169 
1170   libusb_free_config_descriptor (config);
1171 }
1172 
1173 /* Scan all CCID devices.
1174 
1175    The function returns 0 if a reader has been found or when a scan
1176    returned without error.
1177 
1178    R_RID should be the address where to store the list of reader_ids
1179    we found.  If on return this list is empty, no CCID device has been
1180    found; otherwise it points to an allocated linked list of reader
1181    IDs.
1182 */
1183 static int
scan_devices(char ** r_rid)1184 scan_devices (char **r_rid)
1185 {
1186   char *rid_list = NULL;
1187   int count = 0;
1188   libusb_device **dev_list = NULL;
1189   libusb_device *dev;
1190   int i;
1191   ssize_t n;
1192 
1193   /* Set return values to a default. */
1194   if (r_rid)
1195     *r_rid = NULL;
1196 
1197   n = libusb_get_device_list (NULL, &dev_list);
1198 
1199   for (i = 0; i < n; i++)
1200     {
1201       dev = dev_list[i];
1202       scan_usb_device (&count, &rid_list, dev);
1203     }
1204 
1205   libusb_free_device_list (dev_list, 1);
1206 
1207   *r_rid = rid_list;
1208   return 0;
1209 }
1210 
1211 
1212 /* Set the level of debugging to LEVEL and return the old level.  -1
1213    just returns the old level.  A level of 0 disables debugging, 1
1214    enables debugging, 2 enables additional tracing of the T=1
1215    protocol, 3 additionally enables debugging for GetSlotStatus, other
1216    values are not yet defined.
1217 
1218    Note that libusb may provide its own debugging feature which is
1219    enabled by setting the envvar USB_DEBUG.  */
1220 int
ccid_set_debug_level(int level)1221 ccid_set_debug_level (int level)
1222 {
1223   int old = debug_level;
1224   if (level != -1)
1225     debug_level = level;
1226   return old;
1227 }
1228 
1229 
1230 char *
ccid_get_reader_list(void)1231 ccid_get_reader_list (void)
1232 {
1233   char *reader_list;
1234 
1235   if (!initialized_usb)
1236     {
1237       int rc;
1238       if ((rc = libusb_init (NULL)))
1239         {
1240           DEBUGOUT_1 ("usb_init failed: %s.\n", libusb_error_name (rc));
1241           return NULL;
1242         }
1243       initialized_usb = 1;
1244     }
1245 
1246   if (scan_devices (&reader_list))
1247     return NULL; /* Error. */
1248   return reader_list;
1249 }
1250 
1251 
1252 /* Vendor specific custom initialization.  */
1253 static int
ccid_vendor_specific_init(ccid_driver_t handle)1254 ccid_vendor_specific_init (ccid_driver_t handle)
1255 {
1256   int r = 0;
1257 
1258   if (handle->id_vendor == VENDOR_VEGA && handle->id_product == VEGA_ALPHA)
1259     {
1260       /*
1261        * Vega alpha has a feature to show retry counter on the pinpad
1262        * display.  But it assumes that the card returns the value of
1263        * retry counter by VERIFY with empty data (return code of
1264        * 63Cx).  Unfortunately, existing OpenPGP cards don't support
1265        * VERIFY command with empty data.  This vendor specific command
1266        * sequence is to disable the feature.
1267        */
1268       const unsigned char cmd[] = { '\xb5', '\x01', '\x00', '\x03', '\x00' };
1269 
1270       r = send_escape_cmd (handle, cmd, sizeof (cmd), NULL, 0, NULL);
1271     }
1272   else if (handle->id_vendor == VENDOR_SCM && handle->id_product == SCM_SPR532)
1273     {
1274       /*
1275        * It seems that SEQ may be out of sync between host and the card reader,
1276        * and SET_INTERFACE doesn't reset it.  Make sure it works at the init.
1277        */
1278       abort_cmd (handle, 0, 1);
1279     }
1280 
1281   if (r != 0 && r != CCID_DRIVER_ERR_CARD_INACTIVE
1282       && r != CCID_DRIVER_ERR_NO_CARD)
1283     return r;
1284   else
1285     return 0;
1286 }
1287 
1288 
1289 static int
ccid_vendor_specific_setup(ccid_driver_t handle)1290 ccid_vendor_specific_setup (ccid_driver_t handle)
1291 {
1292   if (handle->id_vendor == VENDOR_SCM && handle->id_product == SCM_SPR532)
1293     {
1294       libusb_clear_halt (handle->idev, handle->ep_intr);
1295     }
1296   return 0;
1297 }
1298 
1299 
1300 static int
ccid_vendor_specific_pinpad_setup(ccid_driver_t handle)1301 ccid_vendor_specific_pinpad_setup (ccid_driver_t handle)
1302 {
1303   if (handle->id_vendor == VENDOR_SCM && handle->id_product == SCM_SPR532)
1304     {
1305       DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n");
1306       send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3,
1307                        NULL, 0, NULL);
1308     }
1309   return 0;
1310 }
1311 
1312 
1313 #define MAX_DEVICE 16 /* See MAX_READER in apdu.c.  */
1314 
1315 struct ccid_dev_table {
1316   int n;                        /* Index to ccid_usb_dev_list */
1317   int interface_number;
1318   int setting_number;
1319   unsigned char *ifcdesc_extra;
1320   int ep_bulk_out;
1321   int ep_bulk_in;
1322   int ep_intr;
1323   size_t ifcdesc_extra_len;
1324 };
1325 
1326 static libusb_device **ccid_usb_dev_list;
1327 static struct ccid_dev_table ccid_dev_table[MAX_DEVICE];
1328 
1329 gpg_error_t
ccid_dev_scan(int * idx_max_p,void ** t_p)1330 ccid_dev_scan (int *idx_max_p, void **t_p)
1331 {
1332   ssize_t n;
1333   libusb_device *dev;
1334   int i;
1335   int ifc_no;
1336   int set_no;
1337   int idx = 0;
1338   int err = 0;
1339 
1340   *idx_max_p = 0;
1341   *t_p = NULL;
1342 
1343   if (!initialized_usb)
1344     {
1345       int rc;
1346       if ((rc = libusb_init (NULL)))
1347         {
1348           DEBUGOUT_1 ("usb_init failed: %s.\n", libusb_error_name (rc));
1349           return gpg_error (GPG_ERR_ENODEV);
1350         }
1351       initialized_usb = 1;
1352     }
1353 
1354   n = libusb_get_device_list (NULL, &ccid_usb_dev_list);
1355   for (i = 0; i < n; i++)
1356     {
1357       struct libusb_config_descriptor *config;
1358       struct libusb_device_descriptor desc;
1359 
1360       dev = ccid_usb_dev_list[i];
1361 
1362       if (libusb_get_device_descriptor (dev, &desc))
1363         continue;
1364 
1365       if (libusb_get_active_config_descriptor (dev, &config))
1366         continue;
1367 
1368       for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
1369         for (set_no=0; set_no < config->interface[ifc_no].num_altsetting;
1370              set_no++)
1371           {
1372             const struct libusb_interface_descriptor *ifcdesc;
1373 
1374             ifcdesc = &config->interface[ifc_no].altsetting[set_no];
1375             /* The second condition is for older SCM SPR 532 who did
1376                not know about the assigned CCID class.  The third
1377                condition does the same for a Cherry SmartTerminal
1378                ST-2000.  Instead of trying to interpret the strings
1379                we simply check the product ID. */
1380             if (ifcdesc && ifcdesc->extra
1381                 && ((ifcdesc->bInterfaceClass == 11
1382                      && ifcdesc->bInterfaceSubClass == 0
1383                      && ifcdesc->bInterfaceProtocol == 0)
1384                     || (ifcdesc->bInterfaceClass == 255
1385                         && desc.idVendor == VENDOR_SCM
1386                         && desc.idProduct == SCM_SPR532)
1387                     || (ifcdesc->bInterfaceClass == 255
1388                         && desc.idVendor == VENDOR_CHERRY
1389                         && desc.idProduct == CHERRY_ST2000)))
1390               {
1391                 /* Found a reader.  */
1392                 unsigned char *ifcdesc_extra;
1393 
1394                 ifcdesc_extra = malloc (ifcdesc->extra_length);
1395                 if (!ifcdesc_extra)
1396                   {
1397                     err = gpg_error_from_syserror ();
1398                     libusb_free_config_descriptor (config);
1399                     goto scan_finish;
1400                   }
1401                 memcpy (ifcdesc_extra, ifcdesc->extra, ifcdesc->extra_length);
1402 
1403                 ccid_dev_table[idx].n = i;
1404                 ccid_dev_table[idx].interface_number = ifc_no;
1405                 ccid_dev_table[idx].setting_number = set_no;
1406                 ccid_dev_table[idx].ifcdesc_extra = ifcdesc_extra;
1407                 ccid_dev_table[idx].ifcdesc_extra_len = ifcdesc->extra_length;
1408                 ccid_dev_table[idx].ep_bulk_out = find_endpoint (ifcdesc, 0);
1409                 ccid_dev_table[idx].ep_bulk_in = find_endpoint (ifcdesc, 1);
1410                 ccid_dev_table[idx].ep_intr = find_endpoint (ifcdesc, 2);
1411 
1412                 idx++;
1413                 if (idx >= MAX_DEVICE)
1414                   {
1415                     libusb_free_config_descriptor (config);
1416                     err = 0;
1417                     goto scan_finish;
1418                   }
1419               }
1420           }
1421 
1422       libusb_free_config_descriptor (config);
1423     }
1424 
1425  scan_finish:
1426 
1427   if (err)
1428     {
1429       for (i = 0; i < idx; i++)
1430         {
1431           free (ccid_dev_table[idx].ifcdesc_extra);
1432           ccid_dev_table[idx].n = 0;
1433           ccid_dev_table[idx].interface_number = 0;
1434           ccid_dev_table[idx].setting_number = 0;
1435           ccid_dev_table[idx].ifcdesc_extra = NULL;
1436           ccid_dev_table[idx].ifcdesc_extra_len = 0;
1437           ccid_dev_table[idx].ep_bulk_out = 0;
1438           ccid_dev_table[idx].ep_bulk_in = 0;
1439           ccid_dev_table[idx].ep_intr = 0;
1440         }
1441       libusb_free_device_list (ccid_usb_dev_list, 1);
1442       ccid_usb_dev_list = NULL;
1443     }
1444   else
1445     {
1446       *idx_max_p = idx;
1447       if (idx)
1448         *t_p = ccid_dev_table;
1449       else
1450         *t_p = NULL;
1451     }
1452 
1453   return err;
1454 }
1455 
1456 void
ccid_dev_scan_finish(void * tbl0,int max)1457 ccid_dev_scan_finish (void *tbl0, int max)
1458 {
1459   int i;
1460   struct ccid_dev_table *tbl = tbl0;
1461 
1462   for (i = 0; i < max; i++)
1463     {
1464       free (tbl[i].ifcdesc_extra);
1465       tbl[i].n = 0;
1466       tbl[i].interface_number = 0;
1467       tbl[i].setting_number = 0;
1468       tbl[i].ifcdesc_extra = NULL;
1469       tbl[i].ifcdesc_extra_len = 0;
1470       tbl[i].ep_bulk_out = 0;
1471       tbl[i].ep_bulk_in = 0;
1472       tbl[i].ep_intr = 0;
1473     }
1474   libusb_free_device_list (ccid_usb_dev_list, 1);
1475   ccid_usb_dev_list = NULL;
1476 }
1477 
1478 unsigned int
ccid_get_BAI(int idx,void * tbl0)1479 ccid_get_BAI (int idx, void *tbl0)
1480 {
1481   int n;
1482   int bus, addr, intf;
1483   unsigned int bai;
1484   libusb_device *dev;
1485   struct ccid_dev_table *tbl = tbl0;
1486 
1487   n = tbl[idx].n;
1488   dev = ccid_usb_dev_list[n];
1489 
1490   bus = libusb_get_bus_number (dev);
1491   addr = libusb_get_device_address (dev);
1492   intf = tbl[idx].interface_number;
1493   bai = (bus << 16) | (addr << 8) | intf;
1494 
1495   return bai;
1496 }
1497 
1498 int
ccid_compare_BAI(ccid_driver_t handle,unsigned int bai)1499 ccid_compare_BAI (ccid_driver_t handle, unsigned int bai)
1500 {
1501   return handle->bai == bai;
1502 }
1503 
1504 
1505 static void
intr_cb(struct libusb_transfer * transfer)1506 intr_cb (struct libusb_transfer *transfer)
1507 {
1508   ccid_driver_t handle = transfer->user_data;
1509 
1510   DEBUGOUT_2 ("CCID: interrupt callback %d (%d)\n",
1511               transfer->status, transfer->actual_length);
1512 
1513   if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT)
1514     {
1515       int err;
1516 
1517     submit_again:
1518       /* Submit the URB again to keep watching the INTERRUPT transfer.  */
1519       err = libusb_submit_transfer (transfer);
1520       if (err == LIBUSB_ERROR_NO_DEVICE)
1521         goto device_removed;
1522 
1523       DEBUGOUT_1 ("CCID submit transfer again %d\n", err);
1524     }
1525   else if (transfer->status == LIBUSB_TRANSFER_COMPLETED)
1526     {
1527       size_t len = transfer->actual_length;
1528       unsigned char *p = transfer->buffer;
1529       int card_removed = 0;
1530 
1531       while (len)
1532         {
1533           if (*p == RDR_to_PC_NotifySlotChange)
1534             {
1535               if (len < 2)
1536                 break;
1537 
1538               DEBUGOUT_1 ("CCID: NotifySlotChange: %02x\n", p[1]);
1539 
1540               if ((p[1] & 1))
1541                 card_removed = 0;
1542               else
1543                 card_removed = 1;
1544 
1545               p += 2;
1546               len -= 2;
1547             }
1548           else if (*p == RDR_to_PC_HardwareError)
1549             {
1550               if (len < 4)
1551                 break;
1552 
1553               DEBUGOUT_1 ("CCID: hardware error detected: %02x\n", p[3]);
1554               p += 4;
1555               len -= 4;
1556             }
1557           else
1558             {
1559               DEBUGOUT_1 ("CCID: unknown intr: %02x\n", p[0]);
1560               break;
1561             }
1562         }
1563 
1564       if (card_removed)
1565         {
1566           DEBUGOUT ("CCID: card removed\n");
1567           handle->powered_off = 1;
1568 #if defined(GNUPG_MAJOR_VERSION)
1569           scd_kick_the_loop ();
1570 #endif
1571         }
1572       else
1573         {
1574           /* Event other than card removal.  */
1575           goto submit_again;
1576         }
1577     }
1578   else if (transfer->status == LIBUSB_TRANSFER_CANCELLED)
1579     handle->powered_off = 1;
1580   else if (transfer->status == LIBUSB_TRANSFER_OVERFLOW)
1581     {
1582       /* Something goes wrong.  Ignore.  */
1583       DEBUGOUT ("CCID: interrupt transfer overflow\n");
1584     }
1585   else
1586     {
1587     device_removed:
1588       DEBUGOUT ("CCID: device removed\n");
1589       handle->powered_off = 1;
1590 #if defined(GNUPG_MAJOR_VERSION)
1591       scd_kick_the_loop ();
1592 #endif
1593     }
1594 }
1595 
1596 static void
ccid_setup_intr(ccid_driver_t handle)1597 ccid_setup_intr  (ccid_driver_t handle)
1598 {
1599   struct libusb_transfer *transfer;
1600   int err;
1601 
1602   transfer = libusb_alloc_transfer (0);
1603   handle->transfer = transfer;
1604   libusb_fill_interrupt_transfer (transfer, handle->idev, handle->ep_intr,
1605                                   handle->intr_buf, sizeof (handle->intr_buf),
1606                                   intr_cb, handle, 0);
1607   err = libusb_submit_transfer (transfer);
1608   DEBUGOUT_2 ("CCID submit transfer (%x): %d", handle->ep_intr, err);
1609 }
1610 
1611 
1612 static void *
ccid_usb_thread(void * arg)1613 ccid_usb_thread (void *arg)
1614 {
1615   libusb_context *ctx = arg;
1616 
1617   while (ccid_usb_thread_is_alive)
1618     {
1619 #ifdef USE_NPTH
1620       npth_unprotect ();
1621 #endif
1622       libusb_handle_events_completed (ctx, NULL);
1623 #ifdef USE_NPTH
1624       npth_protect ();
1625 #endif
1626     }
1627 
1628   return NULL;
1629 }
1630 
1631 
1632 static int
ccid_open_usb_reader(const char * spec_reader_name,int idx,void * ccid_table0,ccid_driver_t * handle,char ** rdrname_p)1633 ccid_open_usb_reader (const char *spec_reader_name,
1634                       int idx, void *ccid_table0,
1635                       ccid_driver_t *handle, char **rdrname_p)
1636 {
1637   libusb_device *dev;
1638   libusb_device_handle *idev = NULL;
1639   char *rid = NULL;
1640   int rc = 0;
1641   int ifc_no, set_no;
1642   struct libusb_device_descriptor desc;
1643   int n;
1644   int bus, addr;
1645   unsigned int bai;
1646   struct ccid_dev_table *ccid_table = ccid_table0;
1647 
1648   n = ccid_table[idx].n;
1649   ifc_no = ccid_table[idx].interface_number;
1650   set_no = ccid_table[idx].setting_number;
1651 
1652   dev = ccid_usb_dev_list[n];
1653   bus = libusb_get_bus_number (dev);
1654   addr = libusb_get_device_address (dev);
1655   bai = (bus << 16) | (addr << 8) | ifc_no;
1656 
1657   rc = libusb_open (dev, &idev);
1658   if (rc)
1659     {
1660       DEBUGOUT_1 ("usb_open failed: %s\n", libusb_error_name (rc));
1661       free (*handle);
1662       *handle = NULL;
1663       return map_libusb_error (rc);
1664     }
1665 
1666   if (ccid_usb_thread_is_alive++ == 0)
1667     {
1668       npth_t thread;
1669       npth_attr_t tattr;
1670       int err;
1671 
1672       err = npth_attr_init (&tattr);
1673       if (err)
1674         {
1675           DEBUGOUT_1 ("npth_attr_init failed: %s\n", strerror (err));
1676           free (*handle);
1677           *handle = NULL;
1678           return err;
1679         }
1680 
1681       npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
1682       err = npth_create (&thread, &tattr, ccid_usb_thread, NULL);
1683       if (err)
1684         {
1685           DEBUGOUT_1 ("npth_create failed: %s\n", strerror (err));
1686           free (*handle);
1687           *handle = NULL;
1688           return err;
1689         }
1690 
1691       npth_attr_destroy (&tattr);
1692     }
1693 
1694   rc = libusb_get_device_descriptor (dev, &desc);
1695   if (rc)
1696     {
1697       DEBUGOUT ("get_device_descripor failed\n");
1698       rc = map_libusb_error (rc);
1699       goto leave;
1700     }
1701 
1702   rid = make_reader_id (idev, desc.idVendor, desc.idProduct,
1703                         desc.iSerialNumber);
1704 
1705   /* Check to see if reader name matches the spec.  */
1706   if (spec_reader_name
1707       && strncmp (rid, spec_reader_name, strlen (spec_reader_name)))
1708     {
1709       DEBUGOUT ("device not matched\n");
1710       rc = CCID_DRIVER_ERR_NO_READER;
1711       goto leave;
1712     }
1713 
1714   (*handle)->id_vendor = desc.idVendor;
1715   (*handle)->id_product = desc.idProduct;
1716   (*handle)->idev = idev;
1717   (*handle)->bai = bai;
1718   (*handle)->ifc_no = ifc_no;
1719   (*handle)->ep_bulk_out = ccid_table[idx].ep_bulk_out;
1720   (*handle)->ep_bulk_in = ccid_table[idx].ep_bulk_in;
1721   (*handle)->ep_intr = ccid_table[idx].ep_intr;
1722 
1723   DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n", idx, rid);
1724 
1725   if (parse_ccid_descriptor (*handle, desc.bcdDevice,
1726                              ccid_table[idx].ifcdesc_extra,
1727                              ccid_table[idx].ifcdesc_extra_len))
1728     {
1729       DEBUGOUT ("device not supported\n");
1730       rc = CCID_DRIVER_ERR_NO_READER;
1731       goto leave;
1732     }
1733 
1734   rc = libusb_claim_interface (idev, ifc_no);
1735   if (rc)
1736     {
1737       DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1738       rc = map_libusb_error (rc);
1739       goto leave;
1740     }
1741 
1742   /* Submit SET_INTERFACE control transfer which can reset the device.  */
1743   rc = libusb_set_interface_alt_setting (idev, ifc_no, set_no);
1744   if (rc)
1745     {
1746       DEBUGOUT_1 ("usb_set_interface_alt_setting failed: %d\n", rc);
1747       rc = map_libusb_error (rc);
1748       goto leave;
1749     }
1750 
1751   rc = ccid_vendor_specific_init (*handle);
1752 
1753  leave:
1754   if (rc)
1755     {
1756       --ccid_usb_thread_is_alive;
1757       free (rid);
1758       libusb_release_interface (idev, ifc_no);
1759       libusb_close (idev);
1760       free (*handle);
1761       *handle = NULL;
1762     }
1763   else
1764     {
1765       if (rdrname_p)
1766         *rdrname_p = rid;
1767       else
1768         free (rid);
1769     }
1770 
1771   return rc;
1772 }
1773 
1774 /* Open the reader with the internal number READERNO and return a
1775    pointer to be used as handle in HANDLE.  Returns 0 on success. */
1776 int
ccid_open_reader(const char * spec_reader_name,int idx,void * ccid_table0,ccid_driver_t * handle,char ** rdrname_p)1777 ccid_open_reader (const char *spec_reader_name, int idx,
1778                   void *ccid_table0,
1779                   ccid_driver_t *handle, char **rdrname_p)
1780 {
1781   struct ccid_dev_table *ccid_table = ccid_table0;
1782 
1783   *handle = calloc (1, sizeof **handle);
1784   if (!*handle)
1785     {
1786       DEBUGOUT ("out of memory\n");
1787       return CCID_DRIVER_ERR_OUT_OF_CORE;
1788     }
1789 
1790   return ccid_open_usb_reader (spec_reader_name, idx, ccid_table,
1791                                handle, rdrname_p);
1792 }
1793 
1794 
1795 int
ccid_require_get_status(ccid_driver_t handle)1796 ccid_require_get_status (ccid_driver_t handle)
1797 {
1798   /* When a card reader supports interrupt transfer to check the
1799      status of card, it is possible to submit only an interrupt
1800      transfer, and no check is required by application layer.  USB can
1801      detect removal of a card and can detect removal of a reader.
1802   */
1803   if (handle->ep_intr >= 0)
1804     {
1805       if (handle->id_vendor != VENDOR_SCM)
1806         return 0;
1807 
1808       /*
1809        * For card reader with interrupt transfer support, ideally,
1810        * removal is detected by intr_cb, but some card reader
1811        * (e.g. SPR532) has a possible case of missing report to
1812        * intr_cb, and another case of valid report to intr_cb.
1813        *
1814        * For such a reader, the removal should be able to be detected
1815        * by PC_to_RDR_GetSlotStatus, too.  Thus, calls to
1816        * ccid_slot_status should go on wire even if "on_wire" is not
1817        * requested.
1818        *
1819        */
1820       if (handle->transfer == NULL)
1821         return 0;
1822     }
1823 
1824   /* Libusb actually detects the removal of USB device in use.
1825      However, there is no good API to handle the removal (yet),
1826      cleanly and with good portability.
1827 
1828      There is libusb_set_pollfd_notifiers function, but it doesn't
1829      offer libusb_device_handle* data to its callback.  So, when it
1830      watches multiple devices, there is no way to know which device is
1831      removed.
1832 
1833      Once, we will have a good programming interface of libusb, we can
1834      list tokens (with no interrupt transfer support, but always with
1835      card inserted) here to return 0, so that scdaemon can submit
1836      minimum packet on wire.
1837   */
1838   return 1;
1839 }
1840 
1841 static int
send_power_off(ccid_driver_t handle)1842 send_power_off (ccid_driver_t handle)
1843 {
1844   int rc;
1845   unsigned char msg[100];
1846   size_t msglen;
1847   unsigned char seqno;
1848 
1849   msg[0] = PC_to_RDR_IccPowerOff;
1850   msg[5] = 0; /* slot */
1851   msg[6] = seqno = handle->seqno++;
1852   msg[7] = 0; /* RFU */
1853   msg[8] = 0; /* RFU */
1854   msg[9] = 0; /* RFU */
1855   set_msg_len (msg, 0);
1856   msglen = 10;
1857 
1858   rc = bulk_out (handle, msg, msglen, 0);
1859   if (!rc)
1860     bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1861              seqno, 2000, 0);
1862   return rc;
1863 }
1864 
1865 static void
do_close_reader(ccid_driver_t handle)1866 do_close_reader (ccid_driver_t handle)
1867 {
1868   int rc;
1869 
1870   if (!handle->powered_off)
1871     send_power_off (handle);
1872 
1873   if (handle->transfer)
1874     {
1875       if (!handle->powered_off)
1876         {
1877           DEBUGOUT ("libusb_cancel_transfer\n");
1878 
1879           rc = libusb_cancel_transfer (handle->transfer);
1880           if (rc != LIBUSB_ERROR_NOT_FOUND)
1881             while (!handle->powered_off)
1882               {
1883                 DEBUGOUT ("libusb_handle_events_completed\n");
1884 #ifdef USE_NPTH
1885                 npth_unprotect ();
1886 #endif
1887                 libusb_handle_events_completed (NULL, &handle->powered_off);
1888 #ifdef USE_NPTH
1889                 npth_protect ();
1890 #endif
1891               }
1892         }
1893 
1894       libusb_free_transfer (handle->transfer);
1895       handle->transfer = NULL;
1896     }
1897 
1898   DEBUGOUT ("libusb_release_interface and libusb_close\n");
1899   libusb_release_interface (handle->idev, handle->ifc_no);
1900   --ccid_usb_thread_is_alive;
1901   libusb_close (handle->idev);
1902   handle->idev = NULL;
1903 }
1904 
1905 
1906 int
ccid_set_progress_cb(ccid_driver_t handle,void (* cb)(void *,const char *,int,int,int),void * cb_arg)1907 ccid_set_progress_cb (ccid_driver_t handle,
1908                       void (*cb)(void *, const char *, int, int, int),
1909                       void *cb_arg)
1910 {
1911   if (!handle)
1912     return CCID_DRIVER_ERR_INV_VALUE;
1913 
1914   handle->progress_cb = cb;
1915   handle->progress_cb_arg = cb_arg;
1916   return 0;
1917 }
1918 
1919 
1920 int
ccid_set_prompt_cb(ccid_driver_t handle,void (* cb)(void *,int),void * cb_arg)1921 ccid_set_prompt_cb (ccid_driver_t handle,
1922 		    void (*cb)(void *, int), void *cb_arg)
1923 {
1924   if (!handle)
1925     return CCID_DRIVER_ERR_INV_VALUE;
1926 
1927   handle->prompt_cb = cb;
1928   handle->prompt_cb_arg = cb_arg;
1929   return 0;
1930 }
1931 
1932 
1933 /* Close the reader HANDLE. */
1934 int
ccid_close_reader(ccid_driver_t handle)1935 ccid_close_reader (ccid_driver_t handle)
1936 {
1937   if (!handle)
1938     return 0;
1939 
1940   do_close_reader (handle);
1941   free (handle);
1942   return 0;
1943 }
1944 
1945 
1946 /* Return False if a card is present and powered. */
1947 int
ccid_check_card_presence(ccid_driver_t handle)1948 ccid_check_card_presence (ccid_driver_t handle)
1949 {
1950   (void)handle;  /* Not yet implemented.  */
1951   return -1;
1952 }
1953 
1954 
1955 /* Write a MSG of length MSGLEN to the designated bulk out endpoint.
1956    Returns 0 on success. */
1957 static int
bulk_out(ccid_driver_t handle,unsigned char * msg,size_t msglen,int no_debug)1958 bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
1959           int no_debug)
1960 {
1961   int rc;
1962   int transferred;
1963 
1964   /* No need to continue and clutter the log with USB write error
1965      messages after we got the first ENODEV.  */
1966   if (handle->enodev_seen)
1967     return CCID_DRIVER_ERR_NO_READER;
1968 
1969   if (debug_level && (!no_debug || debug_level >= 3))
1970     {
1971       switch (msglen? msg[0]:0)
1972         {
1973         case PC_to_RDR_IccPowerOn:
1974           print_p2r_iccpoweron (msg, msglen);
1975           break;
1976         case PC_to_RDR_IccPowerOff:
1977           print_p2r_iccpoweroff (msg, msglen);
1978           break;
1979         case PC_to_RDR_GetSlotStatus:
1980           print_p2r_getslotstatus (msg, msglen);
1981           break;
1982         case PC_to_RDR_XfrBlock:
1983           print_p2r_xfrblock (msg, msglen);
1984           break;
1985         case PC_to_RDR_GetParameters:
1986           print_p2r_getparameters (msg, msglen);
1987           break;
1988         case PC_to_RDR_ResetParameters:
1989           print_p2r_resetparameters (msg, msglen);
1990           break;
1991         case PC_to_RDR_SetParameters:
1992           print_p2r_setparameters (msg, msglen);
1993           break;
1994         case PC_to_RDR_Escape:
1995           print_p2r_escape (msg, msglen);
1996           break;
1997         case PC_to_RDR_IccClock:
1998           print_p2r_iccclock (msg, msglen);
1999           break;
2000         case PC_to_RDR_T0APDU:
2001           print_p2r_to0apdu (msg, msglen);
2002           break;
2003         case PC_to_RDR_Secure:
2004           print_p2r_secure (msg, msglen);
2005           break;
2006         case PC_to_RDR_Mechanical:
2007           print_p2r_mechanical (msg, msglen);
2008           break;
2009         case PC_to_RDR_Abort:
2010           print_p2r_abort (msg, msglen);
2011           break;
2012         case PC_to_RDR_SetDataRate:
2013           print_p2r_setdatarate (msg, msglen);
2014           break;
2015         default:
2016           print_p2r_unknown (msg, msglen);
2017           break;
2018         }
2019     }
2020 
2021 #ifdef USE_NPTH
2022   npth_unprotect ();
2023 #endif
2024   rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_out,
2025                              msg, msglen, &transferred,
2026                              5000 /* ms timeout */);
2027 #ifdef USE_NPTH
2028   npth_protect ();
2029 #endif
2030   if (rc == 0 && transferred == msglen)
2031     return 0;
2032 
2033   if (rc)
2034     {
2035       DEBUGOUT_1 ("usb_bulk_write error: %s\n", libusb_error_name (rc));
2036       if (rc == LIBUSB_ERROR_NO_DEVICE)
2037         {
2038           handle->enodev_seen = 1;
2039           return CCID_DRIVER_ERR_NO_READER;
2040         }
2041     }
2042 
2043   return 0;
2044 }
2045 
2046 
2047 /* Read a maximum of LENGTH bytes from the bulk in endpoint into
2048    BUFFER and return the actual read number if bytes in NREAD. SEQNO
2049    is the sequence number used to send the request and EXPECTED_TYPE
2050    the type of message we expect. Does checks on the ccid
2051    header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to
2052    avoid debug messages in case of no error; this can be overridden
2053    with a glibal debug level of at least 3. Returns 0 on success. */
2054 static int
bulk_in(ccid_driver_t handle,unsigned char * buffer,size_t length,size_t * nread,int expected_type,int seqno,int timeout,int no_debug)2055 bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
2056          size_t *nread, int expected_type, int seqno, int timeout,
2057          int no_debug)
2058 {
2059   int rc;
2060   int msglen;
2061   int notified = 0;
2062   int bwi = 1;
2063 
2064   /* Fixme: The next line for the current Valgrind without support
2065      for USB IOCTLs. */
2066   memset (buffer, 0, length);
2067  retry:
2068 
2069 #ifdef USE_NPTH
2070   npth_unprotect ();
2071 #endif
2072   rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_in,
2073                              buffer, length, &msglen, bwi*timeout);
2074 #ifdef USE_NPTH
2075   npth_protect ();
2076 #endif
2077   if (rc)
2078     {
2079       DEBUGOUT_1 ("usb_bulk_read error: %s\n", libusb_error_name (rc));
2080       if (rc == LIBUSB_ERROR_NO_DEVICE)
2081         handle->enodev_seen = 1;
2082 
2083       return map_libusb_error (rc);
2084     }
2085   if (msglen < 0)
2086     return CCID_DRIVER_ERR_INV_VALUE;  /* Faulty libusb.  */
2087   *nread = msglen;
2088 
2089   if (msglen < 10)
2090     {
2091       DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen);
2092       abort_cmd (handle, seqno, 0);
2093       return CCID_DRIVER_ERR_INV_VALUE;
2094     }
2095   if (buffer[5] != 0)
2096     {
2097       DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]);
2098       return CCID_DRIVER_ERR_INV_VALUE;
2099     }
2100   if (buffer[6] != seqno)
2101     {
2102       DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n",
2103                   seqno, buffer[6]);
2104       /* Retry until we are synced again.  */
2105       goto retry;
2106     }
2107 
2108   /* We need to handle the time extension request before we check that
2109      we got the expected message type.  This is in particular required
2110      for the Cherry keyboard which sends a time extension request for
2111      each key hit.  */
2112   if (!(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80)
2113     {
2114       /* Card present and active, time extension requested. */
2115       DEBUGOUT_2 ("time extension requested (%02X,%02X)\n",
2116                   buffer[7], buffer[8]);
2117 
2118       bwi = 1;
2119       if (buffer[8] != 0 && buffer[8] != 0xff)
2120         bwi = buffer[8];
2121 
2122       /* Gnuk enhancement to prompt user input by ack button */
2123       if (buffer[8] == 0xff && !notified)
2124         {
2125           notified = 1;
2126 	  handle->prompt_cb (handle->prompt_cb_arg, 1);
2127         }
2128 
2129       goto retry;
2130     }
2131 
2132   if (notified)
2133     handle->prompt_cb (handle->prompt_cb_arg, 0);
2134 
2135   if (buffer[0] != expected_type && buffer[0] != RDR_to_PC_SlotStatus)
2136     {
2137       DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]);
2138       abort_cmd (handle, seqno, 0);
2139       return CCID_DRIVER_ERR_INV_VALUE;
2140     }
2141 
2142   if (debug_level && (!no_debug || debug_level >= 3))
2143     {
2144       switch (buffer[0])
2145         {
2146         case RDR_to_PC_DataBlock:
2147           print_r2p_datablock (buffer, msglen);
2148           break;
2149         case RDR_to_PC_SlotStatus:
2150           print_r2p_slotstatus (buffer, msglen);
2151           break;
2152         case RDR_to_PC_Parameters:
2153           print_r2p_parameters (buffer, msglen);
2154           break;
2155         case RDR_to_PC_Escape:
2156           print_r2p_escape (buffer, msglen);
2157           break;
2158         case RDR_to_PC_DataRate:
2159           print_r2p_datarate (buffer, msglen);
2160           break;
2161         default:
2162           print_r2p_unknown (buffer, msglen);
2163           break;
2164         }
2165     }
2166   if (CCID_COMMAND_FAILED (buffer))
2167     {
2168       int ec;
2169 
2170       ec = CCID_ERROR_CODE (buffer);
2171       print_command_failed (buffer);
2172       if (ec == 0xEF)
2173         return CCID_DRIVER_ERR_UI_CANCELLED;
2174       else if (ec == 0xF0)
2175         return CCID_DRIVER_ERR_UI_TIMEOUT;
2176     }
2177 
2178   /* Check whether a card is at all available.  Note: If you add new
2179      error codes here, check whether they need to be ignored in
2180      send_escape_cmd. */
2181   switch ((buffer[7] & 0x03))
2182     {
2183     case 0: /* no error */ break;
2184     case 1: rc = CCID_DRIVER_ERR_CARD_INACTIVE; break;
2185     case 2: rc = CCID_DRIVER_ERR_NO_CARD; break;
2186     case 3: /* RFU */ break;
2187     }
2188 
2189   if (rc)
2190     {
2191       /*
2192        * Communication failure by device side.
2193        * Possibly, it was forcibly suspended and resumed.
2194        */
2195       if (handle->ep_intr < 0)
2196         {
2197           DEBUGOUT ("CCID: card inactive/removed\n");
2198           handle->powered_off = 1;
2199         }
2200 
2201 #if defined(GNUPG_MAJOR_VERSION)
2202       scd_kick_the_loop ();
2203 #endif
2204     }
2205 
2206   return rc;
2207 }
2208 
2209 
2210 
2211 /* Send an abort sequence and wait until everything settled.  */
2212 static int
abort_cmd(ccid_driver_t handle,int seqno,int init)2213 abort_cmd (ccid_driver_t handle, int seqno, int init)
2214 {
2215   int rc;
2216   unsigned char dummybuf[8];
2217   unsigned char msg[100];
2218   int msglen;
2219 
2220   seqno &= 0xff;
2221   DEBUGOUT_1 ("sending abort sequence for seqno %d\n", seqno);
2222   /* Send the abort command to the control pipe.  Note that we don't
2223      need to keep track of sent abort commands because there should
2224      never be another thread using the same slot concurrently.  */
2225 #ifdef USE_NPTH
2226   npth_unprotect ();
2227 #endif
2228   rc = libusb_control_transfer (handle->idev,
2229                                 0x21,/* bmRequestType: host-to-device,
2230                                         class specific, to interface.  */
2231                                 1,   /* ABORT */
2232                                 (seqno << 8 | 0 /* slot */),
2233                                 handle->ifc_no,
2234                                 dummybuf, 0,
2235                                 1000 /* ms timeout */);
2236 #ifdef USE_NPTH
2237   npth_protect ();
2238 #endif
2239   if (rc)
2240     {
2241       DEBUGOUT_1 ("usb_control_msg error: %s\n", libusb_error_name (rc));
2242       if (!init)
2243         return map_libusb_error (rc);
2244     }
2245 
2246   /* Now send the abort command to the bulk out pipe using the same
2247      SEQNO and SLOT.  Do this in a loop to so that all seqno are
2248      tried.  */
2249   seqno--;  /* Adjust for next increment.  */
2250   do
2251     {
2252       int transferred;
2253 
2254       seqno++;
2255       msg[0] = PC_to_RDR_Abort;
2256       msg[5] = 0; /* slot */
2257       msg[6] = seqno;
2258       msg[7] = 0; /* RFU */
2259       msg[8] = 0; /* RFU */
2260       msg[9] = 0; /* RFU */
2261       msglen = 10;
2262       set_msg_len (msg, 0);
2263 
2264 #ifdef USE_NPTH
2265       npth_unprotect ();
2266 #endif
2267       rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_out,
2268                                  msg, msglen, &transferred,
2269                                  init? 100: 5000 /* ms timeout */);
2270 #ifdef USE_NPTH
2271       npth_protect ();
2272 #endif
2273       if (rc == 0 && transferred == msglen)
2274         rc = 0;
2275       else if (rc)
2276         DEBUGOUT_1 ("usb_bulk_write error in abort_cmd: %s\n",
2277                     libusb_error_name (rc));
2278 
2279       if (rc)
2280         return map_libusb_error (rc);
2281 
2282 #ifdef USE_NPTH
2283       npth_unprotect ();
2284 #endif
2285       rc = libusb_bulk_transfer (handle->idev, handle->ep_bulk_in,
2286                                  msg, sizeof msg, &msglen,
2287                                  init? 100: 5000 /*ms timeout*/);
2288 #ifdef USE_NPTH
2289       npth_protect ();
2290 #endif
2291       if (rc)
2292         {
2293           DEBUGOUT_1 ("usb_bulk_read error in abort_cmd: %s\n",
2294                       libusb_error_name (rc));
2295           if (init && rc == LIBUSB_ERROR_TIMEOUT)
2296             continue;
2297           else
2298             return map_libusb_error (rc);
2299         }
2300 
2301       if (msglen < 10)
2302         {
2303           DEBUGOUT_1 ("bulk-in msg in abort_cmd too short (%u)\n",
2304                       (unsigned int)msglen);
2305           return CCID_DRIVER_ERR_INV_VALUE;
2306         }
2307       if (msg[5] != 0)
2308         {
2309           DEBUGOUT_1 ("unexpected bulk-in slot (%d) in abort_cmd\n", msg[5]);
2310           return CCID_DRIVER_ERR_INV_VALUE;
2311         }
2312 
2313       DEBUGOUT_3 ("status: %02X  error: %02X  octet[9]: %02X\n",
2314                   msg[7], msg[8], msg[9]);
2315       if (CCID_COMMAND_FAILED (msg))
2316         print_command_failed (msg);
2317     }
2318   while (rc == LIBUSB_ERROR_TIMEOUT
2319          || (msg[0] != RDR_to_PC_SlotStatus && msg[5] != 0 && msg[6] != seqno));
2320 
2321   handle->seqno = ((seqno + 1) & 0xff);
2322   DEBUGOUT ("sending abort sequence succeeded\n");
2323 
2324   return 0;
2325 }
2326 
2327 
2328 /* Note that this function won't return the error codes NO_CARD or
2329    CARD_INACTIVE.  IF RESULT is not NULL, the result from the
2330    operation will get returned in RESULT and its length in RESULTLEN.
2331    If the response is larger than RESULTMAX, an error is returned and
2332    the required buffer length returned in RESULTLEN.  */
2333 static int
send_escape_cmd(ccid_driver_t handle,const unsigned char * data,size_t datalen,unsigned char * result,size_t resultmax,size_t * resultlen)2334 send_escape_cmd (ccid_driver_t handle,
2335                  const unsigned char *data, size_t datalen,
2336                  unsigned char *result, size_t resultmax, size_t *resultlen)
2337 {
2338   int rc;
2339   unsigned char msg[100];
2340   size_t msglen;
2341   unsigned char seqno;
2342 
2343   if (resultlen)
2344     *resultlen = 0;
2345 
2346   if (datalen > sizeof msg - 10)
2347     return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large.  */
2348 
2349   msg[0] = PC_to_RDR_Escape;
2350   msg[5] = 0; /* slot */
2351   msg[6] = seqno = handle->seqno++;
2352   msg[7] = 0; /* RFU */
2353   msg[8] = 0; /* RFU */
2354   msg[9] = 0; /* RFU */
2355   memcpy (msg+10, data, datalen);
2356   msglen = 10 + datalen;
2357   set_msg_len (msg, datalen);
2358 
2359   rc = bulk_out (handle, msg, msglen, 0);
2360   if (rc)
2361     return rc;
2362   rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape,
2363                 seqno, 5000, 0);
2364   if (result)
2365     switch (rc)
2366       {
2367         /* We need to ignore certain errorcode here. */
2368       case 0:
2369       case CCID_DRIVER_ERR_CARD_INACTIVE:
2370       case CCID_DRIVER_ERR_NO_CARD:
2371         {
2372           if (msglen > resultmax)
2373             rc = CCID_DRIVER_ERR_INV_VALUE; /* Response too large. */
2374           else
2375             {
2376               memcpy (result, msg, msglen);
2377               if (resultlen)
2378                 *resultlen = msglen;
2379               rc = 0;
2380             }
2381         }
2382         break;
2383       default:
2384         break;
2385       }
2386 
2387   return rc;
2388 }
2389 
2390 
2391 int
ccid_transceive_escape(ccid_driver_t handle,const unsigned char * data,size_t datalen,unsigned char * resp,size_t maxresplen,size_t * nresp)2392 ccid_transceive_escape (ccid_driver_t handle,
2393                         const unsigned char *data, size_t datalen,
2394                         unsigned char *resp, size_t maxresplen, size_t *nresp)
2395 {
2396   return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp);
2397 }
2398 
2399 
2400 
2401 /* experimental */
2402 int
ccid_poll(ccid_driver_t handle)2403 ccid_poll (ccid_driver_t handle)
2404 {
2405   int rc;
2406   unsigned char msg[10];
2407   int msglen;
2408   int i, j;
2409 
2410   rc = libusb_interrupt_transfer (handle->idev, handle->ep_intr,
2411                                   msg, sizeof msg, &msglen,
2412                                   0 /* ms timeout */ );
2413   if (rc == LIBUSB_ERROR_TIMEOUT)
2414     return 0;
2415 
2416   if (rc)
2417     {
2418       DEBUGOUT_1 ("usb_intr_read error: %s\n", libusb_error_name (rc));
2419       return CCID_DRIVER_ERR_CARD_IO_ERROR;
2420     }
2421 
2422   if (msglen < 1)
2423     {
2424       DEBUGOUT ("intr-in msg too short\n");
2425       return CCID_DRIVER_ERR_INV_VALUE;
2426     }
2427 
2428   if (msg[0] == RDR_to_PC_NotifySlotChange)
2429     {
2430       DEBUGOUT ("notify slot change:");
2431       for (i=1; i < msglen; i++)
2432         for (j=0; j < 4; j++)
2433           DEBUGOUT_CONT_3 (" %d:%c%c",
2434                            (i-1)*4+j,
2435                            (msg[i] & (1<<(j*2)))? 'p':'-',
2436                            (msg[i] & (2<<(j*2)))? '*':' ');
2437       DEBUGOUT_LF ();
2438     }
2439   else if (msg[0] == RDR_to_PC_HardwareError)
2440     {
2441       DEBUGOUT ("hardware error occurred\n");
2442     }
2443   else
2444     {
2445       DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]);
2446     }
2447 
2448   return 0;
2449 }
2450 
2451 
2452 /* Note that this function won't return the error codes NO_CARD or
2453    CARD_INACTIVE */
2454 int
ccid_slot_status(ccid_driver_t handle,int * statusbits,int on_wire)2455 ccid_slot_status (ccid_driver_t handle, int *statusbits, int on_wire)
2456 {
2457   int rc;
2458   unsigned char msg[100];
2459   size_t msglen;
2460   unsigned char seqno;
2461   int retries = 0;
2462 
2463   if (handle->powered_off)
2464     return CCID_DRIVER_ERR_NO_READER;
2465 
2466   /* If the card (with its lower-level driver) doesn't require
2467      GET_STATUS on wire (because it supports INTERRUPT transfer for
2468      status change, or it's a token which has a card always inserted),
2469      no need to send on wire.  */
2470   if (!on_wire && !ccid_require_get_status (handle))
2471     {
2472       /* Setup interrupt transfer at the initial call of slot_status
2473          with ON_WIRE == 0 */
2474       if (handle->transfer == NULL)
2475         ccid_setup_intr (handle);
2476 
2477       *statusbits = 0;
2478       return 0;
2479     }
2480 
2481  retry:
2482   msg[0] = PC_to_RDR_GetSlotStatus;
2483   msg[5] = 0; /* slot */
2484   msg[6] = seqno = handle->seqno++;
2485   msg[7] = 0; /* RFU */
2486   msg[8] = 0; /* RFU */
2487   msg[9] = 0; /* RFU */
2488   set_msg_len (msg, 0);
2489 
2490   rc = bulk_out (handle, msg, 10, 1);
2491   if (rc)
2492     return rc;
2493   /* Note that we set the NO_DEBUG flag here, so that the logs won't
2494      get cluttered up by a ticker function checking for the slot
2495      status and debugging enabled. */
2496   rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
2497                 seqno, retries? 1000 : 200, 1);
2498   if ((rc == CCID_DRIVER_ERR_CARD_IO_ERROR || rc == CCID_DRIVER_ERR_USB_TIMEOUT)
2499       && retries < 3)
2500     {
2501       if (!retries)
2502         {
2503           DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n");
2504 #ifdef USE_NPTH
2505           npth_unprotect ();
2506 #endif
2507           libusb_clear_halt (handle->idev, handle->ep_bulk_in);
2508           libusb_clear_halt (handle->idev, handle->ep_bulk_out);
2509 #ifdef USE_NPTH
2510           npth_protect ();
2511 #endif
2512         }
2513       else
2514         DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n");
2515       retries++;
2516       goto retry;
2517     }
2518   if (rc && rc != CCID_DRIVER_ERR_NO_CARD && rc != CCID_DRIVER_ERR_CARD_INACTIVE)
2519     return rc;
2520   *statusbits = (msg[7] & 3);
2521 
2522   return 0;
2523 }
2524 
2525 
2526 /* Parse ATR string (of ATRLEN) and update parameters at PARAM.
2527    Calling this routine, it should prepare default values at PARAM
2528    beforehand.  This routine assumes that card is accessed by T=1
2529    protocol.  It doesn't analyze historical bytes at all.
2530 
2531    Returns < 0 value on error:
2532      -1 for parse error or integrity check error
2533      -2 for card doesn't support T=1 protocol
2534      -3 for parameters are nod explicitly defined by ATR
2535      -4 for this driver doesn't support CRC
2536 
2537    Returns >= 0 on success:
2538       0 for card is negotiable mode
2539       1 for card is specific mode (and not negotiable)
2540  */
2541 static int
update_param_by_atr(unsigned char * param,unsigned char * atr,size_t atrlen)2542 update_param_by_atr (unsigned char *param, unsigned char *atr, size_t atrlen)
2543 {
2544   int i = -1;
2545   int t, y, chk;
2546   int historical_bytes_num, negotiable = 1;
2547 
2548 #define NEXTBYTE() do { i++; if (atrlen <= i) return -1; } while (0)
2549 
2550   NEXTBYTE ();
2551 
2552   if (atr[i] == 0x3F)
2553     param[1] |= 0x02;           /* Convention is inverse.  */
2554   NEXTBYTE ();
2555 
2556   y = (atr[i] >> 4);
2557   historical_bytes_num = atr[i] & 0x0f;
2558   NEXTBYTE ();
2559 
2560   if ((y & 1))
2561     {
2562       param[0] = atr[i];        /* TA1 - Fi & Di */
2563       NEXTBYTE ();
2564     }
2565 
2566   if ((y & 2))
2567     NEXTBYTE ();                /* TB1 - ignore */
2568 
2569   if ((y & 4))
2570     {
2571       param[2] = atr[i];        /* TC1 - Guard Time */
2572       NEXTBYTE ();
2573     }
2574 
2575   if ((y & 8))
2576     {
2577       y = (atr[i] >> 4);        /* TD1 */
2578       t = atr[i] & 0x0f;
2579       NEXTBYTE ();
2580 
2581       if ((y & 1))
2582         {                       /* TA2 - PPS mode */
2583           if ((atr[i] & 0x0f) != 1)
2584             return -2;          /* Wrong card protocol (!= 1).  */
2585 
2586           if ((atr[i] & 0x10) != 0x10)
2587             return -3; /* Transmission parameters are implicitly defined. */
2588 
2589           negotiable = 0;       /* TA2 means specific mode.  */
2590           NEXTBYTE ();
2591         }
2592 
2593       if ((y & 2))
2594         NEXTBYTE ();            /* TB2 - ignore */
2595 
2596       if ((y & 4))
2597         NEXTBYTE ();            /* TC2 - ignore */
2598 
2599       if ((y & 8))
2600         {
2601           y = (atr[i] >> 4);    /* TD2 */
2602           t = atr[i] & 0x0f;
2603           NEXTBYTE ();
2604         }
2605       else
2606         y = 0;
2607 
2608       while (y)
2609         {
2610           if ((y & 1))
2611             {                   /* TAx */
2612               if (t == 1)
2613                 param[5] = atr[i]; /* IFSC */
2614               else if (t == 15)
2615                 /* XXX: check voltage? */
2616                 param[4] = (atr[i] >> 6); /* ClockStop */
2617 
2618               NEXTBYTE ();
2619             }
2620 
2621           if ((y & 2))
2622             {
2623               if (t == 1)
2624                 param[3] = atr[i]; /* TBx - BWI & CWI */
2625               NEXTBYTE ();
2626             }
2627 
2628           if ((y & 4))
2629             {
2630               if (t == 1)
2631                 param[1] |= (atr[i] & 0x01); /* TCx - LRC/CRC */
2632               NEXTBYTE ();
2633 
2634               if (param[1] & 0x01)
2635                 return -4;      /* CRC not supported yet.  */
2636             }
2637 
2638           if ((y & 8))
2639             {
2640               y = (atr[i] >> 4); /* TDx */
2641               t = atr[i] & 0x0f;
2642               NEXTBYTE ();
2643             }
2644           else
2645             y = 0;
2646         }
2647     }
2648 
2649   i += historical_bytes_num - 1;
2650   NEXTBYTE ();
2651   if (atrlen != i+1)
2652     return -1;
2653 
2654 #undef NEXTBYTE
2655 
2656   chk = 0;
2657   do
2658     {
2659       chk ^= atr[i];
2660       i--;
2661     }
2662   while (i > 0);
2663 
2664   if (chk != 0)
2665     return -1;
2666 
2667   return negotiable;
2668 }
2669 
2670 
2671 /* Return the ATR of the card.  This is not a cached value and thus an
2672    actual reset is done.  */
2673 int
ccid_get_atr(ccid_driver_t handle,unsigned char * atr,size_t maxatrlen,size_t * atrlen)2674 ccid_get_atr (ccid_driver_t handle,
2675               unsigned char *atr, size_t maxatrlen, size_t *atrlen)
2676 {
2677   int rc;
2678   int statusbits;
2679   unsigned char msg[100];
2680   unsigned char *tpdu;
2681   size_t msglen, tpdulen;
2682   unsigned char seqno;
2683   int use_crc = 0;
2684   unsigned int edc;
2685   int tried_iso = 0;
2686   int got_param;
2687   unsigned char param[7] = { /* For Protocol T=1 */
2688     0x11, /* bmFindexDindex */
2689     0x10, /* bmTCCKST1 */
2690     0x00, /* bGuardTimeT1 */
2691     0x4d, /* bmWaitingIntegersT1 */
2692     0x00, /* bClockStop */
2693     0x20, /* bIFSC */
2694     0x00  /* bNadValue */
2695   };
2696 
2697   /* First check whether a card is available.  */
2698   rc = ccid_slot_status (handle, &statusbits, 1);
2699   if (rc)
2700     return rc;
2701   if (statusbits == 2)
2702     return CCID_DRIVER_ERR_NO_CARD;
2703 
2704   /*
2705    * In the first invocation of ccid_slot_status, card reader may
2706    * return CCID_DRIVER_ERR_CARD_INACTIVE and handle->powered_off may
2707    * become 1.  Because inactive card is no problem (we are turning it
2708    * ON here), clear the flag.
2709    */
2710   handle->powered_off = 0;
2711 
2712   /* For an inactive and also for an active card, issue the PowerOn
2713      command to get the ATR.  */
2714  again:
2715   msg[0] = PC_to_RDR_IccPowerOn;
2716   msg[5] = 0; /* slot */
2717   msg[6] = seqno = handle->seqno++;
2718   /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */
2719   msg[7] = handle->auto_voltage ? 0 : 1;
2720   msg[8] = 0; /* RFU */
2721   msg[9] = 0; /* RFU */
2722   set_msg_len (msg, 0);
2723   msglen = 10;
2724 
2725   rc = bulk_out (handle, msg, msglen, 0);
2726   if (rc)
2727     return rc;
2728   rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2729                 seqno, 5000, 0);
2730   if (rc)
2731     return rc;
2732   if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb
2733       && ((handle->id_vendor == VENDOR_CHERRY
2734            && handle->id_product == 0x0005)
2735           || (handle->id_vendor == VENDOR_GEMPC
2736               && handle->id_product == 0x4433)
2737           ))
2738     {
2739       tried_iso = 1;
2740       /* Try switching to ISO mode. */
2741       if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2,
2742                             NULL, 0, NULL))
2743         goto again;
2744     }
2745   else if (statusbits == 0 && CCID_COMMAND_FAILED (msg))
2746     {
2747       /* Card was active already, and something went wrong with
2748          PC_to_RDR_IccPowerOn command.  It may be baud-rate mismatch
2749          between the card and the reader.  To recover from this state,
2750          send PC_to_RDR_IccPowerOff command to reset the card and try
2751          again.
2752        */
2753       rc = send_power_off (handle);
2754       if (rc)
2755         return rc;
2756 
2757       statusbits = 1;
2758       goto again;
2759     }
2760   else if (CCID_COMMAND_FAILED (msg))
2761     return CCID_DRIVER_ERR_CARD_IO_ERROR;
2762 
2763 
2764   handle->powered_off = 0;
2765 
2766   if (atr)
2767     {
2768       size_t n = msglen - 10;
2769 
2770       if (n > maxatrlen)
2771         n = maxatrlen;
2772       memcpy (atr, msg+10, n);
2773       *atrlen = n;
2774     }
2775 
2776   param[6] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2777   rc = update_param_by_atr (param, msg+10, msglen - 10);
2778   if (rc < 0)
2779     {
2780       DEBUGOUT_1 ("update_param_by_atr failed: %d\n", rc);
2781       return CCID_DRIVER_ERR_CARD_IO_ERROR;
2782     }
2783 
2784   got_param = 0;
2785 
2786   if (handle->auto_param)
2787     {
2788       msg[0] = PC_to_RDR_GetParameters;
2789       msg[5] = 0; /* slot */
2790       msg[6] = seqno = handle->seqno++;
2791       msg[7] = 0; /* RFU */
2792       msg[8] = 0; /* RFU */
2793       msg[9] = 0; /* RFU */
2794       set_msg_len (msg, 0);
2795       msglen = 10;
2796       rc = bulk_out (handle, msg, msglen, 0);
2797       if (!rc)
2798         rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2799                       seqno, 2000, 0);
2800       if (rc)
2801         DEBUGOUT ("GetParameters failed\n");
2802       else if (msglen == 17 && msg[9] == 1)
2803         got_param = 1;
2804     }
2805   else if (handle->auto_pps)
2806     ;
2807   else if (rc == 1)             /* It's negotiable, send PPS.  */
2808     {
2809       msg[0] = PC_to_RDR_XfrBlock;
2810       msg[5] = 0; /* slot */
2811       msg[6] = seqno = handle->seqno++;
2812       msg[7] = 0;
2813       msg[8] = 0;
2814       msg[9] = 0;
2815       msg[10] = 0xff;           /* PPSS */
2816       msg[11] = 0x11;           /* PPS0: PPS1, Protocol T=1 */
2817       msg[12] = param[0];       /* PPS1: Fi / Di */
2818       msg[13] = 0xff ^ 0x11 ^ param[0]; /* PCK */
2819       set_msg_len (msg, 4);
2820       msglen = 10 + 4;
2821 
2822       rc = bulk_out (handle, msg, msglen, 0);
2823       if (rc)
2824         return rc;
2825 
2826       rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2827                     seqno, 5000, 0);
2828       if (rc)
2829         return rc;
2830 
2831       if (msglen != 10 + 4)
2832         {
2833           DEBUGOUT_1 ("Setting PPS failed: %zu\n", msglen);
2834           return CCID_DRIVER_ERR_CARD_IO_ERROR;
2835         }
2836 
2837       if (msg[10] != 0xff || msg[11] != 0x11 || msg[12] != param[0])
2838         {
2839           DEBUGOUT_1 ("Setting PPS failed: 0x%02x\n", param[0]);
2840           return CCID_DRIVER_ERR_CARD_IO_ERROR;
2841         }
2842     }
2843 
2844   /* Setup parameters to select T=1. */
2845   msg[0] = PC_to_RDR_SetParameters;
2846   msg[5] = 0; /* slot */
2847   msg[6] = seqno = handle->seqno++;
2848   msg[7] = 1; /* Select T=1. */
2849   msg[8] = 0; /* RFU */
2850   msg[9] = 0; /* RFU */
2851 
2852   if (!got_param)
2853     memcpy (&msg[10], param, 7);
2854   set_msg_len (msg, 7);
2855   msglen = 10 + 7;
2856 
2857   rc = bulk_out (handle, msg, msglen, 0);
2858   if (rc)
2859     return rc;
2860   rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2861                 seqno, 5000, 0);
2862   if (rc)
2863     DEBUGOUT ("SetParameters failed (ignored)\n");
2864 
2865   if (!rc && msglen > 15 && msg[15] >= 16 && msg[15] <= 254 )
2866     handle->ifsc = msg[15];
2867   else
2868     handle->ifsc = 128; /* Something went wrong, assume 128 bytes.  */
2869 
2870   if (handle->nonnull_nad && msglen > 16 && msg[16] == 0)
2871     {
2872       DEBUGOUT ("Use Null-NAD, clearing handle->nonnull_nad.\n");
2873       handle->nonnull_nad = 0;
2874     }
2875 
2876   handle->t1_ns = 0;
2877   handle->t1_nr = 0;
2878 
2879   /* Send an S-Block with our maximum IFSD to the CCID.  */
2880   if (!handle->apdu_level && !handle->auto_ifsd)
2881     {
2882       tpdu = msg+10;
2883       /* NAD: DAD=1, SAD=0 */
2884       tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2885       tpdu[1] = (0xc0 | 0 | 1); /* S-block request: change IFSD */
2886       tpdu[2] = 1;
2887       tpdu[3] = handle->max_ifsd? handle->max_ifsd : 32;
2888       tpdulen = 4;
2889       edc = compute_edc (tpdu, tpdulen, use_crc);
2890       if (use_crc)
2891         tpdu[tpdulen++] = (edc >> 8);
2892       tpdu[tpdulen++] = edc;
2893 
2894       msg[0] = PC_to_RDR_XfrBlock;
2895       msg[5] = 0; /* slot */
2896       msg[6] = seqno = handle->seqno++;
2897       msg[7] = 0;
2898       msg[8] = 0; /* RFU */
2899       msg[9] = 0; /* RFU */
2900       set_msg_len (msg, tpdulen);
2901       msglen = 10 + tpdulen;
2902 
2903       if (debug_level > 1)
2904         DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
2905                       ((msg[11] & 0xc0) == 0x80)? 'R' :
2906                                 (msg[11] & 0x80)? 'S' : 'I',
2907                       ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2908                                        : !!(msg[11] & 0x40)),
2909                     (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2910 
2911       rc = bulk_out (handle, msg, msglen, 0);
2912       if (rc)
2913         return rc;
2914 
2915 
2916       rc = bulk_in (handle, msg, sizeof msg, &msglen,
2917                     RDR_to_PC_DataBlock, seqno, 5000, 0);
2918       if (rc)
2919         return rc;
2920 
2921       tpdu = msg + 10;
2922       tpdulen = msglen - 10;
2923 
2924       if (tpdulen < 4)
2925         return CCID_DRIVER_ERR_ABORTED;
2926 
2927       if (debug_level > 1)
2928         DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2929                     ((msg[11] & 0xc0) == 0x80)? 'R' :
2930                               (msg[11] & 0x80)? 'S' : 'I',
2931                     ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2932                                      : !!(msg[11] & 0x40)),
2933                     ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2934                     (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2935 
2936       if ((tpdu[1] & 0xe0) != 0xe0 || tpdu[2] != 1)
2937         {
2938           DEBUGOUT ("invalid response for S-block (Change-IFSD)\n");
2939           return -1;
2940         }
2941       DEBUGOUT_1 ("IFSD has been set to %d\n", tpdu[3]);
2942     }
2943 
2944   ccid_vendor_specific_setup (handle);
2945   return 0;
2946 }
2947 
2948 
2949 
2950 
2951 static unsigned int
compute_edc(const unsigned char * data,size_t datalen,int use_crc)2952 compute_edc (const unsigned char *data, size_t datalen, int use_crc)
2953 {
2954   if (use_crc)
2955     {
2956       return 0x42; /* Not yet implemented. */
2957     }
2958   else
2959     {
2960       unsigned char crc = 0;
2961 
2962       for (; datalen; datalen--)
2963         crc ^= *data++;
2964       return crc;
2965     }
2966 }
2967 
2968 
2969 /* Return true if APDU is an extended length one.  */
2970 static int
is_exlen_apdu(const unsigned char * apdu,size_t apdulen)2971 is_exlen_apdu (const unsigned char *apdu, size_t apdulen)
2972 {
2973   if (apdulen < 7 || apdu[4])
2974     return 0;  /* Too short or no Z byte.  */
2975   return 1;
2976 }
2977 
2978 
2979 /* Helper for ccid_transceive used for APDU level exchanges.  */
2980 static int
ccid_transceive_apdu_level(ccid_driver_t handle,const unsigned char * apdu_buf,size_t apdu_len,unsigned char * resp,size_t maxresplen,size_t * nresp)2981 ccid_transceive_apdu_level (ccid_driver_t handle,
2982                             const unsigned char *apdu_buf, size_t apdu_len,
2983                             unsigned char *resp, size_t maxresplen,
2984                             size_t *nresp)
2985 {
2986   int rc;
2987   unsigned char msg[CCID_MAX_BUF];
2988   const unsigned char *apdu_p;
2989   size_t apdu_part_len;
2990   size_t msglen;
2991   unsigned char seqno;
2992   int bwi = 0;
2993   unsigned char chain = 0;
2994 
2995   if (apdu_len == 0 || apdu_len > sizeof (msg) - 10)
2996     return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
2997 
2998   apdu_p = apdu_buf;
2999   while (1)
3000     {
3001       apdu_part_len = apdu_len;
3002       if (apdu_part_len > handle->max_ccid_msglen - 10)
3003         {
3004           apdu_part_len = handle->max_ccid_msglen - 10;
3005           chain |= 0x01;
3006         }
3007 
3008       msg[0] = PC_to_RDR_XfrBlock;
3009       msg[5] = 0; /* slot */
3010       msg[6] = seqno = handle->seqno++;
3011       msg[7] = bwi;
3012       msg[8] = chain;
3013       msg[9] = 0;
3014       memcpy (msg+10, apdu_p, apdu_part_len);
3015       set_msg_len (msg, apdu_part_len);
3016       msglen = 10 + apdu_part_len;
3017 
3018       rc = bulk_out (handle, msg, msglen, 0);
3019       if (rc)
3020         return rc;
3021 
3022       apdu_p += apdu_part_len;
3023       apdu_len -= apdu_part_len;
3024 
3025       rc = bulk_in (handle, msg, sizeof msg, &msglen,
3026                     RDR_to_PC_DataBlock, seqno, CCID_CMD_TIMEOUT, 0);
3027       if (rc)
3028         return rc;
3029 
3030       if (!(chain & 0x01))
3031         break;
3032 
3033       chain = 0x02;
3034     }
3035 
3036   apdu_len = 0;
3037   while (1)
3038     {
3039       apdu_part_len = msglen - 10;
3040       if (resp && apdu_len + apdu_part_len <= maxresplen)
3041         memcpy (resp + apdu_len, msg+10, apdu_part_len);
3042       apdu_len += apdu_part_len;
3043 
3044       if (!(msg[9] & 0x01))
3045         break;
3046 
3047       msg[0] = PC_to_RDR_XfrBlock;
3048       msg[5] = 0; /* slot */
3049       msg[6] = seqno = handle->seqno++;
3050       msg[7] = bwi;
3051       msg[8] = 0x10;                /* Request next data block */
3052       msg[9] = 0;
3053       set_msg_len (msg, 0);
3054       msglen = 10;
3055 
3056       rc = bulk_out (handle, msg, msglen, 0);
3057       if (rc)
3058         return rc;
3059 
3060       rc = bulk_in (handle, msg, sizeof msg, &msglen,
3061                     RDR_to_PC_DataBlock, seqno, CCID_CMD_TIMEOUT, 0);
3062       if (rc)
3063         return rc;
3064     }
3065 
3066   if (resp)
3067     {
3068       if (apdu_len > maxresplen)
3069         {
3070           DEBUGOUT_2 ("provided buffer too short for received data "
3071                       "(%u/%u)\n",
3072                       (unsigned int)apdu_len, (unsigned int)maxresplen);
3073           return CCID_DRIVER_ERR_INV_VALUE;
3074         }
3075 
3076       *nresp = apdu_len;
3077     }
3078 
3079   return 0;
3080 }
3081 
3082 
3083 
3084 /*
3085   Protocol T=1 overview
3086 
3087   Block Structure:
3088            Prologue Field:
3089    1 byte     Node Address (NAD)
3090    1 byte     Protocol Control Byte (PCB)
3091    1 byte     Length (LEN)
3092            Information Field:
3093    0-254 byte APDU or Control Information (INF)
3094            Epilogue Field:
3095    1 byte     Error Detection Code (EDC)
3096 
3097   NAD:
3098    bit 7     unused
3099    bit 4..6  Destination Node Address (DAD)
3100    bit 3     unused
3101    bit 2..0  Source Node Address (SAD)
3102 
3103    If node addresses are not used, SAD and DAD should be set to 0 on
3104    the first block sent to the card.  If they are used they should
3105    have different values (0 for one is okay); that first block sets up
3106    the addresses of the nodes.
3107 
3108   PCB:
3109    Information Block (I-Block):
3110       bit 7    0
3111       bit 6    Sequence number (yep, that is modulo 2)
3112       bit 5    Chaining flag
3113       bit 4..0 reserved
3114    Received-Ready Block (R-Block):
3115       bit 7    1
3116       bit 6    0
3117       bit 5    0
3118       bit 4    Sequence number
3119       bit 3..0  0 = no error
3120                 1 = EDC or parity error
3121                 2 = other error
3122                 other values are reserved
3123    Supervisory Block (S-Block):
3124       bit 7    1
3125       bit 6    1
3126       bit 5    clear=request,set=response
3127       bit 4..0  0 = resynchronization request
3128                 1 = information field size request
3129                 2 = abort request
3130                 3 = extension of BWT request
3131                 4 = VPP error
3132                 other values are reserved
3133 
3134 */
3135 
3136 int
ccid_transceive(ccid_driver_t handle,const unsigned char * apdu_buf,size_t apdu_buflen,unsigned char * resp,size_t maxresplen,size_t * nresp)3137 ccid_transceive (ccid_driver_t handle,
3138                  const unsigned char *apdu_buf, size_t apdu_buflen,
3139                  unsigned char *resp, size_t maxresplen, size_t *nresp)
3140 {
3141   int rc;
3142   /* The size of the buffer used to be 10+259.  For the via_escape
3143      hack we need one extra byte, thus 11+259.  */
3144   unsigned char send_buffer[11+259], recv_buffer[11+259];
3145   const unsigned char *apdu;
3146   size_t apdulen;
3147   unsigned char *msg, *tpdu, *p;
3148   size_t msglen, tpdulen, last_tpdulen, n;
3149   unsigned char seqno;
3150   unsigned int edc;
3151   int use_crc = 0;
3152   int hdrlen, pcboff;
3153   size_t dummy_nresp;
3154   int via_escape = 0;
3155   int next_chunk = 1;
3156   int sending = 1;
3157   int retries = 0;
3158   int resyncing = 0;
3159   int nad_byte;
3160   int wait_more = 0;
3161 
3162   if (!nresp)
3163     nresp = &dummy_nresp;
3164   *nresp = 0;
3165 
3166   /* Smarter readers allow sending APDUs directly; divert here. */
3167   if (handle->apdu_level)
3168     {
3169       /* We employ a hack for Omnikey readers which are able to send
3170          TPDUs using an escape sequence.  There is no documentation
3171          but the Windows driver does it this way.  Tested using a
3172          CM6121.  This method works also for the Cherry XX44
3173          keyboards; however there are problems with the
3174          ccid_transceive_secure which leads to a loss of sync on the
3175          CCID level.  If Cherry wants to make their keyboard work
3176          again, they should hand over some docs. */
3177       if ((handle->id_vendor == VENDOR_OMNIKEY)
3178           && handle->apdu_level < 2
3179           && is_exlen_apdu (apdu_buf, apdu_buflen))
3180         via_escape = 1;
3181       else
3182         return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen,
3183                                            resp, maxresplen, nresp);
3184     }
3185 
3186   /* The other readers we support require sending TPDUs.  */
3187 
3188   tpdulen = 0; /* Avoid compiler warning about no initialization. */
3189   msg = send_buffer;
3190   hdrlen = via_escape? 11 : 10;
3191 
3192   /* NAD: DAD=1, SAD=0 */
3193   nad_byte = handle->nonnull_nad? ((1 << 4) | 0): 0;
3194   if (via_escape)
3195     nad_byte = 0;
3196 
3197   last_tpdulen = 0;  /* Avoid gcc warning (controlled by RESYNCING). */
3198   for (;;)
3199     {
3200       if (next_chunk)
3201         {
3202           next_chunk = 0;
3203 
3204           apdu = apdu_buf;
3205           apdulen = apdu_buflen;
3206           log_assert (apdulen);
3207 
3208           /* Construct an I-Block. */
3209           tpdu = msg + hdrlen;
3210           tpdu[0] = nad_byte;
3211           tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */
3212           if (apdulen > handle->ifsc )
3213             {
3214               apdulen = handle->ifsc;
3215               apdu_buf += handle->ifsc;
3216               apdu_buflen -= handle->ifsc;
3217               tpdu[1] |= (1 << 5); /* Set more bit. */
3218             }
3219           tpdu[2] = apdulen;
3220           memcpy (tpdu+3, apdu, apdulen);
3221           tpdulen = 3 + apdulen;
3222           edc = compute_edc (tpdu, tpdulen, use_crc);
3223           if (use_crc)
3224             tpdu[tpdulen++] = (edc >> 8);
3225           tpdu[tpdulen++] = edc;
3226         }
3227 
3228       if (via_escape)
3229         {
3230           msg[0] = PC_to_RDR_Escape;
3231           msg[5] = 0; /* slot */
3232           msg[6] = seqno = handle->seqno++;
3233           msg[7] = 0; /* RFU */
3234           msg[8] = 0; /* RFU */
3235           msg[9] = 0; /* RFU */
3236           msg[10] = 0x1a; /* Omnikey command to send a TPDU.  */
3237           set_msg_len (msg, 1 + tpdulen);
3238         }
3239       else
3240         {
3241           msg[0] = PC_to_RDR_XfrBlock;
3242           msg[5] = 0; /* slot */
3243           msg[6] = seqno = handle->seqno++;
3244           msg[7] = wait_more; /* bBWI */
3245           msg[8] = 0; /* RFU */
3246           msg[9] = 0; /* RFU */
3247           set_msg_len (msg, tpdulen);
3248         }
3249       msglen = hdrlen + tpdulen;
3250       if (!resyncing)
3251         last_tpdulen = tpdulen;
3252       pcboff = hdrlen+1;
3253 
3254       if (debug_level > 1)
3255         DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
3256                     ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
3257                     (msg[pcboff] & 0x80)? 'S' : 'I',
3258                     ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
3259                      : !!(msg[pcboff] & 0x40)),
3260                     (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
3261                      " [more]":""));
3262 
3263       rc = bulk_out (handle, msg, msglen, 0);
3264       if (rc)
3265         return rc;
3266 
3267       msg = recv_buffer;
3268       rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3269                     via_escape? RDR_to_PC_Escape : RDR_to_PC_DataBlock, seqno,
3270                     (wait_more ? wait_more : 1) * CCID_CMD_TIMEOUT, 0);
3271       if (rc)
3272         return rc;
3273 
3274       tpdu = msg + hdrlen;
3275       tpdulen = msglen - hdrlen;
3276       resyncing = 0;
3277 
3278       if (tpdulen < 4)
3279         {
3280 #ifdef USE_NPTH
3281           npth_unprotect ();
3282 #endif
3283           libusb_clear_halt (handle->idev, handle->ep_bulk_in);
3284 #ifdef USE_NPTH
3285           npth_protect ();
3286 #endif
3287           return CCID_DRIVER_ERR_ABORTED;
3288         }
3289 
3290       if (debug_level > 1)
3291         DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3292                     ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
3293                               (msg[pcboff] & 0x80)? 'S' : 'I',
3294                     ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
3295                      : !!(msg[pcboff] & 0x40)),
3296                     ((msg[pcboff] & 0xc0) == 0x80)? (msg[pcboff] & 0x0f) : 0,
3297                     (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
3298                      " [more]":""));
3299 
3300       wait_more = 0;
3301       if (!(tpdu[1] & 0x80))
3302         { /* This is an I-block. */
3303           retries = 0;
3304           if (sending)
3305             { /* last block sent was successful. */
3306               handle->t1_ns ^= 1;
3307               sending = 0;
3308             }
3309 
3310           if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3311             { /* Response does not match our sequence number. */
3312               msg = send_buffer;
3313               tpdu = msg + hdrlen;
3314               tpdu[0] = nad_byte;
3315               tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */
3316               tpdu[2] = 0;
3317               tpdulen = 3;
3318               edc = compute_edc (tpdu, tpdulen, use_crc);
3319               if (use_crc)
3320                 tpdu[tpdulen++] = (edc >> 8);
3321               tpdu[tpdulen++] = edc;
3322 
3323               continue;
3324             }
3325 
3326           handle->t1_nr ^= 1;
3327 
3328           p = tpdu + 3; /* Skip the prologue field. */
3329           n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3330           /* fixme: verify the checksum. */
3331           if (resp)
3332             {
3333               if (n > maxresplen)
3334                 {
3335                   DEBUGOUT_2 ("provided buffer too short for received data "
3336                               "(%u/%u)\n",
3337                               (unsigned int)n, (unsigned int)maxresplen);
3338                   return CCID_DRIVER_ERR_INV_VALUE;
3339                 }
3340 
3341               memcpy (resp, p, n);
3342               resp += n;
3343               *nresp += n;
3344               maxresplen -= n;
3345             }
3346 
3347           if (!(tpdu[1] & 0x20))
3348             return 0; /* No chaining requested - ready. */
3349 
3350           msg = send_buffer;
3351           tpdu = msg + hdrlen;
3352           tpdu[0] = nad_byte;
3353           tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */
3354           tpdu[2] = 0;
3355           tpdulen = 3;
3356           edc = compute_edc (tpdu, tpdulen, use_crc);
3357           if (use_crc)
3358             tpdu[tpdulen++] = (edc >> 8);
3359           tpdu[tpdulen++] = edc;
3360         }
3361       else if ((tpdu[1] & 0xc0) == 0x80)
3362         { /* This is a R-block. */
3363           if ( (tpdu[1] & 0x0f))
3364             {
3365               retries++;
3366               if (via_escape && retries == 1 && (msg[pcboff] & 0x0f))
3367                 {
3368                   /* Error probably due to switching to TPDU.  Send a
3369                      resync request.  We use the recv_buffer so that
3370                      we don't corrupt the send_buffer.  */
3371                   msg = recv_buffer;
3372                   tpdu = msg + hdrlen;
3373                   tpdu[0] = nad_byte;
3374                   tpdu[1] = 0xc0; /* S-block resync request. */
3375                   tpdu[2] = 0;
3376                   tpdulen = 3;
3377                   edc = compute_edc (tpdu, tpdulen, use_crc);
3378                   if (use_crc)
3379                     tpdu[tpdulen++] = (edc >> 8);
3380                   tpdu[tpdulen++] = edc;
3381                   resyncing = 1;
3382                   DEBUGOUT ("T=1: requesting resync\n");
3383                 }
3384               else if (retries > 3)
3385                 {
3386                   DEBUGOUT ("T=1: 3 failed retries\n");
3387                   return CCID_DRIVER_ERR_CARD_IO_ERROR;
3388                 }
3389               else
3390                 {
3391                   /* Error: repeat last block */
3392                   msg = send_buffer;
3393                   tpdulen = last_tpdulen;
3394                 }
3395             }
3396           else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns)
3397             { /* Response does not match our sequence number. */
3398               DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3399               return CCID_DRIVER_ERR_CARD_IO_ERROR;
3400             }
3401           else if (sending)
3402             { /* Send next chunk. */
3403               retries = 0;
3404               msg = send_buffer;
3405               next_chunk = 1;
3406               handle->t1_ns ^= 1;
3407             }
3408           else
3409             {
3410               DEBUGOUT ("unexpected ACK R-block received\n");
3411               return CCID_DRIVER_ERR_CARD_IO_ERROR;
3412             }
3413         }
3414       else
3415         { /* This is a S-block. */
3416           retries = 0;
3417           DEBUGOUT_2 ("T=1: S-block %s received cmd=%d\n",
3418                       (tpdu[1] & 0x20)? "response": "request",
3419                       (tpdu[1] & 0x1f));
3420           if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 1 && tpdu[2] == 1)
3421             {
3422               /* Information field size request.  */
3423               unsigned char ifsc = tpdu[3];
3424 
3425               if (ifsc < 16 || ifsc > 254)
3426                 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3427 
3428               msg = send_buffer;
3429               tpdu = msg + hdrlen;
3430               tpdu[0] = nad_byte;
3431               tpdu[1] = (0xc0 | 0x20 | 1); /* S-block response */
3432               tpdu[2] = 1;
3433               tpdu[3] = ifsc;
3434               tpdulen = 4;
3435               edc = compute_edc (tpdu, tpdulen, use_crc);
3436               if (use_crc)
3437                 tpdu[tpdulen++] = (edc >> 8);
3438               tpdu[tpdulen++] = edc;
3439               DEBUGOUT_1 ("T=1: requesting an ifsc=%d\n", ifsc);
3440             }
3441           else if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2])
3442             {
3443               /* Wait time extension request. */
3444               unsigned char bwi = tpdu[3];
3445 
3446 	      wait_more = bwi;
3447 
3448               msg = send_buffer;
3449               tpdu = msg + hdrlen;
3450               tpdu[0] = nad_byte;
3451               tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */
3452               tpdu[2] = 1;
3453               tpdu[3] = bwi;
3454               tpdulen = 4;
3455               edc = compute_edc (tpdu, tpdulen, use_crc);
3456               if (use_crc)
3457                 tpdu[tpdulen++] = (edc >> 8);
3458               tpdu[tpdulen++] = edc;
3459               DEBUGOUT_1 ("T=1: waittime extension of bwi=%d\n", bwi);
3460               print_progress (handle);
3461             }
3462           else if ( (tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 0 && !tpdu[2])
3463             {
3464               DEBUGOUT ("T=1: resync ack from reader\n");
3465               /* Repeat previous block.  */
3466               msg = send_buffer;
3467               tpdulen = last_tpdulen;
3468             }
3469           else
3470             return CCID_DRIVER_ERR_CARD_IO_ERROR;
3471         }
3472     } /* end T=1 protocol loop. */
3473 
3474   return 0;
3475 }
3476 
3477 
3478 /* Send the CCID Secure command to the reader.  APDU_BUF should
3479    contain the APDU template.  PIN_MODE defines how the pin gets
3480    formatted:
3481 
3482      1 := The PIN is ASCII encoded and of variable length.  The
3483           length of the PIN entered will be put into Lc by the reader.
3484           The APDU should me made up of 4 bytes without Lc.
3485 
3486    PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0
3487    may be used t enable reasonable defaults.
3488 
3489    When called with RESP and NRESP set to NULL, the function will
3490    merely check whether the reader supports the secure command for the
3491    given APDU and PIN_MODE. */
3492 int
ccid_transceive_secure(ccid_driver_t handle,const unsigned char * apdu_buf,size_t apdu_buflen,pininfo_t * pininfo,unsigned char * resp,size_t maxresplen,size_t * nresp)3493 ccid_transceive_secure (ccid_driver_t handle,
3494                         const unsigned char *apdu_buf, size_t apdu_buflen,
3495                         pininfo_t *pininfo,
3496                         unsigned char *resp, size_t maxresplen, size_t *nresp)
3497 {
3498   int rc;
3499   unsigned char send_buffer[10+259], recv_buffer[10+259];
3500   unsigned char *msg, *tpdu, *p;
3501   size_t msglen, tpdulen, n;
3502   unsigned char seqno;
3503   size_t dummy_nresp;
3504   int testmode;
3505   int cherry_mode = 0;
3506   int add_zero = 0;
3507   int enable_varlen = 0;
3508 
3509   testmode = !resp && !nresp;
3510 
3511   if (!nresp)
3512     nresp = &dummy_nresp;
3513   *nresp = 0;
3514 
3515   if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1))
3516     ;
3517   else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2))
3518     ;
3519   else
3520     return CCID_DRIVER_ERR_NO_PINPAD;
3521 
3522   if (!pininfo->minlen)
3523     pininfo->minlen = 1;
3524   if (!pininfo->maxlen)
3525     pininfo->maxlen = 15;
3526 
3527   /* Note that the 25 is the maximum value the SPR532 allows.  */
3528   if (pininfo->minlen < 1 || pininfo->minlen > 25
3529       || pininfo->maxlen < 1 || pininfo->maxlen > 25
3530       || pininfo->minlen > pininfo->maxlen)
3531     return CCID_DRIVER_ERR_INV_VALUE;
3532 
3533   /* We have only tested a few readers so better don't risk anything
3534      and do not allow the use with other readers. */
3535   switch (handle->id_vendor)
3536     {
3537     case VENDOR_SCM:  /* Tested with SPR 532. */
3538     case VENDOR_KAAN: /* Tested with KAAN Advanced (1.02). */
3539     case VENDOR_FSIJ: /* Tested with Gnuk (0.21). */
3540       pininfo->maxlen = 25;
3541       enable_varlen = 1;
3542       break;
3543     case VENDOR_REINER:/* Tested with cyberJack go */
3544     case VENDOR_VASCO: /* Tested with DIGIPASS 920 */
3545       enable_varlen = 1;
3546       break;
3547     case VENDOR_CHERRY:
3548       pininfo->maxlen = 15;
3549       enable_varlen = 1;
3550       /* The CHERRY XX44 keyboard echos an asterisk for each entered
3551          character on the keyboard channel.  We use a special variant
3552          of PC_to_RDR_Secure which directs these characters to the
3553          smart card's bulk-in channel.  We also need to append a zero
3554          Lc byte to the APDU.  It seems that it will be replaced with
3555          the actual length instead of being appended before the APDU
3556          is send to the card. */
3557       add_zero = 1;
3558       if (handle->id_product != CHERRY_ST2000)
3559         cherry_mode = 1;
3560       break;
3561     case VENDOR_NXP:
3562       if (handle->id_product == CRYPTOUCAN)
3563         {
3564           pininfo->maxlen = 25;
3565           enable_varlen = 1;
3566           break;
3567         }
3568       return CCID_DRIVER_ERR_NOT_SUPPORTED;
3569     case VENDOR_GEMPC:
3570       if (handle->id_product == GEMPC_PINPAD)
3571         {
3572           enable_varlen = 0;
3573           pininfo->minlen = 4;
3574           pininfo->maxlen = 8;
3575           break;
3576         }
3577       else if (handle->id_product == GEMPC_EZIO)
3578         {
3579           pininfo->maxlen = 25;
3580           enable_varlen = 1;
3581           break;
3582         }
3583       return CCID_DRIVER_ERR_NOT_SUPPORTED;
3584     default:
3585       if ((handle->id_vendor == VENDOR_VEGA &&
3586            handle->id_product == VEGA_ALPHA))
3587         {
3588           enable_varlen = 0;
3589           pininfo->minlen = 4;
3590           pininfo->maxlen = 8;
3591           break;
3592         }
3593      return CCID_DRIVER_ERR_NOT_SUPPORTED;
3594     }
3595 
3596   if (enable_varlen)
3597     pininfo->fixedlen = 0;
3598 
3599   if (testmode)
3600     return 0; /* Success */
3601 
3602   if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
3603     return CCID_DRIVER_ERR_NOT_SUPPORTED;
3604 
3605   ccid_vendor_specific_pinpad_setup (handle);
3606 
3607   msg = send_buffer;
3608   msg[0] = cherry_mode? 0x89 : PC_to_RDR_Secure;
3609   msg[5] = 0; /* slot */
3610   msg[6] = seqno = handle->seqno++;
3611   msg[7] = 0; /* bBWI */
3612   msg[8] = 0; /* RFU */
3613   msg[9] = 0; /* RFU */
3614   msg[10] = apdu_buf[1] == 0x20 ? 0 : 1;
3615                /* Perform PIN verification or PIN modification. */
3616   msg[11] = 0; /* Timeout in seconds. */
3617   msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
3618   if (handle->id_vendor == VENDOR_SCM)
3619     {
3620       /* For the SPR532 the next 2 bytes need to be zero.  We do this
3621          for all SCM products.  Kudos to Martin Paljak for this
3622          hint.  */
3623       msg[13] = msg[14] = 0;
3624     }
3625   else
3626     {
3627       msg[13] = pininfo->fixedlen; /* bmPINBlockString:
3628                                       0 bits of pin length to insert.
3629                                       PIN block size by fixedlen.  */
3630       msg[14] = 0x00; /* bmPINLengthFormat:
3631                          Units are bytes, position is 0. */
3632     }
3633 
3634   msglen = 15;
3635   if (apdu_buf[1] == 0x24)
3636     {
3637       msg[msglen++] = 0;    /* bInsertionOffsetOld */
3638       msg[msglen++] = pininfo->fixedlen;    /* bInsertionOffsetNew */
3639     }
3640 
3641   /* The following is a little endian word. */
3642   msg[msglen++] = pininfo->maxlen;   /* wPINMaxExtraDigit-Maximum.  */
3643   msg[msglen++] = pininfo->minlen;   /* wPINMaxExtraDigit-Minimum.  */
3644 
3645   if (apdu_buf[1] == 0x24)
3646     msg[msglen++] = apdu_buf[2] == 0 ? 0x03 : 0x01;
3647               /* bConfirmPIN
3648                *    0x00: new PIN once
3649                *    0x01: new PIN twice (confirmation)
3650                *    0x02: old PIN and new PIN once
3651                *    0x03: old PIN and new PIN twice (confirmation)
3652                */
3653 
3654   msg[msglen] = 0x02; /* bEntryValidationCondition:
3655                          Validation key pressed */
3656   if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
3657     msg[msglen] |= 0x01; /* Max size reached.  */
3658   msglen++;
3659 
3660   if (apdu_buf[1] == 0x20)
3661     msg[msglen++] = 0x01; /* bNumberMessage. */
3662   else
3663     msg[msglen++] = 0x03; /* bNumberMessage. */
3664 
3665   msg[msglen++] = 0x09; /* wLangId-Low:  English FIXME: use the first entry. */
3666   msg[msglen++] = 0x04; /* wLangId-High. */
3667 
3668   if (apdu_buf[1] == 0x20)
3669     msg[msglen++] = 0;    /* bMsgIndex. */
3670   else
3671     {
3672       msg[msglen++] = 0;    /* bMsgIndex1. */
3673       msg[msglen++] = 1;    /* bMsgIndex2. */
3674       msg[msglen++] = 2;    /* bMsgIndex3. */
3675     }
3676 
3677   /* Calculate Lc.  */
3678   n = pininfo->fixedlen;
3679   if (apdu_buf[1] == 0x24)
3680     n += pininfo->fixedlen;
3681 
3682   /* bTeoProlog follows: */
3683   msg[msglen++] = handle->nonnull_nad? ((1 << 4) | 0): 0;
3684   msg[msglen++] = ((handle->t1_ns & 1) << 6); /* I-block */
3685   if (n)
3686     msg[msglen++] = n + 5; /* apdulen should be filled for fixed length.  */
3687   else
3688     msg[msglen++] = 0; /* The apdulen will be filled in by the reader.  */
3689   /* APDU follows:  */
3690   msg[msglen++] = apdu_buf[0]; /* CLA */
3691   msg[msglen++] = apdu_buf[1]; /* INS */
3692   msg[msglen++] = apdu_buf[2]; /* P1 */
3693   msg[msglen++] = apdu_buf[3]; /* P2 */
3694   if (add_zero)
3695     msg[msglen++] = 0;
3696   else if (pininfo->fixedlen != 0)
3697     {
3698       msg[msglen++] = n;
3699       memset (&msg[msglen], 0xff, n);
3700       msglen += n;
3701     }
3702   /* An EDC is not required. */
3703   set_msg_len (msg, msglen - 10);
3704 
3705   rc = bulk_out (handle, msg, msglen, 0);
3706   if (rc)
3707     return rc;
3708 
3709   msg = recv_buffer;
3710   rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3711                 RDR_to_PC_DataBlock, seqno, 30000, 0);
3712   if (rc)
3713     return rc;
3714 
3715   tpdu = msg + 10;
3716   tpdulen = msglen - 10;
3717 
3718   if (handle->apdu_level)
3719     {
3720       if (resp)
3721         {
3722           if (tpdulen > maxresplen)
3723             {
3724               DEBUGOUT_2 ("provided buffer too short for received data "
3725                           "(%u/%u)\n",
3726                           (unsigned int)tpdulen, (unsigned int)maxresplen);
3727               return CCID_DRIVER_ERR_INV_VALUE;
3728             }
3729 
3730           memcpy (resp, tpdu, tpdulen);
3731           *nresp = tpdulen;
3732         }
3733       return 0;
3734     }
3735 
3736   if (tpdulen < 4)
3737     {
3738 #ifdef USE_NPTH
3739       npth_unprotect ();
3740 #endif
3741       libusb_clear_halt (handle->idev, handle->ep_bulk_in);
3742 #ifdef USE_NPTH
3743       npth_protect ();
3744 #endif
3745       return CCID_DRIVER_ERR_ABORTED;
3746     }
3747   if (debug_level > 1)
3748     DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3749                 ((msg[11] & 0xc0) == 0x80)? 'R' :
3750                           (msg[11] & 0x80)? 'S' : 'I',
3751                 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
3752                 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
3753                 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
3754 
3755   if (!(tpdu[1] & 0x80))
3756     { /* This is an I-block. */
3757       /* Last block sent was successful. */
3758       handle->t1_ns ^= 1;
3759 
3760       if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3761         { /* Response does not match our sequence number. */
3762           DEBUGOUT ("I-block with wrong seqno received\n");
3763           return CCID_DRIVER_ERR_CARD_IO_ERROR;
3764         }
3765 
3766       handle->t1_nr ^= 1;
3767 
3768       p = tpdu + 3; /* Skip the prologue field. */
3769       n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3770       /* fixme: verify the checksum. */
3771       if (resp)
3772         {
3773           if (n > maxresplen)
3774             {
3775               DEBUGOUT_2 ("provided buffer too short for received data "
3776                           "(%u/%u)\n",
3777                           (unsigned int)n, (unsigned int)maxresplen);
3778               return CCID_DRIVER_ERR_INV_VALUE;
3779             }
3780 
3781           memcpy (resp, p, n);
3782           *nresp += n;
3783         }
3784 
3785       if (!(tpdu[1] & 0x20))
3786         return 0; /* No chaining requested - ready. */
3787 
3788       DEBUGOUT ("chaining requested but not supported for Secure operation\n");
3789       return CCID_DRIVER_ERR_CARD_IO_ERROR;
3790     }
3791   else if ((tpdu[1] & 0xc0) == 0x80)
3792     { /* This is a R-block. */
3793       if ( (tpdu[1] & 0x0f))
3794         { /* Error: repeat last block */
3795           DEBUGOUT ("No retries supported for Secure operation\n");
3796           return CCID_DRIVER_ERR_CARD_IO_ERROR;
3797         }
3798       else if (!!(tpdu[1] & 0x10) == handle->t1_ns)
3799         { /* Response does not match our sequence number. */
3800           DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3801           return CCID_DRIVER_ERR_CARD_IO_ERROR;
3802         }
3803       else
3804         { /* Send next chunk. */
3805           DEBUGOUT ("chaining not supported on Secure operation\n");
3806           return CCID_DRIVER_ERR_CARD_IO_ERROR;
3807         }
3808     }
3809   else
3810     { /* This is a S-block. */
3811       DEBUGOUT_2 ("T=1: S-block %s received cmd=%d for Secure operation\n",
3812                   (tpdu[1] & 0x20)? "response": "request",
3813                   (tpdu[1] & 0x1f));
3814       return CCID_DRIVER_ERR_CARD_IO_ERROR;
3815     }
3816 
3817   return 0;
3818 }
3819 
3820 
3821 
3822 
3823 #ifdef TEST
3824 
3825 
3826 static void
print_error(int err)3827 print_error (int err)
3828 {
3829   const char *p;
3830   char buf[50];
3831 
3832   switch (err)
3833     {
3834     case 0: p = "success"; break;
3835     case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break;
3836     case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break;
3837     case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break;
3838     case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break;
3839     case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break;
3840     case CCID_DRIVER_ERR_BUSY: p = "busy"; break;
3841     case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break;
3842     case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break;
3843     case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break;
3844     case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break;
3845     case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break;
3846     case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break;
3847     default: sprintf (buf, "0x%05x", err); p = buf; break;
3848     }
3849   fprintf (stderr, "operation failed: %s\n", p);
3850 }
3851 
3852 
3853 static void
print_data(const unsigned char * data,size_t length)3854 print_data (const unsigned char *data, size_t length)
3855 {
3856   if (length >= 2)
3857     {
3858       fprintf (stderr, "operation status: %02X%02X\n",
3859                data[length-2], data[length-1]);
3860       length -= 2;
3861     }
3862   if (length)
3863     {
3864         fputs ("   returned data:", stderr);
3865         for (; length; length--, data++)
3866           fprintf (stderr, " %02X", *data);
3867         putc ('\n', stderr);
3868     }
3869 }
3870 
3871 static void
print_result(int rc,const unsigned char * data,size_t length)3872 print_result (int rc, const unsigned char *data, size_t length)
3873 {
3874   if (rc)
3875     print_error (rc);
3876   else if (data)
3877     print_data (data, length);
3878 }
3879 
3880 int
main(int argc,char ** argv)3881 main (int argc, char **argv)
3882 {
3883   gpg_error_t err;
3884   ccid_driver_t ccid;
3885   int slotstat;
3886   unsigned char result[512];
3887   size_t resultlen;
3888   int no_pinpad = 0;
3889   int verify_123456 = 0;
3890   int did_verify = 0;
3891   int no_poll = 0;
3892   int idx_max;
3893   struct ccid_dev_table *ccid_table;
3894 
3895   if (argc)
3896     {
3897       argc--;
3898       argv++;
3899     }
3900 
3901   while (argc)
3902     {
3903       if ( !strcmp (*argv, "--list"))
3904         {
3905           char *p;
3906           p = ccid_get_reader_list ();
3907           if (!p)
3908             return 1;
3909           fputs (p, stderr);
3910           free (p);
3911           return 0;
3912         }
3913       else if ( !strcmp (*argv, "--debug"))
3914         {
3915           ccid_set_debug_level (ccid_set_debug_level (-1)+1);
3916           argc--; argv++;
3917         }
3918       else if ( !strcmp (*argv, "--no-poll"))
3919         {
3920           no_poll = 1;
3921           argc--; argv++;
3922         }
3923       else if ( !strcmp (*argv, "--no-pinpad"))
3924         {
3925           no_pinpad = 1;
3926           argc--; argv++;
3927         }
3928       else if ( !strcmp (*argv, "--verify-123456"))
3929         {
3930           verify_123456 = 1;
3931           argc--; argv++;
3932         }
3933       else
3934         break;
3935     }
3936 
3937   err = ccid_dev_scan (&idx_max, &ccid_table);
3938   if (err)
3939     return 1;
3940 
3941   if (idx_max == 0)
3942     return 1;
3943 
3944   err = ccid_open_reader (argc? *argv:NULL, 0, ccid_table, &ccid, NULL);
3945   if (err)
3946     return 1;
3947 
3948   ccid_dev_scan_finish (ccid_table, idx_max);
3949 
3950   if (!no_poll)
3951     ccid_poll (ccid);
3952   fputs ("getting ATR ...\n", stderr);
3953   err = ccid_get_atr (ccid, NULL, 0, NULL);
3954   if (err)
3955     {
3956       print_error (err);
3957       return 1;
3958     }
3959 
3960   if (!no_poll)
3961     ccid_poll (ccid);
3962   fputs ("getting slot status ...\n", stderr);
3963   err = ccid_slot_status (ccid, &slotstat, 1);
3964   if (err)
3965     {
3966       print_error (err);
3967       return 1;
3968     }
3969 
3970   if (!no_poll)
3971     ccid_poll (ccid);
3972 
3973   fputs ("selecting application OpenPGP ....\n", stderr);
3974   {
3975     static unsigned char apdu[] = {
3976       0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01};
3977     err = ccid_transceive (ccid,
3978                            apdu, sizeof apdu,
3979                            result, sizeof result, &resultlen);
3980     print_result (err, result, resultlen);
3981   }
3982 
3983 
3984   if (!no_poll)
3985     ccid_poll (ccid);
3986 
3987   fputs ("getting OpenPGP DO 0x65 ....\n", stderr);
3988   {
3989     static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 };
3990     err = ccid_transceive (ccid, apdu, sizeof apdu,
3991                            result, sizeof result, &resultlen);
3992     print_result (err, result, resultlen);
3993   }
3994 
3995   if (!no_pinpad)
3996     {
3997     }
3998 
3999   if (!no_pinpad)
4000     {
4001       static unsigned char apdu[] = { 0, 0x20, 0, 0x81 };
4002       pininfo_t pininfo = { 0, 0, 0 };
4003 
4004       if (ccid_transceive_secure (ccid, apdu, sizeof apdu, &pininfo,
4005                                   NULL, 0, NULL))
4006         fputs ("can't verify using a PIN-Pad reader\n", stderr);
4007       else
4008         {
4009            fputs ("verifying CHV1 using the PINPad ....\n", stderr);
4010 
4011           err = ccid_transceive_secure (ccid, apdu, sizeof apdu, &pininfo,
4012                                         result, sizeof result, &resultlen);
4013           print_result (err, result, resultlen);
4014           did_verify = 1;
4015         }
4016     }
4017 
4018   if (verify_123456 && !did_verify)
4019     {
4020       fputs ("verifying that CHV1 is 123456....\n", stderr);
4021       {
4022         static unsigned char apdu[] = {0, 0x20, 0, 0x81,
4023                                        6, '1','2','3','4','5','6'};
4024         err = ccid_transceive (ccid, apdu, sizeof apdu,
4025                                result, sizeof result, &resultlen);
4026         print_result (err, result, resultlen);
4027       }
4028     }
4029 
4030   if (!err)
4031     {
4032       fputs ("getting OpenPGP DO 0x5E ....\n", stderr);
4033       {
4034         static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 };
4035         err = ccid_transceive (ccid, apdu, sizeof apdu,
4036                                result, sizeof result, &resultlen);
4037         print_result (err, result, resultlen);
4038       }
4039     }
4040 
4041   ccid_close_reader (ccid);
4042 
4043   return 0;
4044 }
4045 
4046 /*
4047  * Local Variables:
4048  *  compile-command: "gcc -DTEST -DGPGRT_ENABLE_ES_MACROS -DHAVE_NPTH -DUSE_NPTH -Wall -I/usr/include/libusb-1.0 -I/usr/local/include -lusb-1.0 -g ccid-driver.c -lnpth -lgpg-error"
4049  * End:
4050  */
4051 #endif /*TEST*/
4052 #endif /*HAVE_LIBUSB*/
4053