1 /* iso7816.c - ISO 7816 commands
2  * Copyright (C) 2003, 2004, 2008, 2009 Free Software Foundation, Inc.
3  *
4  * This file is part of GnuPG.
5  *
6  * GnuPG is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * GnuPG is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see <http://www.gnu.org/licenses/>.
18  *
19  * $Id$
20  */
21 
22 #include <config.h>
23 #include <errno.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 
28 #if defined(GNUPG_SCD_MAIN_HEADER)
29 #include GNUPG_SCD_MAIN_HEADER
30 #elif GNUPG_MAJOR_VERSION == 1
31 /* This is used with GnuPG version < 1.9.  The code has been source
32    copied from the current GnuPG >= 1.9  and is maintained over
33    there. */
34 #include "options.h"
35 #include "errors.h"
36 #include "memory.h"
37 #include "util.h"
38 #include "i18n.h"
39 #else /* GNUPG_MAJOR_VERSION != 1 */
40 #include "scdaemon.h"
41 #endif /* GNUPG_MAJOR_VERSION != 1 */
42 
43 #include "iso7816.h"
44 #include "apdu.h"
45 
46 
47 #define CMD_SELECT_FILE 0xA4
48 #define CMD_VERIFY                ISO7816_VERIFY
49 #define CMD_CHANGE_REFERENCE_DATA ISO7816_CHANGE_REFERENCE_DATA
50 #define CMD_RESET_RETRY_COUNTER   ISO7816_RESET_RETRY_COUNTER
51 #define CMD_GET_DATA    0xCA
52 #define CMD_PUT_DATA    0xDA
53 #define CMD_MSE         0x22
54 #define CMD_PSO         0x2A
55 #define CMD_INTERNAL_AUTHENTICATE 0x88
56 #define CMD_GENERATE_KEYPAIR      0x47
57 #define CMD_GET_CHALLENGE         0x84
58 #define CMD_READ_BINARY 0xB0
59 #define CMD_READ_RECORD 0xB2
60 
61 static gpg_error_t
map_sw(int sw)62 map_sw (int sw)
63 {
64   gpg_err_code_t ec;
65 
66   switch (sw)
67     {
68     case SW_EEPROM_FAILURE: ec = GPG_ERR_HARDWARE; break;
69     case SW_TERM_STATE:     ec = GPG_ERR_CARD; break;
70     case SW_WRONG_LENGTH:   ec = GPG_ERR_INV_VALUE; break;
71     case SW_SM_NOT_SUP:     ec = GPG_ERR_NOT_SUPPORTED; break;
72     case SW_CC_NOT_SUP:     ec = GPG_ERR_NOT_SUPPORTED; break;
73     case SW_CHV_WRONG:      ec = GPG_ERR_BAD_PIN; break;
74     case SW_CHV_BLOCKED:    ec = GPG_ERR_PIN_BLOCKED; break;
75     case SW_USE_CONDITIONS: ec = GPG_ERR_USE_CONDITIONS; break;
76     case SW_NOT_SUPPORTED:  ec = GPG_ERR_NOT_SUPPORTED; break;
77     case SW_BAD_PARAMETER:  ec = GPG_ERR_INV_VALUE; break;
78     case SW_FILE_NOT_FOUND: ec = GPG_ERR_ENOENT; break;
79     case SW_RECORD_NOT_FOUND:ec= GPG_ERR_NOT_FOUND; break;
80     case SW_REF_NOT_FOUND:  ec = GPG_ERR_NO_OBJ; break;
81     case SW_BAD_P0_P1:      ec = GPG_ERR_INV_VALUE; break;
82     case SW_EXACT_LENGTH:   ec = GPG_ERR_INV_VALUE; break;
83     case SW_INS_NOT_SUP:    ec = GPG_ERR_CARD; break;
84     case SW_CLA_NOT_SUP:    ec = GPG_ERR_CARD; break;
85     case SW_SUCCESS:        ec = 0; break;
86 
87     case SW_HOST_OUT_OF_CORE: ec = GPG_ERR_ENOMEM; break;
88     case SW_HOST_INV_VALUE:   ec = GPG_ERR_INV_VALUE; break;
89     case SW_HOST_INCOMPLETE_CARD_RESPONSE: ec = GPG_ERR_CARD; break;
90     case SW_HOST_NOT_SUPPORTED: ec = GPG_ERR_NOT_SUPPORTED; break;
91     case SW_HOST_LOCKING_FAILED: ec = GPG_ERR_BUG; break;
92     case SW_HOST_BUSY:           ec = GPG_ERR_EBUSY; break;
93     case SW_HOST_NO_CARD:        ec = GPG_ERR_CARD_NOT_PRESENT; break;
94     case SW_HOST_CARD_INACTIVE:  ec = GPG_ERR_CARD_RESET; break;
95     case SW_HOST_CARD_IO_ERROR:  ec = GPG_ERR_EIO; break;
96     case SW_HOST_GENERAL_ERROR:  ec = GPG_ERR_GENERAL; break;
97     case SW_HOST_NO_READER:      ec = GPG_ERR_ENODEV; break;
98     case SW_HOST_ABORTED:        ec = GPG_ERR_CANCELED; break;
99     case SW_HOST_NO_KEYPAD:      ec = GPG_ERR_NOT_SUPPORTED; break;
100 
101     default:
102       if ((sw & 0x010000))
103         ec = GPG_ERR_GENERAL; /* Should not happen. */
104       else if ((sw & 0xff00) == SW_MORE_DATA)
105         ec = 0; /* This should actually never been seen here. */
106       else
107         ec = GPG_ERR_CARD;
108     }
109   return gpg_error (ec);
110 }
111 
112 /* Map a status word from the APDU layer to a gpg-error code.  */
113 gpg_error_t
iso7816_map_sw(int sw)114 iso7816_map_sw (int sw)
115 {
116   /* All APDU functions should return 0x9000 on success but for
117      historical reasons of the implementation some return 0 to
118      indicate success.  We allow for that here. */
119   return sw? map_sw (sw) : 0;
120 }
121 
122 
123 /* This function is specialized version of the SELECT FILE command.
124    SLOT is the card and reader as created for example by
125    apdu_open_reader (), AID is a buffer of size AIDLEN holding the
126    requested application ID.  The function can't be used to enumerate
127    AIDs and won't return the AID on success.  The return value is 0
128    for okay or a GPG error code.  Note that ISO error codes are
129    internally mapped.  Bit 0 of FLAGS should be set if the card does
130    not understand P2=0xC0. */
131 gpg_error_t
iso7816_select_application(int slot,const char * aid,size_t aidlen,unsigned int flags)132 iso7816_select_application (int slot, const char *aid, size_t aidlen,
133                             unsigned int flags)
134 {
135   int sw;
136   sw = apdu_send_simple (slot, 0, 0x00, CMD_SELECT_FILE, 4,
137                          (flags&1)? 0 :0x0c, aidlen, aid);
138   return map_sw (sw);
139 }
140 
141 
142 gpg_error_t
iso7816_select_file(int slot,int tag,int is_dir,unsigned char ** result,size_t * resultlen)143 iso7816_select_file (int slot, int tag, int is_dir,
144                      unsigned char **result, size_t *resultlen)
145 {
146   int sw, p0, p1;
147   unsigned char tagbuf[2];
148 
149   tagbuf[0] = (tag >> 8) & 0xff;
150   tagbuf[1] = tag & 0xff;
151 
152   if (result || resultlen)
153     {
154       *result = NULL;
155       *resultlen = 0;
156       return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
157     }
158   else
159     {
160       p0 = (tag == 0x3F00)? 0: is_dir? 1:2;
161       p1 = 0x0c; /* No FC return. */
162       sw = apdu_send_simple (slot, 0, 0x00, CMD_SELECT_FILE,
163                              p0, p1, 2, (char*)tagbuf );
164       return map_sw (sw);
165     }
166 
167   return 0;
168 }
169 
170 
171 /* Do a select file command with a direct path. */
172 gpg_error_t
iso7816_select_path(int slot,const unsigned short * path,size_t pathlen,unsigned char ** result,size_t * resultlen)173 iso7816_select_path (int slot, const unsigned short *path, size_t pathlen,
174                      unsigned char **result, size_t *resultlen)
175 {
176   int sw, p0, p1;
177   unsigned char buffer[100];
178   int buflen;
179 
180   if (result || resultlen)
181     {
182       *result = NULL;
183       *resultlen = 0;
184       return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
185     }
186 
187   if (pathlen/2 >= sizeof buffer)
188     return gpg_error (GPG_ERR_TOO_LARGE);
189 
190   for (buflen = 0; pathlen; pathlen--, path++)
191     {
192       buffer[buflen++] = (*path >> 8);
193       buffer[buflen++] = *path;
194     }
195 
196   p0 = 0x08;
197   p1 = 0x0c; /* No FC return. */
198   sw = apdu_send_simple (slot, 0, 0x00, CMD_SELECT_FILE,
199                          p0, p1, buflen, (char*)buffer );
200   return map_sw (sw);
201 }
202 
203 
204 /* This is a private command currently only working for TCOS cards. */
205 gpg_error_t
iso7816_list_directory(int slot,int list_dirs,unsigned char ** result,size_t * resultlen)206 iso7816_list_directory (int slot, int list_dirs,
207                         unsigned char **result, size_t *resultlen)
208 {
209   int sw;
210 
211   if (!result || !resultlen)
212     return gpg_error (GPG_ERR_INV_VALUE);
213   *result = NULL;
214   *resultlen = 0;
215 
216   sw = apdu_send (slot, 0, 0x80, 0xAA, list_dirs? 1:2, 0, -1, NULL,
217                   result, resultlen);
218   if (sw != SW_SUCCESS)
219     {
220       /* Make sure that pending buffers are released. */
221       xfree (*result);
222       *result = NULL;
223       *resultlen = 0;
224     }
225   return map_sw (sw);
226 }
227 
228 
229 /* This funcion sends an already formatted APDU to the card.  With
230    HANDLE_MORE set to true a MORE DATA status will be handled
231    internally.  The return value is a gpg error code (i.e. a mapped
232    status word).  This is basically the same as apdu_send_direct but
233    it maps the status word and does not return it in the result
234    buffer.  */
235 gpg_error_t
iso7816_apdu_direct(int slot,const void * apdudata,size_t apdudatalen,int handle_more,unsigned char ** result,size_t * resultlen)236 iso7816_apdu_direct (int slot, const void *apdudata, size_t apdudatalen,
237                      int handle_more,
238                      unsigned char **result, size_t *resultlen)
239 {
240   int sw;
241 
242   if (!result || !resultlen)
243     return gpg_error (GPG_ERR_INV_VALUE);
244   *result = NULL;
245   *resultlen = 0;
246 
247   sw = apdu_send_direct (slot, 0, apdudata, apdudatalen, handle_more,
248                          result, resultlen);
249   if (!sw)
250     {
251       if (*resultlen < 2)
252         sw = SW_HOST_GENERAL_ERROR;
253       else
254         {
255           sw = ((*result)[*resultlen-2] << 8) | (*result)[*resultlen-1];
256           (*resultlen)--;
257           (*resultlen)--;
258         }
259     }
260   if (sw != SW_SUCCESS)
261     {
262       /* Make sure that pending buffers are released. */
263       xfree (*result);
264       *result = NULL;
265       *resultlen = 0;
266     }
267   return map_sw (sw);
268 }
269 
270 
271 /* Check whether the reader supports the ISO command code COMMAND on
272    the keypad.  Returns 0 on success.  */
273 gpg_error_t
iso7816_check_keypad(int slot,int command,iso7816_pininfo_t * pininfo)274 iso7816_check_keypad (int slot, int command, iso7816_pininfo_t *pininfo)
275 {
276   int sw;
277 
278   sw = apdu_check_keypad (slot, command,
279                           pininfo->mode, pininfo->minlen, pininfo->maxlen,
280                           pininfo->padlen);
281   return iso7816_map_sw (sw);
282 }
283 
284 
285 /* Perform a VERIFY command on SLOT using the card holder verification
286    vector CHVNO with a CHV of lenght CHVLEN.  With PININFO non-NULL
287    the keypad of the reader will be used.  Returns 0 on success. */
288 gpg_error_t
iso7816_verify_kp(int slot,int chvno,const char * chv,size_t chvlen,iso7816_pininfo_t * pininfo)289 iso7816_verify_kp (int slot, int chvno, const char *chv, size_t chvlen,
290                    iso7816_pininfo_t *pininfo)
291 {
292   int sw;
293 
294   if (pininfo && pininfo->mode)
295     sw = apdu_send_simple_kp (slot, 0x00, CMD_VERIFY, 0, chvno, chvlen, chv,
296                               pininfo->mode,
297                               pininfo->minlen,
298                               pininfo->maxlen,
299                               pininfo->padlen);
300   else
301     sw = apdu_send_simple (slot, 0, 0x00, CMD_VERIFY, 0, chvno, chvlen, chv);
302   return map_sw (sw);
303 }
304 
305 /* Perform a VERIFY command on SLOT using the card holder verification
306    vector CHVNO with a CHV of lenght CHVLEN.  Returns 0 on success. */
307 gpg_error_t
iso7816_verify(int slot,int chvno,const char * chv,size_t chvlen)308 iso7816_verify (int slot, int chvno, const char *chv, size_t chvlen)
309 {
310   return iso7816_verify_kp (slot, chvno, chv, chvlen, NULL);
311 }
312 
313 /* Perform a CHANGE_REFERENCE_DATA command on SLOT for the card holder
314    verification vector CHVNO.  If the OLDCHV is NULL (and OLDCHVLEN
315    0), a "change reference data" is done, otherwise an "exchange
316    reference data".  The new reference data is expected in NEWCHV of
317    length NEWCHVLEN.  With PININFO non-NULL the keypad of the reader
318    will be used.  */
319 gpg_error_t
iso7816_change_reference_data_kp(int slot,int chvno,const char * oldchv,size_t oldchvlen,const char * newchv,size_t newchvlen,iso7816_pininfo_t * pininfo)320 iso7816_change_reference_data_kp (int slot, int chvno,
321                                   const char *oldchv, size_t oldchvlen,
322                                   const char *newchv, size_t newchvlen,
323                                   iso7816_pininfo_t *pininfo)
324 {
325   int sw;
326   char *buf;
327 
328   if ((!oldchv && oldchvlen)
329       || (oldchv && !oldchvlen)
330       || !newchv || !newchvlen )
331     return gpg_error (GPG_ERR_INV_VALUE);
332 
333   buf = xtrymalloc (oldchvlen + newchvlen);
334   if (!buf)
335     return gpg_error (gpg_err_code_from_errno (errno));
336   if (oldchvlen)
337     memcpy (buf, oldchv, oldchvlen);
338   memcpy (buf+oldchvlen, newchv, newchvlen);
339 
340   if (pininfo && pininfo->mode)
341     sw = apdu_send_simple_kp (slot, 0x00, CMD_CHANGE_REFERENCE_DATA,
342                            oldchvlen? 0 : 1, chvno, oldchvlen+newchvlen, buf,
343                            pininfo->mode,
344                            pininfo->minlen,
345                            pininfo->maxlen,
346                            pininfo->padlen);
347   else
348     sw = apdu_send_simple (slot, 0, 0x00, CMD_CHANGE_REFERENCE_DATA,
349                            oldchvlen? 0 : 1, chvno, oldchvlen+newchvlen, buf);
350   xfree (buf);
351   return map_sw (sw);
352 
353 }
354 
355 /* Perform a CHANGE_REFERENCE_DATA command on SLOT for the card holder
356    verification vector CHVNO.  If the OLDCHV is NULL (and OLDCHVLEN
357    0), a "change reference data" is done, otherwise an "exchange
358    reference data".  The new reference data is expected in NEWCHV of
359    length NEWCHVLEN.  */
360 gpg_error_t
iso7816_change_reference_data(int slot,int chvno,const char * oldchv,size_t oldchvlen,const char * newchv,size_t newchvlen)361 iso7816_change_reference_data (int slot, int chvno,
362                                const char *oldchv, size_t oldchvlen,
363                                const char *newchv, size_t newchvlen)
364 {
365   return iso7816_change_reference_data_kp (slot, chvno, oldchv, oldchvlen,
366                                            newchv, newchvlen, NULL);
367 }
368 
369 
370 gpg_error_t
iso7816_reset_retry_counter_kp(int slot,int chvno,const char * newchv,size_t newchvlen,iso7816_pininfo_t * pininfo)371 iso7816_reset_retry_counter_kp (int slot, int chvno,
372                                 const char *newchv, size_t newchvlen,
373                                 iso7816_pininfo_t *pininfo)
374 {
375   int sw;
376 
377   if (!newchv || !newchvlen )
378     return gpg_error (GPG_ERR_INV_VALUE);
379 
380   /* FIXME:  The keypad mode has not yet been tested.  */
381   if (pininfo && pininfo->mode)
382     sw = apdu_send_simple_kp (slot, 0x00, CMD_RESET_RETRY_COUNTER,
383                            2, chvno, newchvlen, newchv,
384                            pininfo->mode,
385                            pininfo->minlen,
386                            pininfo->maxlen,
387                            pininfo->padlen);
388   else
389     sw = apdu_send_simple (slot, 0, 0x00, CMD_RESET_RETRY_COUNTER,
390                            2, chvno, newchvlen, newchv);
391   return map_sw (sw);
392 }
393 
394 
395 gpg_error_t
iso7816_reset_retry_counter_with_rc(int slot,int chvno,const char * data,size_t datalen)396 iso7816_reset_retry_counter_with_rc (int slot, int chvno,
397                                      const char *data, size_t datalen)
398 {
399   int sw;
400 
401   if (!data || !datalen )
402     return gpg_error (GPG_ERR_INV_VALUE);
403 
404   sw = apdu_send_simple (slot, 0, 0x00, CMD_RESET_RETRY_COUNTER,
405                          0, chvno, datalen, data);
406   return map_sw (sw);
407 }
408 
409 
410 gpg_error_t
iso7816_reset_retry_counter(int slot,int chvno,const char * newchv,size_t newchvlen)411 iso7816_reset_retry_counter (int slot, int chvno,
412                              const char *newchv, size_t newchvlen)
413 {
414   return iso7816_reset_retry_counter_kp (slot, chvno, newchv, newchvlen, NULL);
415 }
416 
417 
418 
419 /* Perform a GET DATA command requesting TAG and storing the result in
420    a newly allocated buffer at the address passed by RESULT.  Return
421    the length of this data at the address of RESULTLEN. */
422 gpg_error_t
iso7816_get_data(int slot,int extended_mode,int tag,unsigned char ** result,size_t * resultlen)423 iso7816_get_data (int slot, int extended_mode, int tag,
424                   unsigned char **result, size_t *resultlen)
425 {
426   int sw;
427   int le;
428 
429   if (!result || !resultlen)
430     return gpg_error (GPG_ERR_INV_VALUE);
431   *result = NULL;
432   *resultlen = 0;
433 
434   if (extended_mode > 0 && extended_mode < 256)
435     le = 65534; /* Not 65535 in case it is used as some special flag.  */
436   else if (extended_mode > 0)
437     le = extended_mode;
438   else
439     le = 256;
440 
441   sw = apdu_send_le (slot, extended_mode, 0x00, CMD_GET_DATA,
442                      ((tag >> 8) & 0xff), (tag & 0xff), -1, NULL, le,
443                      result, resultlen);
444   if (sw != SW_SUCCESS)
445     {
446       /* Make sure that pending buffers are released. */
447       xfree (*result);
448       *result = NULL;
449       *resultlen = 0;
450       return map_sw (sw);
451     }
452 
453   return 0;
454 }
455 
456 
457 /* Perform a PUT DATA command on card in SLOT.  Write DATA of length
458    DATALEN to TAG.  EXTENDED_MODE controls whether extended length
459    headers or command chaining is used instead of single length
460    bytes. */
461 gpg_error_t
iso7816_put_data(int slot,int extended_mode,int tag,const unsigned char * data,size_t datalen)462 iso7816_put_data (int slot, int extended_mode, int tag,
463                   const unsigned char *data, size_t datalen)
464 {
465   int sw;
466 
467   sw = apdu_send_simple (slot, extended_mode, 0x00, CMD_PUT_DATA,
468                          ((tag >> 8) & 0xff), (tag & 0xff),
469                          datalen, (const char*)data);
470   return map_sw (sw);
471 }
472 
473 /* Same as iso7816_put_data but uses an odd instruction byte.  */
474 gpg_error_t
iso7816_put_data_odd(int slot,int extended_mode,int tag,const unsigned char * data,size_t datalen)475 iso7816_put_data_odd (int slot, int extended_mode, int tag,
476                       const unsigned char *data, size_t datalen)
477 {
478   int sw;
479 
480   sw = apdu_send_simple (slot, extended_mode, 0x00, CMD_PUT_DATA+1,
481                          ((tag >> 8) & 0xff), (tag & 0xff),
482                          datalen, (const char*)data);
483   return map_sw (sw);
484 }
485 
486 /* Manage Security Environment.  This is a weird operation and there
487    is no easy abstraction for it.  Furthermore, some card seem to have
488    a different interpreation of 7816-8 and thus we resort to let the
489    caller decide what to do. */
490 gpg_error_t
iso7816_manage_security_env(int slot,int p1,int p2,const unsigned char * data,size_t datalen)491 iso7816_manage_security_env (int slot, int p1, int p2,
492                              const unsigned char *data, size_t datalen)
493 {
494   int sw;
495 
496   if (p1 < 0 || p1 > 255 || p2 < 0 || p2 > 255 )
497     return gpg_error (GPG_ERR_INV_VALUE);
498 
499   sw = apdu_send_simple (slot, 0, 0x00, CMD_MSE, p1, p2,
500                          data? datalen : -1, (const char*)data);
501   return map_sw (sw);
502 }
503 
504 
505 /* Perform the security operation COMPUTE DIGITAL SIGANTURE.  On
506    success 0 is returned and the data is availavle in a newly
507    allocated buffer stored at RESULT with its length stored at
508    RESULTLEN.  For LE see do_generate_keypair. */
509 gpg_error_t
iso7816_compute_ds(int slot,int extended_mode,const unsigned char * data,size_t datalen,int le,unsigned char ** result,size_t * resultlen)510 iso7816_compute_ds (int slot, int extended_mode,
511                     const unsigned char *data, size_t datalen, int le,
512                     unsigned char **result, size_t *resultlen)
513 {
514   int sw;
515 
516   if (!data || !datalen || !result || !resultlen)
517     return gpg_error (GPG_ERR_INV_VALUE);
518   *result = NULL;
519   *resultlen = 0;
520 
521   if (!extended_mode)
522     le = 256;  /* Ignore provided Le and use what apdu_send uses. */
523   else if (le >= 0 && le < 256)
524     le = 256;
525 
526   sw = apdu_send_le (slot, extended_mode,
527                      0x00, CMD_PSO, 0x9E, 0x9A,
528                      datalen, (const char*)data,
529                      le,
530                      result, resultlen);
531   if (sw != SW_SUCCESS)
532     {
533       /* Make sure that pending buffers are released. */
534       xfree (*result);
535       *result = NULL;
536       *resultlen = 0;
537       return map_sw (sw);
538     }
539 
540   return 0;
541 }
542 
543 
544 /* Perform the security operation DECIPHER.  PADIND is the padding
545    indicator to be used.  It should be 0 if no padding is required, a
546    value of -1 suppresses the padding byte.  On success 0 is returned
547    and the plaintext is available in a newly allocated buffer stored
548    at RESULT with its length stored at RESULTLEN.  For LE see
549    do_generate_keypair. */
550 gpg_error_t
iso7816_decipher(int slot,int extended_mode,const unsigned char * data,size_t datalen,int le,int padind,unsigned char ** result,size_t * resultlen)551 iso7816_decipher (int slot, int extended_mode,
552                   const unsigned char *data, size_t datalen, int le,
553                   int padind, unsigned char **result, size_t *resultlen)
554 {
555   int sw;
556   unsigned char *buf;
557 
558   if (!data || !datalen || !result || !resultlen)
559     return gpg_error (GPG_ERR_INV_VALUE);
560   *result = NULL;
561   *resultlen = 0;
562 
563   if (!extended_mode)
564     le = 256;  /* Ignore provided Le and use what apdu_send uses. */
565   else if (le >= 0 && le < 256)
566     le = 256;
567 
568   if (padind >= 0)
569     {
570       /* We need to prepend the padding indicator. */
571       buf = xtrymalloc (datalen + 1);
572       if (!buf)
573         return gpg_error (gpg_err_code_from_errno (errno));
574 
575       *buf = padind; /* Padding indicator. */
576       memcpy (buf+1, data, datalen);
577       sw = apdu_send_le (slot, extended_mode,
578                          0x00, CMD_PSO, 0x80, 0x86,
579                          datalen+1, (char*)buf, le,
580                          result, resultlen);
581       xfree (buf);
582     }
583   else
584     {
585       sw = apdu_send_le (slot, extended_mode,
586                          0x00, CMD_PSO, 0x80, 0x86,
587                          datalen, (const char *)data, le,
588                          result, resultlen);
589     }
590   if (sw != SW_SUCCESS)
591     {
592       /* Make sure that pending buffers are released. */
593       xfree (*result);
594       *result = NULL;
595       *resultlen = 0;
596       return map_sw (sw);
597     }
598 
599   return 0;
600 }
601 
602 
603 /*  For LE see do_generate_keypair.  */
604 gpg_error_t
iso7816_internal_authenticate(int slot,int extended_mode,const unsigned char * data,size_t datalen,int le,unsigned char ** result,size_t * resultlen)605 iso7816_internal_authenticate (int slot, int extended_mode,
606                                const unsigned char *data, size_t datalen,
607                                int le,
608                                unsigned char **result, size_t *resultlen)
609 {
610   int sw;
611 
612   if (!data || !datalen || !result || !resultlen)
613     return gpg_error (GPG_ERR_INV_VALUE);
614   *result = NULL;
615   *resultlen = 0;
616 
617   if (!extended_mode)
618     le = 256;  /* Ignore provided Le and use what apdu_send uses. */
619   else if (le >= 0 && le < 256)
620     le = 256;
621 
622   sw = apdu_send_le (slot, extended_mode,
623                      0x00, CMD_INTERNAL_AUTHENTICATE, 0, 0,
624                      datalen, (const char*)data,
625                      le,
626                      result, resultlen);
627   if (sw != SW_SUCCESS)
628     {
629       /* Make sure that pending buffers are released. */
630       xfree (*result);
631       *result = NULL;
632       *resultlen = 0;
633       return map_sw (sw);
634     }
635 
636   return 0;
637 }
638 
639 
640 /* LE is the expected return length.  This is usually 0 except if
641    extended length mode is used and more than 256 byte will be
642    returned.  In that case a value of -1 uses a large default
643    (e.g. 4096 bytes), a value larger 256 used that value.  */
644 static gpg_error_t
do_generate_keypair(int slot,int extended_mode,int read_only,const unsigned char * data,size_t datalen,int le,unsigned char ** result,size_t * resultlen)645 do_generate_keypair (int slot, int extended_mode, int read_only,
646                      const unsigned char *data, size_t datalen,
647                      int le,
648                      unsigned char **result, size_t *resultlen)
649 {
650   int sw;
651 
652   if (!data || !datalen || !result || !resultlen)
653     return gpg_error (GPG_ERR_INV_VALUE);
654   *result = NULL;
655   *resultlen = 0;
656 
657   sw = apdu_send_le (slot, extended_mode,
658                      0x00, CMD_GENERATE_KEYPAIR, read_only? 0x81:0x80, 0,
659                      datalen, (const char*)data,
660                      le >= 0 && le < 256? 256:le,
661                      result, resultlen);
662   if (sw != SW_SUCCESS)
663     {
664       /* Make sure that pending buffers are released. */
665       xfree (*result);
666       *result = NULL;
667       *resultlen = 0;
668       return map_sw (sw);
669     }
670 
671   return 0;
672 }
673 
674 
675 gpg_error_t
iso7816_generate_keypair(int slot,int extended_mode,const unsigned char * data,size_t datalen,int le,unsigned char ** result,size_t * resultlen)676 iso7816_generate_keypair (int slot, int extended_mode,
677                           const unsigned char *data, size_t datalen,
678                           int le,
679                           unsigned char **result, size_t *resultlen)
680 {
681   return do_generate_keypair (slot, extended_mode, 0,
682                               data, datalen, le, result, resultlen);
683 }
684 
685 
686 gpg_error_t
iso7816_read_public_key(int slot,int extended_mode,const unsigned char * data,size_t datalen,int le,unsigned char ** result,size_t * resultlen)687 iso7816_read_public_key (int slot, int extended_mode,
688                          const unsigned char *data, size_t datalen,
689                          int le,
690                          unsigned char **result, size_t *resultlen)
691 {
692   return do_generate_keypair (slot, extended_mode, 1,
693                               data, datalen, le, result, resultlen);
694 }
695 
696 
697 
698 gpg_error_t
iso7816_get_challenge(int slot,int length,unsigned char * buffer)699 iso7816_get_challenge (int slot, int length, unsigned char *buffer)
700 {
701   int sw;
702   unsigned char *result;
703   size_t resultlen, n;
704 
705   if (!buffer || length < 1)
706     return gpg_error (GPG_ERR_INV_VALUE);
707 
708   do
709     {
710       result = NULL;
711       n = length > 254? 254 : length;
712       sw = apdu_send_le (slot, 0,
713                          0x00, CMD_GET_CHALLENGE, 0, 0, -1, NULL, n,
714                          &result, &resultlen);
715       if (sw != SW_SUCCESS)
716         {
717           /* Make sure that pending buffers are released. */
718           xfree (result);
719           return map_sw (sw);
720         }
721       if (resultlen > n)
722         resultlen = n;
723       memcpy (buffer, result, resultlen);
724       buffer += resultlen;
725       length -= resultlen;
726       xfree (result);
727     }
728   while (length > 0);
729 
730   return 0;
731 }
732 
733 /* Perform a READ BINARY command requesting a maximum of NMAX bytes
734    from OFFSET.  With NMAX = 0 the entire file is read. The result is
735    stored in a newly allocated buffer at the address passed by RESULT.
736    Returns the length of this data at the address of RESULTLEN. */
737 gpg_error_t
iso7816_read_binary(int slot,size_t offset,size_t nmax,unsigned char ** result,size_t * resultlen)738 iso7816_read_binary (int slot, size_t offset, size_t nmax,
739                      unsigned char **result, size_t *resultlen)
740 {
741   int sw;
742   unsigned char *buffer;
743   size_t bufferlen;
744   int read_all = !nmax;
745   size_t n;
746 
747   if (!result || !resultlen)
748     return gpg_error (GPG_ERR_INV_VALUE);
749   *result = NULL;
750   *resultlen = 0;
751 
752   /* We can only encode 15 bits in p0,p1 to indicate an offset. Thus
753      we check for this limit. */
754   if (offset > 32767)
755     return gpg_error (GPG_ERR_INV_VALUE);
756 
757   do
758     {
759       buffer = NULL;
760       bufferlen = 0;
761       n = read_all? 0 : nmax;
762       sw = apdu_send_le (slot, 0, 0x00, CMD_READ_BINARY,
763                          ((offset>>8) & 0xff), (offset & 0xff) , -1, NULL,
764                          n, &buffer, &bufferlen);
765       if ( SW_EXACT_LENGTH_P(sw) )
766         {
767           n = (sw & 0x00ff);
768           sw = apdu_send_le (slot, 0, 0x00, CMD_READ_BINARY,
769                              ((offset>>8) & 0xff), (offset & 0xff) , -1, NULL,
770                              n, &buffer, &bufferlen);
771         }
772 
773       if (*result && sw == SW_BAD_P0_P1)
774         {
775           /* Bad Parameter means that the offset is outside of the
776              EF. When reading all data we take this as an indication
777              for EOF.  */
778           break;
779         }
780 
781       if (sw != SW_SUCCESS && sw != SW_EOF_REACHED)
782         {
783           /* Make sure that pending buffers are released. */
784           xfree (buffer);
785           xfree (*result);
786           *result = NULL;
787           *resultlen = 0;
788           return map_sw (sw);
789         }
790       if (*result) /* Need to extend the buffer. */
791         {
792           unsigned char *p = xtryrealloc (*result, *resultlen + bufferlen);
793           if (!p)
794             {
795               gpg_error_t err = gpg_error_from_syserror ();
796               xfree (buffer);
797               xfree (*result);
798               *result = NULL;
799               *resultlen = 0;
800               return err;
801             }
802           *result = p;
803           memcpy (*result + *resultlen, buffer, bufferlen);
804           *resultlen += bufferlen;
805           xfree (buffer);
806           buffer = NULL;
807         }
808       else /* Transfer the buffer into our result. */
809         {
810           *result = buffer;
811           *resultlen = bufferlen;
812         }
813       offset += bufferlen;
814       if (offset > 32767)
815         break; /* We simply truncate the result for too large
816                   files. */
817       if (nmax > bufferlen)
818         nmax -= bufferlen;
819       else
820         nmax = 0;
821     }
822   while ((read_all && sw != SW_EOF_REACHED) || (!read_all && nmax));
823 
824   return 0;
825 }
826 
827 /* Perform a READ RECORD command. RECNO gives the record number to
828    read with 0 indicating the current record.  RECCOUNT must be 1 (not
829    all cards support reading of more than one record).  SHORT_EF
830    should be 0 to read the current EF or contain a short EF. The
831    result is stored in a newly allocated buffer at the address passed
832    by RESULT.  Returns the length of this data at the address of
833    RESULTLEN. */
834 gpg_error_t
iso7816_read_record(int slot,int recno,int reccount,int short_ef,unsigned char ** result,size_t * resultlen)835 iso7816_read_record (int slot, int recno, int reccount, int short_ef,
836                      unsigned char **result, size_t *resultlen)
837 {
838   int sw;
839   unsigned char *buffer;
840   size_t bufferlen;
841 
842   if (!result || !resultlen)
843     return gpg_error (GPG_ERR_INV_VALUE);
844   *result = NULL;
845   *resultlen = 0;
846 
847   /* We can only encode 15 bits in p0,p1 to indicate an offset. Thus
848      we check for this limit. */
849   if (recno < 0 || recno > 255 || reccount != 1
850       || short_ef < 0 || short_ef > 254 )
851     return gpg_error (GPG_ERR_INV_VALUE);
852 
853   buffer = NULL;
854   bufferlen = 0;
855   sw = apdu_send_le (slot, 0, 0x00, CMD_READ_RECORD,
856                      recno,
857                      short_ef? short_ef : 0x04,
858                      -1, NULL,
859                      0, &buffer, &bufferlen);
860 
861   if (sw != SW_SUCCESS && sw != SW_EOF_REACHED)
862     {
863       /* Make sure that pending buffers are released. */
864       xfree (buffer);
865       xfree (*result);
866       *result = NULL;
867       *resultlen = 0;
868       return map_sw (sw);
869     }
870   *result = buffer;
871   *resultlen = bufferlen;
872 
873   return 0;
874 }
875 
876