1 /* app-openpgp.c - The OpenPGP card application.
2  * Copyright (C) 2003, 2004, 2005, 2007, 2008,
3  *               2009 Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <http://www.gnu.org/licenses/>.
19  *
20  * $Id$
21  */
22 
23 /* Some notes:
24 
25    CHV means Card Holder Verification and is nothing else than a PIN
26    or password.  That term seems to have been used originally with GSM
27    cards.  Version v2 of the specs changes the term to the clearer
28    term PW for password.  We use the terms here interchangeable
29    because we do not want to change existing strings i18n wise.
30 
31    Version 2 of the specs also drops the separate PW2 which was
32    required in v1 due to ISO requirements.  It is now possible to have
33    one physical PW but two reference to it so that they can be
34    individually be verified (e.g. to implement a forced verification
35    for one key).  Thus you will noticed the use of PW2 with the verify
36    command but not with change_reference_data because the latter
37    operates directly on the physical PW.
38 
39    The Reset Code (RC) as implemented by v2 cards uses the same error
40    counter as the PW2 of v1 cards.  By default no RC is set and thus
41    that error counter is set to 0.  After setting the RC the error
42    counter will be initialized to 3.
43 
44  */
45 
46 #include <config.h>
47 #include <errno.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <assert.h>
52 #include <time.h>
53 
54 #if GNUPG_MAJOR_VERSION == 1
55 /* This is used with GnuPG version < 1.9.  The code has been source
56    copied from the current GnuPG >= 1.9  and is maintained over
57    there. */
58 #include "options.h"
59 #include "errors.h"
60 #include "memory.h"
61 #include "util.h"
62 #include "cardglue.h"
63 #else /* GNUPG_MAJOR_VERSION != 1 */
64 #include "scdaemon.h"
65 #endif /* GNUPG_MAJOR_VERSION != 1 */
66 
67 #include "i18n.h"
68 #include "iso7816.h"
69 #include "app-common.h"
70 #include "tlv.h"
71 #include "../include/host2net.h"
72 
73 
74 /* A table describing the DOs of the card.  */
75 static struct {
76   int tag;
77   int constructed;
78   int get_from;  /* Constructed DO with this DO or 0 for direct access. */
79   int binary:1;
80   int dont_cache:1;
81   int flush_on_error:1;
82   int get_immediate_in_v11:1; /* Enable a hack to bypass the cache of
83                                  this data object if it is used in 1.1
84                                  and later versions of the card.  This
85                                  does not work with composite DO and
86                                  is currently only useful for the CHV
87                                  status bytes. */
88   int try_extlen:1;           /* Large object; try to use an extended
89                                  length APDU.  */
90   char *desc;
91 } data_objects[] = {
92   { 0x005E, 0,    0, 1, 0, 0, 0, 0, "Login Data" },
93   { 0x5F50, 0,    0, 0, 0, 0, 0, 0, "URL" },
94   { 0x5F52, 0,    0, 1, 0, 0, 0, 0, "Historical Bytes" },
95   { 0x0065, 1,    0, 1, 0, 0, 0, 0, "Cardholder Related Data"},
96   { 0x005B, 0, 0x65, 0, 0, 0, 0, 0, "Name" },
97   { 0x5F2D, 0, 0x65, 0, 0, 0, 0, 0, "Language preferences" },
98   { 0x5F35, 0, 0x65, 0, 0, 0, 0, 0, "Sex" },
99   { 0x006E, 1,    0, 1, 0, 0, 0, 0, "Application Related Data" },
100   { 0x004F, 0, 0x6E, 1, 0, 0, 0, 0, "AID" },
101   { 0x0073, 1,    0, 1, 0, 0, 0, 0, "Discretionary Data Objects" },
102   { 0x0047, 0, 0x6E, 1, 1, 0, 0, 0, "Card Capabilities" },
103   { 0x00C0, 0, 0x6E, 1, 1, 0, 0, 0, "Extended Card Capabilities" },
104   { 0x00C1, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Signature" },
105   { 0x00C2, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Decryption" },
106   { 0x00C3, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Authentication" },
107   { 0x00C4, 0, 0x6E, 1, 0, 1, 1, 0, "CHV Status Bytes" },
108   { 0x00C5, 0, 0x6E, 1, 0, 0, 0, 0, "Fingerprints" },
109   { 0x00C6, 0, 0x6E, 1, 0, 0, 0, 0, "CA Fingerprints" },
110   { 0x00CD, 0, 0x6E, 1, 0, 0, 0, 0, "Generation time" },
111   { 0x007A, 1,    0, 1, 0, 0, 0, 0, "Security Support Template" },
112   { 0x0093, 0, 0x7A, 1, 1, 0, 0, 0, "Digital Signature Counter" },
113   { 0x0101, 0,    0, 0, 0, 0, 0, 0, "Private DO 1"},
114   { 0x0102, 0,    0, 0, 0, 0, 0, 0, "Private DO 2"},
115   { 0x0103, 0,    0, 0, 0, 0, 0, 0, "Private DO 3"},
116   { 0x0104, 0,    0, 0, 0, 0, 0, 0, "Private DO 4"},
117   { 0x7F21, 1,    0, 1, 0, 0, 0, 1, "Cardholder certificate"},
118   { 0 }
119 };
120 
121 
122 /* The format of RSA private keys.  */
123 typedef enum
124   {
125     RSA_UNKNOWN_FMT,
126     RSA_STD,
127     RSA_STD_N,
128     RSA_CRT,
129     RSA_CRT_N
130   }
131 rsa_key_format_t;
132 
133 
134 /* One cache item for DOs.  */
135 struct cache_s {
136   struct cache_s *next;
137   int tag;
138   size_t length;
139   unsigned char data[1];
140 };
141 
142 
143 /* Object with application (i.e. OpenPGP card) specific data.  */
144 struct app_local_s {
145   /* A linked list with cached DOs.  */
146   struct cache_s *cache;
147 
148   /* Keep track of the public keys.  */
149   struct
150   {
151     int read_done;   /* True if we have at least tried to read them.  */
152     unsigned char *key; /* This is a malloced buffer with a canonical
153                            encoded S-expression encoding a public
154                            key. Might be NULL if key is not
155                            available.  */
156     size_t keylen;      /* The length of the above S-expression.  This
157                            is usually only required for cross checks
158                            because the length of an S-expression is
159                            implicitly available.  */
160   } pk[3];
161 
162   unsigned char status_indicator; /* The card status indicator.  */
163 
164   /* Keep track of the ISO card capabilities.  */
165   struct
166   {
167     unsigned int cmd_chaining:1;  /* Command chaining is supported.  */
168     unsigned int ext_lc_le:1;     /* Extended Lc and Le are supported.  */
169   } cardcap;
170 
171   /* Keep track of extended card capabilities.  */
172   struct
173   {
174     unsigned int is_v2:1;              /* This is a v2.0 compatible card.  */
175     unsigned int get_challenge:1;
176     unsigned int key_import:1;
177     unsigned int change_force_chv:1;
178     unsigned int private_dos:1;
179     unsigned int algo_attr_change:1;   /* Algorithm attributes changeable.  */
180     unsigned int sm_supported:1;       /* Secure Messaging is supported.  */
181     unsigned int sm_aes128:1;          /* Use AES-128 for SM.  */
182     unsigned int max_certlen_3:16;
183     unsigned int max_get_challenge:16; /* Maximum size for get_challenge.  */
184     unsigned int max_cmd_data:16;      /* Maximum data size for a command.  */
185     unsigned int max_rsp_data:16;      /* Maximum size of a response.  */
186   } extcap;
187 
188   /* Flags used to control the application.  */
189   struct
190   {
191     unsigned int no_sync:1;   /* Do not sync CHV1 and CHV2 */
192     unsigned int def_chv2:1;  /* Use 123456 for CHV2.  */
193   } flags;
194 
195   struct
196   {
197     unsigned int n_bits;     /* Size of the modulus in bits.  The rest
198                                 of this strucuire is only valid if
199                                 this is not 0.  */
200     unsigned int e_bits;     /* Size of the public exponent in bits.  */
201     rsa_key_format_t format;
202   } keyattr[3];
203 
204 };
205 
206 
207 
208 /***** Local prototypes  *****/
209 static unsigned long convert_sig_counter_value (const unsigned char *value,
210                                                 size_t valuelen);
211 static unsigned long get_sig_counter (app_t app);
212 static gpg_error_t do_auth (app_t app, const char *keyidstr,
213                             gpg_error_t (*pincb)(void*, const char *, char **),
214                             void *pincb_arg,
215                             const void *indata, size_t indatalen,
216                             unsigned char **outdata, size_t *outdatalen);
217 static void parse_algorithm_attribute (app_t app, int keyno);
218 static gpg_error_t change_keyattr_from_string
219                            (app_t app,
220                             gpg_error_t (*pincb)(void*, const char *, char **),
221                             void *pincb_arg,
222                             const void *value, size_t valuelen);
223 
224 
225 
226 
227 
228 /* Deconstructor. */
229 static void
do_deinit(app_t app)230 do_deinit (app_t app)
231 {
232   if (app && app->app_local)
233     {
234       struct cache_s *c, *c2;
235       int i;
236 
237       for (c = app->app_local->cache; c; c = c2)
238         {
239           c2 = c->next;
240           xfree (c);
241         }
242 
243       for (i=0; i < DIM (app->app_local->pk); i++)
244         {
245           xfree (app->app_local->pk[i].key);
246           app->app_local->pk[i].read_done = 0;
247         }
248       xfree (app->app_local);
249       app->app_local = NULL;
250     }
251 }
252 
253 
254 /* Wrapper around iso7816_get_data which first tries to get the data
255    from the cache.  With GET_IMMEDIATE passed as true, the cache is
256    bypassed.  With TRY_EXTLEN extended lengths APDUs are use if
257    supported by the card.  */
258 static gpg_error_t
get_cached_data(app_t app,int tag,unsigned char ** result,size_t * resultlen,int get_immediate,int try_extlen)259 get_cached_data (app_t app, int tag,
260                  unsigned char **result, size_t *resultlen,
261                  int get_immediate, int try_extlen)
262 {
263   gpg_error_t err;
264   int i;
265   unsigned char *p;
266   size_t len;
267   struct cache_s *c;
268   int exmode;
269 
270   *result = NULL;
271   *resultlen = 0;
272 
273   if (!get_immediate)
274     {
275       for (c=app->app_local->cache; c; c = c->next)
276         if (c->tag == tag)
277           {
278             if(c->length)
279               {
280                 p = xtrymalloc (c->length);
281                 if (!p)
282                   return gpg_error (gpg_err_code_from_errno (errno));
283                 memcpy (p, c->data, c->length);
284                 *result = p;
285               }
286 
287             *resultlen = c->length;
288 
289             return 0;
290           }
291     }
292 
293   if (try_extlen && app->app_local->cardcap.ext_lc_le)
294     exmode = app->app_local->extcap.max_rsp_data;
295   else
296     exmode = 0;
297 
298   err = iso7816_get_data (app->slot, exmode, tag, &p, &len);
299   if (err)
300     return err;
301   *result = p;
302   *resultlen = len;
303 
304   /* Check whether we should cache this object. */
305   if (get_immediate)
306     return 0;
307 
308   for (i=0; data_objects[i].tag; i++)
309     if (data_objects[i].tag == tag)
310       {
311         if (data_objects[i].dont_cache)
312           return 0;
313         break;
314       }
315 
316   /* Okay, cache it. */
317   for (c=app->app_local->cache; c; c = c->next)
318     assert (c->tag != tag);
319 
320   c = xtrymalloc (sizeof *c + len);
321   if (c)
322     {
323       memcpy (c->data, p, len);
324       c->length = len;
325       c->tag = tag;
326       c->next = app->app_local->cache;
327       app->app_local->cache = c;
328     }
329 
330   return 0;
331 }
332 
333 /* Remove DO at TAG from the cache. */
334 static void
flush_cache_item(app_t app,int tag)335 flush_cache_item (app_t app, int tag)
336 {
337   struct cache_s *c, *cprev;
338   int i;
339 
340   if (!app->app_local)
341     return;
342 
343   for (c=app->app_local->cache, cprev=NULL; c ; cprev=c, c = c->next)
344     if (c->tag == tag)
345       {
346         if (cprev)
347           cprev->next = c->next;
348         else
349           app->app_local->cache = c->next;
350         xfree (c);
351 
352         for (c=app->app_local->cache; c ; c = c->next)
353           {
354             assert (c->tag != tag); /* Oops: duplicated entry. */
355           }
356         return;
357       }
358 
359   /* Try again if we have an outer tag. */
360   for (i=0; data_objects[i].tag; i++)
361     if (data_objects[i].tag == tag && data_objects[i].get_from
362         && data_objects[i].get_from != tag)
363       flush_cache_item (app, data_objects[i].get_from);
364 }
365 
366 /* Flush all entries from the cache which might be out of sync after
367    an error. */
368 static void
flush_cache_after_error(app_t app)369 flush_cache_after_error (app_t app)
370 {
371   int i;
372 
373   for (i=0; data_objects[i].tag; i++)
374     if (data_objects[i].flush_on_error)
375       flush_cache_item (app, data_objects[i].tag);
376 }
377 
378 
379 /* Flush the entire cache. */
380 static void
flush_cache(app_t app)381 flush_cache (app_t app)
382 {
383   if (app && app->app_local)
384     {
385       struct cache_s *c, *c2;
386 
387       for (c = app->app_local->cache; c; c = c2)
388         {
389           c2 = c->next;
390           xfree (c);
391         }
392       app->app_local->cache = NULL;
393     }
394 }
395 
396 
397 /* Get the DO identified by TAG from the card in SLOT and return a
398    buffer with its content in RESULT and NBYTES.  The return value is
399    NULL if not found or a pointer which must be used to release the
400    buffer holding value. */
401 static void *
get_one_do(app_t app,int tag,unsigned char ** result,size_t * nbytes,int * r_rc)402 get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes,
403             int *r_rc)
404 {
405   int rc, i;
406   unsigned char *buffer;
407   size_t buflen;
408   unsigned char *value;
409   size_t valuelen;
410   int dummyrc;
411   int exmode;
412 
413   if (!r_rc)
414     r_rc = &dummyrc;
415 
416   *result = NULL;
417   *nbytes = 0;
418   *r_rc = 0;
419   for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
420     ;
421 
422   if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11)
423     {
424       if (data_objects[i].try_extlen && app->app_local->cardcap.ext_lc_le)
425         exmode = app->app_local->extcap.max_rsp_data;
426       else
427         exmode = 0;
428       rc = iso7816_get_data (app->slot, exmode, tag, &buffer, &buflen);
429       if (rc)
430         {
431           *r_rc = rc;
432           return NULL;
433         }
434       *result = buffer;
435       *nbytes = buflen;
436       return buffer;
437     }
438 
439   value = NULL;
440   rc = -1;
441   if (data_objects[i].tag && data_objects[i].get_from)
442     {
443       rc = get_cached_data (app, data_objects[i].get_from,
444                             &buffer, &buflen,
445                             (data_objects[i].dont_cache
446                              || data_objects[i].get_immediate_in_v11),
447                             data_objects[i].try_extlen);
448       if (!rc)
449         {
450           const unsigned char *s;
451 
452           s = find_tlv_unchecked (buffer, buflen, tag, &valuelen);
453           if (!s)
454             value = NULL; /* not found */
455           else if (valuelen > buflen - (s - buffer))
456             {
457               log_error ("warning: constructed DO too short\n");
458               value = NULL;
459               xfree (buffer); buffer = NULL;
460             }
461           else
462             value = buffer + (s - buffer);
463         }
464     }
465 
466   if (!value) /* Not in a constructed DO, try simple. */
467     {
468       rc = get_cached_data (app, tag, &buffer, &buflen,
469                             (data_objects[i].dont_cache
470                              || data_objects[i].get_immediate_in_v11),
471                             data_objects[i].try_extlen);
472       if (!rc)
473         {
474           value = buffer;
475           valuelen = buflen;
476         }
477     }
478 
479   if (!rc)
480     {
481       *nbytes = valuelen;
482       *result = value;
483       return buffer;
484     }
485   *r_rc = rc;
486   return NULL;
487 }
488 
489 
490 static void
dump_all_do(int slot)491 dump_all_do (int slot)
492 {
493   int rc, i, j;
494   unsigned char *buffer;
495   size_t buflen;
496 
497   for (i=0; data_objects[i].tag; i++)
498     {
499       if (data_objects[i].get_from)
500         continue;
501 
502       /* We don't try extended length APDU because such large DO would
503          be pretty useless in a log file.  */
504       rc = iso7816_get_data (slot, 0, data_objects[i].tag, &buffer, &buflen);
505       if (gpg_err_code (rc) == GPG_ERR_NO_OBJ)
506         ;
507       else if (rc)
508         log_info ("DO `%s' not available: %s\n",
509                   data_objects[i].desc, gpg_strerror (rc));
510       else
511         {
512           if (data_objects[i].binary)
513             {
514               log_info ("DO `%s': ", data_objects[i].desc);
515               log_printhex ("", buffer, buflen);
516             }
517           else
518             log_info ("DO `%s': `%.*s'\n",
519                       data_objects[i].desc,
520                       (int)buflen, buffer); /* FIXME: sanitize */
521 
522           if (data_objects[i].constructed)
523             {
524               for (j=0; data_objects[j].tag; j++)
525                 {
526                   const unsigned char *value;
527                   size_t valuelen;
528 
529                   if (j==i || data_objects[i].tag != data_objects[j].get_from)
530                     continue;
531                   value = find_tlv_unchecked (buffer, buflen,
532                                               data_objects[j].tag, &valuelen);
533                   if (!value)
534                     ; /* not found */
535                   else if (valuelen > buflen - (value - buffer))
536                     log_error ("warning: constructed DO too short\n");
537                   else
538                     {
539                       if (data_objects[j].binary)
540                         {
541                           log_info ("DO `%s': ", data_objects[j].desc);
542                           if (valuelen > 200)
543                             log_info ("[%u]\n", (unsigned int)valuelen);
544                           else
545                             log_printhex ("", value, valuelen);
546                         }
547                       else
548                         log_info ("DO `%s': `%.*s'\n",
549                                   data_objects[j].desc,
550                                   (int)valuelen, value); /* FIXME: sanitize */
551                     }
552                 }
553             }
554         }
555       xfree (buffer); buffer = NULL;
556     }
557 }
558 
559 
560 /* Count the number of bits, assuming the A represents an unsigned big
561    integer of length LEN bytes. */
562 static unsigned int
count_bits(const unsigned char * a,size_t len)563 count_bits (const unsigned char *a, size_t len)
564 {
565   unsigned int n = len * 8;
566   int i;
567 
568   for (; len && !*a; len--, a++, n -=8)
569     ;
570   if (len)
571     {
572       for (i=7; i && !(*a & (1<<i)); i--)
573         n--;
574     }
575   return n;
576 }
577 
578 /* GnuPG makes special use of the login-data DO, this function parses
579    the login data to store the flags for later use.  It may be called
580    at any time and should be called after changing the login-data DO.
581 
582    Everything up to a LF is considered a mailbox or account name.  If
583    the first LF is followed by DC4 (0x14) control sequence are
584    expected up to the next LF.  Control sequences are separated by FS
585    (0x18) and consist of key=value pairs.  There is one key defined:
586 
587     F=<flags>
588 
589     Were FLAGS is a plain hexadecimal number representing flag values.
590     The lsb is here the rightmost bit.  Defined flags bits are:
591 
592       Bit 0 = CHV1 and CHV2 are not syncronized
593       Bit 1 = CHV2 has been been set to the default PIN of "123456"
594               (this implies that bit 0 is also set).
595 
596 */
597 static void
parse_login_data(app_t app)598 parse_login_data (app_t app)
599 {
600   unsigned char *buffer, *p;
601   size_t buflen, len;
602   void *relptr;
603 
604   /* Set defaults.  */
605   app->app_local->flags.no_sync = 0;
606   app->app_local->flags.def_chv2 = 0;
607 
608   /* Read the DO.  */
609   relptr = get_one_do (app, 0x005E, &buffer, &buflen, NULL);
610   if (!relptr)
611     return; /* Ooops. */
612   for (; buflen; buflen--, buffer++)
613     if (*buffer == '\n')
614       break;
615   if (buflen < 2 || buffer[1] != '\x14')
616     return; /* No control sequences.  */
617   buflen--;
618   buffer++;
619   do
620     {
621       buflen--;
622       buffer++;
623       if (buflen > 1 && *buffer == 'F' && buffer[1] == '=')
624         {
625           /* Flags control sequence found.  */
626           int lastdig = 0;
627 
628           /* For now we are only interested in the last digit, so skip
629              any leading digits but bail out on invalid characters. */
630           for (p=buffer+2, len = buflen-2; len && hexdigitp (p); p++, len--)
631             lastdig = xtoi_1 (p);
632           if (len && !(*p == '\n' || *p == '\x18'))
633             goto next;  /* Invalid characters in field.  */
634           app->app_local->flags.no_sync = !!(lastdig & 1);
635           app->app_local->flags.def_chv2 = (lastdig & 3) == 3;
636         }
637     next:
638       for (; buflen && *buffer != '\x18'; buflen--, buffer++)
639         if (*buffer == '\n')
640           buflen = 1;
641     }
642   while (buflen);
643 
644   xfree (relptr);
645 }
646 
647 /* Note, that FPR must be at least 20 bytes. */
648 static gpg_error_t
store_fpr(app_t app,int keynumber,u32 timestamp,const unsigned char * m,size_t mlen,const unsigned char * e,size_t elen,unsigned char * fpr,unsigned int card_version)649 store_fpr (app_t app, int keynumber, u32 timestamp,
650            const unsigned char *m, size_t mlen,
651            const unsigned char *e, size_t elen,
652            unsigned char *fpr, unsigned int card_version)
653 {
654   unsigned int n, nbits;
655   unsigned char *buffer, *p;
656   int tag, tag2;
657   int rc;
658 
659   for (; mlen && !*m; mlen--, m++) /* strip leading zeroes */
660     ;
661   for (; elen && !*e; elen--, e++) /* strip leading zeroes */
662     ;
663 
664   n = 6 + 2 + mlen + 2 + elen;
665   p = buffer = xtrymalloc (3 + n);
666   if (!buffer)
667     return gpg_error_from_syserror ();
668 
669   *p++ = 0x99;     /* ctb */
670   *p++ = n >> 8;   /* 2 byte length header */
671   *p++ = n;
672   *p++ = 4;        /* key packet version */
673   *p++ = timestamp >> 24;
674   *p++ = timestamp >> 16;
675   *p++ = timestamp >>  8;
676   *p++ = timestamp;
677   *p++ = 1; /* RSA */
678   nbits = count_bits (m, mlen);
679   *p++ = nbits >> 8;
680   *p++ = nbits;
681   memcpy (p, m, mlen); p += mlen;
682   nbits = count_bits (e, elen);
683   *p++ = nbits >> 8;
684   *p++ = nbits;
685   memcpy (p, e, elen); p += elen;
686 
687   gcry_md_hash_buffer (GCRY_MD_SHA1, fpr, buffer, n+3);
688 
689   xfree (buffer);
690 
691   tag = (card_version > 0x0007? 0xC7 : 0xC6) + keynumber;
692   flush_cache_item (app, 0xC5);
693   tag2 = 0xCE + keynumber;
694   flush_cache_item (app, 0xCD);
695 
696   rc = iso7816_put_data (app->slot, 0, tag, fpr, 20);
697   if (rc)
698     log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc));
699 
700   if (!rc && card_version > 0x0100)
701     {
702       unsigned char buf[4];
703 
704       buf[0] = timestamp >> 24;
705       buf[1] = timestamp >> 16;
706       buf[2] = timestamp >>  8;
707       buf[3] = timestamp;
708 
709       rc = iso7816_put_data (app->slot, 0, tag2, buf, 4);
710       if (rc)
711         log_error (_("failed to store the creation date: %s\n"),
712                    gpg_strerror (rc));
713     }
714 
715   return rc;
716 }
717 
718 
719 static void
send_fpr_if_not_null(ctrl_t ctrl,const char * keyword,int number,const unsigned char * fpr)720 send_fpr_if_not_null (ctrl_t ctrl, const char *keyword,
721                       int number, const unsigned char *fpr)
722 {
723   int i;
724   char buf[41];
725   char numbuf[25];
726 
727   for (i=0; i < 20 && !fpr[i]; i++)
728     ;
729   if (i==20)
730     return; /* All zero. */
731   bin2hex (fpr, 20, buf);
732   if (number == -1)
733     *numbuf = 0; /* Don't print the key number */
734   else
735     sprintf (numbuf, "%d", number);
736   send_status_info (ctrl, keyword,
737                     numbuf, (size_t)strlen(numbuf),
738                     buf, (size_t)strlen (buf), NULL, 0);
739 }
740 
741 static void
send_fprtime_if_not_null(ctrl_t ctrl,const char * keyword,int number,const unsigned char * stamp)742 send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,
743                           int number, const unsigned char *stamp)
744 {
745   char numbuf1[50], numbuf2[50];
746   unsigned long value;
747 
748   value = buf32_to_ulong (stamp);
749   if (!value)
750     return;
751   sprintf (numbuf1, "%d", number);
752   sprintf (numbuf2, "%lu", value);
753   send_status_info (ctrl, keyword,
754                     numbuf1, (size_t)strlen(numbuf1),
755                     numbuf2, (size_t)strlen(numbuf2), NULL, 0);
756 }
757 
758 static void
send_key_data(ctrl_t ctrl,const char * name,const unsigned char * a,size_t alen)759 send_key_data (ctrl_t ctrl, const char *name,
760                const unsigned char *a, size_t alen)
761 {
762   char *buf;
763 
764   buf = bin2hex (a, alen, NULL);
765   if (!buf)
766     {
767       log_error ("memory allocation error in send_key_data\n");
768       return;
769     }
770 
771   send_status_info (ctrl, "KEY-DATA",
772                     name, (size_t)strlen(name),
773                     buf, (size_t)strlen (buf),
774                     NULL, 0);
775   xfree (buf);
776 }
777 
778 
779 static void
send_key_attr(ctrl_t ctrl,app_t app,const char * keyword,int number)780 send_key_attr (ctrl_t ctrl, app_t app, const char *keyword, int number)
781 {
782   char buffer[200];
783 
784   assert (number >=0 && number < DIM(app->app_local->keyattr));
785 
786   /* We only support RSA thus the algo identifier is fixed to 1.  */
787   snprintf (buffer, sizeof buffer, "%d 1 %u %u %d",
788             number+1,
789             app->app_local->keyattr[number].n_bits,
790             app->app_local->keyattr[number].e_bits,
791             app->app_local->keyattr[number].format);
792   send_status_direct (ctrl, keyword, buffer);
793 }
794 
795 
796 /* Implement the GETATTR command.  This is similar to the LEARN
797    command but returns just one value via the status interface. */
798 static gpg_error_t
do_getattr(app_t app,ctrl_t ctrl,const char * name)799 do_getattr (app_t app, ctrl_t ctrl, const char *name)
800 {
801   static struct {
802     const char *name;
803     int tag;
804     int special;
805   } table[] = {
806     { "DISP-NAME",    0x005B },
807     { "LOGIN-DATA",   0x005E },
808     { "DISP-LANG",    0x5F2D },
809     { "DISP-SEX",     0x5F35 },
810     { "PUBKEY-URL",   0x5F50 },
811     { "KEY-FPR",      0x00C5, 3 },
812     { "KEY-TIME",     0x00CD, 4 },
813     { "KEY-ATTR",     0x0000, -5 },
814     { "CA-FPR",       0x00C6, 3 },
815     { "CHV-STATUS",   0x00C4, 1 },
816     { "SIG-COUNTER",  0x0093, 2 },
817     { "SERIALNO",     0x004F, -1 },
818     { "AID",          0x004F },
819     { "EXTCAP",       0x0000, -2 },
820     { "PRIVATE-DO-1", 0x0101 },
821     { "PRIVATE-DO-2", 0x0102 },
822     { "PRIVATE-DO-3", 0x0103 },
823     { "PRIVATE-DO-4", 0x0104 },
824     { "$AUTHKEYID",   0x0000, -3 },
825     { "$DISPSERIALNO",0x0000, -4 },
826     { NULL, 0 }
827   };
828   int idx, i, rc;
829   void *relptr;
830   unsigned char *value;
831   size_t valuelen;
832 
833   for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
834     ;
835   if (!table[idx].name)
836     return gpg_error (GPG_ERR_INV_NAME);
837 
838   if (table[idx].special == -1)
839     {
840       /* The serial number is very special.  We could have used the
841          AID DO to retrieve it, but we have it already in the app
842          context and the stamp argument is required anyway which we
843          can't by other means. The AID DO is available anyway but not
844          hex formatted. */
845       char *serial;
846       time_t stamp;
847       char tmp[50];
848 
849       if (!app_get_serial_and_stamp (app, &serial, &stamp))
850         {
851           sprintf (tmp, "%lu", (unsigned long)stamp);
852           send_status_info (ctrl, "SERIALNO",
853                             serial, strlen (serial),
854                             tmp, strlen (tmp),
855                             NULL, 0);
856           xfree (serial);
857         }
858       return 0;
859     }
860   if (table[idx].special == -2)
861     {
862       char tmp[100];
863 
864       snprintf (tmp, sizeof tmp,
865                 "gc=%d ki=%d fc=%d pd=%d mcl3=%u aac=%d sm=%d",
866                 app->app_local->extcap.get_challenge,
867                 app->app_local->extcap.key_import,
868                 app->app_local->extcap.change_force_chv,
869                 app->app_local->extcap.private_dos,
870                 app->app_local->extcap.max_certlen_3,
871                 app->app_local->extcap.algo_attr_change,
872                 (app->app_local->extcap.sm_supported
873                  ? (app->app_local->extcap.sm_aes128? 7 : 2)
874                  : 0));
875       send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
876       return 0;
877     }
878   if (table[idx].special == -3)
879     {
880       char const tmp[] = "OPENPGP.3";
881       send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
882       return 0;
883     }
884   if (table[idx].special == -4)
885     {
886       char *serial;
887       time_t stamp;
888 
889       if (!app_get_serial_and_stamp (app, &serial, &stamp))
890         {
891           if (strlen (serial) > 16+12)
892             {
893               send_status_info (ctrl, table[idx].name, serial+16, 12, NULL, 0);
894               xfree (serial);
895               return 0;
896             }
897           xfree (serial);
898         }
899       return gpg_error (GPG_ERR_INV_NAME);
900     }
901   if (table[idx].special == -5)
902     {
903       for (i=0; i < 3; i++)
904         send_key_attr (ctrl, app, table[idx].name, i);
905       return 0;
906     }
907 
908   relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc);
909   if (relptr)
910     {
911       if (table[idx].special == 1)
912         {
913           char numbuf[7*23];
914 
915           for (i=0,*numbuf=0; i < valuelen && i < 7; i++)
916             sprintf (numbuf+strlen (numbuf), " %d", value[i]);
917           send_status_info (ctrl, table[idx].name,
918                             numbuf, strlen (numbuf), NULL, 0);
919         }
920       else if (table[idx].special == 2)
921         {
922           char numbuf[50];
923 
924           sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen));
925           send_status_info (ctrl, table[idx].name,
926                             numbuf, strlen (numbuf), NULL, 0);
927         }
928       else if (table[idx].special == 3)
929         {
930           if (valuelen >= 60)
931             for (i=0; i < 3; i++)
932               send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
933         }
934       else if (table[idx].special == 4)
935         {
936           if (valuelen >= 12)
937             for (i=0; i < 3; i++)
938               send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
939         }
940       else
941         send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
942 
943       xfree (relptr);
944     }
945   return rc;
946 }
947 
948 /* Retrieve the fingerprint from the card inserted in SLOT and write
949    the according hex representation to FPR.  Caller must have provide
950    a buffer at FPR of least 41 bytes.  Returns 0 on success or an
951    error code. */
952 #if GNUPG_MAJOR_VERSION > 1
953 static gpg_error_t
retrieve_fpr_from_card(app_t app,int keyno,char * fpr)954 retrieve_fpr_from_card (app_t app, int keyno, char *fpr)
955 {
956   gpg_error_t err = 0;
957   void *relptr;
958   unsigned char *value;
959   size_t valuelen;
960 
961   assert (keyno >=0 && keyno <= 2);
962 
963   relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
964   if (relptr && valuelen >= 60)
965     bin2hex (value+keyno*20, 20, fpr);
966   else
967     err = gpg_error (GPG_ERR_NOT_FOUND);
968   xfree (relptr);
969   return err;
970 }
971 #endif /*GNUPG_MAJOR_VERSION > 1*/
972 
973 
974 /* Retrieve the public key material for the RSA key, whose fingerprint
975    is FPR, from gpg output, which can be read through the stream FP.
976    The RSA modulus will be stored at the address of M and MLEN, the
977    public exponent at E and ELEN.  Returns zero on success, an error
978    code on failure.  Caller must release the allocated buffers at M
979    and E if the function returns success.  */
980 #if GNUPG_MAJOR_VERSION > 1
981 static gpg_error_t
retrieve_key_material(FILE * fp,const char * hexkeyid,const unsigned char ** m,size_t * mlen,const unsigned char ** e,size_t * elen)982 retrieve_key_material (FILE *fp, const char *hexkeyid,
983 		       const unsigned char **m, size_t *mlen,
984 		       const unsigned char **e, size_t *elen)
985 {
986   gcry_error_t err = 0;
987   char *line = NULL;    /* read_line() buffer. */
988   size_t line_size = 0; /* Helper for for read_line. */
989   int found_key = 0;    /* Helper to find a matching key. */
990   unsigned char *m_new = NULL;
991   unsigned char *e_new = NULL;
992   size_t m_new_n = 0;
993   size_t e_new_n = 0;
994 
995   /* Loop over all records until we have found the subkey
996      corresponding to the fingerprint. Inm general the first record
997      should be the pub record, but we don't rely on that.  Given that
998      we only need to look at one key, it is sufficient to compare the
999      keyid so that we don't need to look at "fpr" records. */
1000   for (;;)
1001     {
1002       char *p;
1003       char *fields[6];
1004       int nfields;
1005       size_t max_length;
1006       gcry_mpi_t mpi;
1007       int i;
1008 
1009       max_length = 4096;
1010       i = read_line (fp, &line, &line_size, &max_length);
1011       if (!i)
1012         break; /* EOF. */
1013       if (i < 0)
1014 	{
1015 	  err = gpg_error_from_syserror ();
1016 	  goto leave; /* Error. */
1017 	}
1018       if (!max_length)
1019         {
1020           err = gpg_error (GPG_ERR_TRUNCATED);
1021           goto leave;  /* Line truncated - we better stop processing.  */
1022         }
1023 
1024       /* Parse the line into fields. */
1025       for (nfields=0, p=line; p && nfields < DIM (fields); nfields++)
1026         {
1027           fields[nfields] = p;
1028           p = strchr (p, ':');
1029           if (p)
1030             *(p++) = 0;
1031         }
1032       if (!nfields)
1033         continue; /* No fields at all - skip line.  */
1034 
1035       if (!found_key)
1036         {
1037           if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1038                && nfields > 4 && !strcmp (fields[4], hexkeyid))
1039             found_key = 1;
1040           continue;
1041       	}
1042 
1043       if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
1044         break; /* Next key - stop.  */
1045 
1046       if ( strcmp (fields[0], "pkd") )
1047         continue; /* Not a key data record.  */
1048       i = 0; /* Avoid erroneous compiler warning. */
1049       if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1
1050            || (!i && m_new) || (i && e_new))
1051         {
1052           err = gpg_error (GPG_ERR_GENERAL);
1053           goto leave; /* Error: Invalid key data record or not an RSA key.  */
1054         }
1055 
1056       err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL);
1057       if (err)
1058         mpi = NULL;
1059       else if (!i)
1060         err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi);
1061       else
1062         err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi);
1063       gcry_mpi_release (mpi);
1064       if (err)
1065         goto leave;
1066     }
1067 
1068   if (m_new && e_new)
1069     {
1070       *m = m_new;
1071       *mlen = m_new_n;
1072       m_new = NULL;
1073       *e = e_new;
1074       *elen = e_new_n;
1075       e_new = NULL;
1076     }
1077   else
1078     err = gpg_error (GPG_ERR_GENERAL);
1079 
1080  leave:
1081   xfree (m_new);
1082   xfree (e_new);
1083   xfree (line);
1084   return err;
1085 }
1086 #endif /*GNUPG_MAJOR_VERSION > 1*/
1087 
1088 
1089 /* Get the public key for KEYNO and store it as an S-expresion with
1090    the APP handle.  On error that field gets cleared.  If we already
1091    know about the public key we will just return.  Note that this does
1092    not mean a key is available; this is soley indicated by the
1093    presence of the app->app_local->pk[KEYNO-1].key field.
1094 
1095    Note that GnuPG 1.x does not need this and it would be too time
1096    consuming to send it just for the fun of it. However, given that we
1097    use the same code in gpg 1.4, we can't use the gcry S-expresion
1098    here but need to open encode it. */
1099 #if GNUPG_MAJOR_VERSION > 1
1100 static gpg_error_t
get_public_key(app_t app,int keyno)1101 get_public_key (app_t app, int keyno)
1102 {
1103   gpg_error_t err = 0;
1104   unsigned char *buffer;
1105   const unsigned char *keydata, *m, *e;
1106   size_t buflen, keydatalen, mlen, elen;
1107   unsigned char *mbuf = NULL;
1108   unsigned char *ebuf = NULL;
1109   char *keybuf = NULL;
1110   char *keybuf_p;
1111 
1112   if (keyno < 1 || keyno > 3)
1113     return gpg_error (GPG_ERR_INV_ID);
1114   keyno--;
1115 
1116   /* Already cached? */
1117   if (app->app_local->pk[keyno].read_done)
1118     return 0;
1119 
1120   xfree (app->app_local->pk[keyno].key);
1121   app->app_local->pk[keyno].key = NULL;
1122   app->app_local->pk[keyno].keylen = 0;
1123 
1124   m = e = NULL; /* (avoid cc warning) */
1125 
1126   if (app->card_version > 0x0100)
1127     {
1128       int exmode, le_value;
1129 
1130       /* We may simply read the public key out of these cards.  */
1131       if (app->app_local->cardcap.ext_lc_le)
1132         {
1133           exmode = 1;    /* Use extended length.  */
1134           le_value = app->app_local->extcap.max_rsp_data;
1135         }
1136       else
1137         {
1138           exmode = 0;
1139           le_value = 256; /* Use legacy value. */
1140         }
1141 
1142       err = iso7816_read_public_key
1143         (app->slot, exmode,
1144          (const unsigned char*)(keyno == 0? "\xB6" :
1145                                 keyno == 1? "\xB8" : "\xA4"), 2,
1146          le_value,
1147          &buffer, &buflen);
1148       if (err)
1149         {
1150           log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
1151           goto leave;
1152         }
1153 
1154       keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1155       if (!keydata)
1156         {
1157           err = gpg_error (GPG_ERR_CARD);
1158           log_error (_("response does not contain the public key data\n"));
1159           goto leave;
1160         }
1161 
1162       m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
1163       if (!m)
1164         {
1165           err = gpg_error (GPG_ERR_CARD);
1166           log_error (_("response does not contain the RSA modulus\n"));
1167           goto leave;
1168         }
1169 
1170 
1171       e = find_tlv (keydata, keydatalen, 0x0082, &elen);
1172       if (!e)
1173         {
1174           err = gpg_error (GPG_ERR_CARD);
1175           log_error (_("response does not contain the RSA public exponent\n"));
1176           goto leave;
1177         }
1178 
1179       /* Prepend numbers with a 0 if needed.  */
1180       if (mlen && (*m & 0x80))
1181         {
1182           mbuf = xtrymalloc ( mlen + 1);
1183           if (!mbuf)
1184             {
1185               err = gpg_error_from_syserror ();
1186               goto leave;
1187             }
1188           *mbuf = 0;
1189           memcpy (mbuf+1, m, mlen);
1190           mlen++;
1191           m = mbuf;
1192         }
1193       if (elen && (*e & 0x80))
1194         {
1195           ebuf = xtrymalloc ( elen + 1);
1196           if (!ebuf)
1197             {
1198               err = gpg_error_from_syserror ();
1199               goto leave;
1200             }
1201           *ebuf = 0;
1202           memcpy (ebuf+1, e, elen);
1203           elen++;
1204           e = ebuf;
1205         }
1206 
1207     }
1208   else
1209     {
1210       /* Due to a design problem in v1.0 cards we can't get the public
1211          key out of these cards without doing a verify on CHV3.
1212          Clearly that is not an option and thus we try to locate the
1213          key using an external helper.
1214 
1215 	 The helper we use here is gpg itself, which should know about
1216 	 the key in any case.  */
1217 
1218       char fpr[41];
1219       char *hexkeyid;
1220       char *command = NULL;
1221       FILE *fp;
1222       int ret;
1223 
1224       buffer = NULL; /* We don't need buffer.  */
1225 
1226       err = retrieve_fpr_from_card (app, keyno, fpr);
1227       if (err)
1228 	{
1229 	  log_error ("error while retrieving fpr from card: %s\n",
1230 		     gpg_strerror (err));
1231 	  goto leave;
1232 	}
1233       hexkeyid = fpr + 24;
1234 
1235       ret = estream_asprintf (&command,
1236 			      "gpg --list-keys --with-colons --with-key-data '%s'",
1237 			      fpr);
1238       if (ret < 0)
1239 	{
1240 	  err = gpg_error_from_syserror ();
1241 	  goto leave;
1242 	}
1243 
1244       fp = popen (command, "r");
1245       xfree (command);
1246       if (!fp)
1247 	{
1248 	  err = gpg_error_from_syserror ();
1249 	  log_error ("running gpg failed: %s\n", gpg_strerror (err));
1250 	  goto leave;
1251 	}
1252 
1253       err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
1254       pclose (fp);
1255       if (err)
1256 	{
1257 	  log_error ("error while retrieving key material through pipe: %s\n",
1258                      gpg_strerror (err));
1259 	  goto leave;
1260 	}
1261     }
1262 
1263   /* Allocate a buffer to construct the S-expression.  */
1264   /* FIXME: We should provide a generalized S-expression creation
1265      mechanism. */
1266   keybuf = xtrymalloc (50 + 2*35 + mlen + elen + 1);
1267   if (!keybuf)
1268     {
1269       err = gpg_error_from_syserror ();
1270       goto leave;
1271     }
1272 
1273   sprintf (keybuf, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen);
1274   keybuf_p = keybuf + strlen (keybuf);
1275   memcpy (keybuf_p, m, mlen);
1276   keybuf_p += mlen;
1277   sprintf (keybuf_p, ")(1:e%u:", (unsigned int)elen);
1278   keybuf_p += strlen (keybuf_p);
1279   memcpy (keybuf_p, e, elen);
1280   keybuf_p += elen;
1281   strcpy (keybuf_p, ")))");
1282   keybuf_p += strlen (keybuf_p);
1283 
1284   app->app_local->pk[keyno].key = (unsigned char*)keybuf;
1285   app->app_local->pk[keyno].keylen = (keybuf_p - keybuf);
1286 
1287  leave:
1288   /* Set a flag to indicate that we tried to read the key.  */
1289   app->app_local->pk[keyno].read_done = 1;
1290 
1291   xfree (buffer);
1292   xfree (mbuf);
1293   xfree (ebuf);
1294   return 0;
1295 }
1296 #endif /* GNUPG_MAJOR_VERSION > 1 */
1297 
1298 
1299 
1300 /* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
1301    This is used by the LEARN command. */
1302 static gpg_error_t
send_keypair_info(app_t app,ctrl_t ctrl,int keyno)1303 send_keypair_info (app_t app, ctrl_t ctrl, int keyno)
1304 {
1305   gpg_error_t err = 0;
1306   /* Note that GnuPG 1.x does not need this and it would be too time
1307      consuming to send it just for the fun of it. */
1308 #if GNUPG_MAJOR_VERSION > 1
1309   unsigned char grip[20];
1310   char gripstr[41];
1311   char idbuf[50];
1312 
1313   err = get_public_key (app, keyno);
1314   if (err)
1315     goto leave;
1316 
1317   assert (keyno >= 1 && keyno <= 3);
1318   if (!app->app_local->pk[keyno-1].key)
1319     goto leave; /* No such key - ignore. */
1320 
1321   err = keygrip_from_canon_sexp (app->app_local->pk[keyno-1].key,
1322                                  app->app_local->pk[keyno-1].keylen,
1323                                  grip);
1324   if (err)
1325     goto leave;
1326 
1327   bin2hex (grip, 20, gripstr);
1328 
1329   sprintf (idbuf, "OPENPGP.%d", keyno);
1330   send_status_info (ctrl, "KEYPAIRINFO",
1331                     gripstr, 40,
1332                     idbuf, strlen (idbuf),
1333                     NULL, (size_t)0);
1334 
1335  leave:
1336 #endif /* GNUPG_MAJOR_VERSION > 1 */
1337 
1338   return err;
1339 }
1340 
1341 
1342 /* Handle the LEARN command for OpenPGP.  */
1343 static gpg_error_t
do_learn_status(app_t app,ctrl_t ctrl,unsigned int flags)1344 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
1345 {
1346   (void)flags;
1347 
1348   do_getattr (app, ctrl, "EXTCAP");
1349   do_getattr (app, ctrl, "DISP-NAME");
1350   do_getattr (app, ctrl, "DISP-LANG");
1351   do_getattr (app, ctrl, "DISP-SEX");
1352   do_getattr (app, ctrl, "PUBKEY-URL");
1353   do_getattr (app, ctrl, "LOGIN-DATA");
1354   do_getattr (app, ctrl, "KEY-FPR");
1355   if (app->card_version > 0x0100)
1356     do_getattr (app, ctrl, "KEY-TIME");
1357   do_getattr (app, ctrl, "CA-FPR");
1358   do_getattr (app, ctrl, "CHV-STATUS");
1359   do_getattr (app, ctrl, "SIG-COUNTER");
1360   if (app->app_local->extcap.private_dos)
1361     {
1362       do_getattr (app, ctrl, "PRIVATE-DO-1");
1363       do_getattr (app, ctrl, "PRIVATE-DO-2");
1364       if (app->did_chv2)
1365         do_getattr (app, ctrl, "PRIVATE-DO-3");
1366       if (app->did_chv3)
1367         do_getattr (app, ctrl, "PRIVATE-DO-4");
1368     }
1369   send_keypair_info (app, ctrl, 1);
1370   send_keypair_info (app, ctrl, 2);
1371   send_keypair_info (app, ctrl, 3);
1372   /* Note: We do not send the Cardholder Certificate, because that is
1373      relativly long and for OpenPGP applications not really needed.  */
1374   return 0;
1375 }
1376 
1377 
1378 /* Handle the READKEY command for OpenPGP.  On success a canonical
1379    encoded S-expression with the public key will get stored at PK and
1380    its length (for assertions) at PKLEN; the caller must release that
1381    buffer. On error PK and PKLEN are not changed and an error code is
1382    returned.  */
1383 static gpg_error_t
do_readkey(app_t app,const char * keyid,unsigned char ** pk,size_t * pklen)1384 do_readkey (app_t app, const char *keyid, unsigned char **pk, size_t *pklen)
1385 {
1386 #if GNUPG_MAJOR_VERSION > 1
1387   gpg_error_t err;
1388   int keyno;
1389   unsigned char *buf;
1390 
1391   if (!strcmp (keyid, "OPENPGP.1"))
1392     keyno = 1;
1393   else if (!strcmp (keyid, "OPENPGP.2"))
1394     keyno = 2;
1395   else if (!strcmp (keyid, "OPENPGP.3"))
1396     keyno = 3;
1397   else
1398     return gpg_error (GPG_ERR_INV_ID);
1399 
1400   err = get_public_key (app, keyno);
1401   if (err)
1402     return err;
1403 
1404   buf = app->app_local->pk[keyno-1].key;
1405   if (!buf)
1406     return gpg_error (GPG_ERR_NO_PUBKEY);
1407   *pklen = app->app_local->pk[keyno-1].keylen;;
1408   *pk = xtrymalloc (*pklen);
1409   if (!*pk)
1410     {
1411       err = gpg_error_from_syserror ();
1412       *pklen = 0;
1413       return err;
1414     }
1415   memcpy (*pk, buf, *pklen);
1416   return 0;
1417 #else
1418   return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1419 #endif
1420 }
1421 
1422 /* Read the standard certificate of an OpenPGP v2 card.  It is
1423    returned in a freshly allocated buffer with that address stored at
1424    CERT and the length of the certificate stored at CERTLEN.  CERTID
1425    needs to be set to "OPENPGP.3".  */
1426 static gpg_error_t
do_readcert(app_t app,const char * certid,unsigned char ** cert,size_t * certlen)1427 do_readcert (app_t app, const char *certid,
1428              unsigned char **cert, size_t *certlen)
1429 {
1430 #if GNUPG_MAJOR_VERSION > 1
1431   gpg_error_t err;
1432   unsigned char *buffer;
1433   size_t buflen;
1434   void *relptr;
1435 
1436   *cert = NULL;
1437   *certlen = 0;
1438   if (strcmp (certid, "OPENPGP.3"))
1439     return gpg_error (GPG_ERR_INV_ID);
1440   if (!app->app_local->extcap.is_v2)
1441     return gpg_error (GPG_ERR_NOT_FOUND);
1442 
1443   relptr = get_one_do (app, 0x7F21, &buffer, &buflen, NULL);
1444   if (!relptr)
1445     return gpg_error (GPG_ERR_NOT_FOUND);
1446 
1447   if (!buflen)
1448     err = gpg_error (GPG_ERR_NOT_FOUND);
1449   else if (!(*cert = xtrymalloc (buflen)))
1450     err = gpg_error_from_syserror ();
1451   else
1452     {
1453       memcpy (*cert, buffer, buflen);
1454       *certlen = buflen;
1455       err  = 0;
1456     }
1457   xfree (relptr);
1458   return err;
1459 #else
1460   return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1461 #endif
1462 }
1463 
1464 
1465 /* Verify a CHV either using using the pinentry or if possibile by
1466    using a keypad.  PINCB and PINCB_ARG describe the usual callback
1467    for the pinentry.  CHVNO must be either 1 or 2. SIGCOUNT is only
1468    used with CHV1.  PINVALUE is the address of a pointer which will
1469    receive a newly allocated block with the actual PIN (this is useful
1470    in case that PIN shall be used for another verify operation).  The
1471    caller needs to free this value.  If the function returns with
1472    success and NULL is stored at PINVALUE, the caller should take this
1473    as an indication that the keypad has been used.
1474    */
1475 static gpg_error_t
verify_a_chv(app_t app,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg,int chvno,unsigned long sigcount,char ** pinvalue)1476 verify_a_chv (app_t app,
1477               gpg_error_t (*pincb)(void*, const char *, char **),
1478               void *pincb_arg,
1479               int chvno, unsigned long sigcount, char **pinvalue)
1480 {
1481   int rc = 0;
1482   char *prompt_buffer = NULL;
1483   const char *prompt;
1484   iso7816_pininfo_t pininfo;
1485   int minlen = 6;
1486 
1487   assert (chvno == 1 || chvno == 2);
1488 
1489   *pinvalue = NULL;
1490 
1491   if (chvno == 2 && app->app_local->flags.def_chv2)
1492     {
1493       /* Special case for def_chv2 mechanism. */
1494       if (opt.verbose)
1495         log_info (_("using default PIN as %s\n"), "CHV2");
1496       rc = iso7816_verify (app->slot, 0x82, "123456", 6);
1497       if (rc)
1498         {
1499           /* Verification of CHV2 with the default PIN failed,
1500              although the card pretends to have the default PIN set as
1501              CHV2.  We better disable the def_chv2 flag now. */
1502           log_info (_("failed to use default PIN as %s: %s"
1503                       " - disabling further default use\n"),
1504                     "CHV2", gpg_strerror (rc));
1505           app->app_local->flags.def_chv2 = 0;
1506         }
1507       return rc;
1508     }
1509 
1510   memset (&pininfo, 0, sizeof pininfo);
1511   pininfo.mode = 1;
1512   pininfo.minlen = minlen;
1513 
1514 
1515   if (chvno == 1)
1516     {
1517 #define PROMPTSTRING  _("||Please enter the PIN%%0A[sigs done: %lu]")
1518       size_t promptsize = strlen (PROMPTSTRING) + 50;
1519 
1520       prompt_buffer = xtrymalloc (promptsize);
1521       if (!prompt_buffer)
1522         return gpg_error_from_syserror ();
1523       snprintf (prompt_buffer, promptsize-1, PROMPTSTRING, sigcount);
1524       prompt = prompt_buffer;
1525 #undef PROMPTSTRING
1526     }
1527   else
1528     prompt = _("||Please enter the PIN");
1529 
1530 
1531   if (!opt.disable_keypad
1532       && !iso7816_check_keypad (app->slot, ISO7816_VERIFY, &pininfo) )
1533     {
1534       /* The reader supports the verify command through the keypad.
1535          Note that the pincb appends a text to the prompt telling the
1536          user to use the keypad. */
1537       rc = pincb (pincb_arg, prompt, NULL);
1538       prompt = NULL;
1539       xfree (prompt_buffer);
1540       prompt_buffer = NULL;
1541       if (rc)
1542         {
1543           log_info (_("PIN callback returned error: %s\n"),
1544                     gpg_strerror (rc));
1545           return rc;
1546         }
1547       rc = iso7816_verify_kp (app->slot, 0x80+chvno, "", 0, &pininfo);
1548       /* Dismiss the prompt. */
1549       pincb (pincb_arg, NULL, NULL);
1550 
1551       assert (!*pinvalue);
1552     }
1553   else
1554     {
1555       /* The reader has no keypad or we don't want to use it. */
1556       rc = pincb (pincb_arg, prompt, pinvalue);
1557       prompt = NULL;
1558       xfree (prompt_buffer);
1559       prompt_buffer = NULL;
1560       if (rc)
1561         {
1562           log_info (_("PIN callback returned error: %s\n"),
1563                     gpg_strerror (rc));
1564           return rc;
1565         }
1566 
1567       if (strlen (*pinvalue) < minlen)
1568         {
1569           log_error (_("PIN for CHV%d is too short;"
1570                        " minimum length is %d\n"), chvno, minlen);
1571           xfree (*pinvalue);
1572           *pinvalue = NULL;
1573           return gpg_error (GPG_ERR_BAD_PIN);
1574         }
1575 
1576       rc = iso7816_verify (app->slot, 0x80+chvno,
1577                            *pinvalue, strlen (*pinvalue));
1578     }
1579 
1580   if (rc)
1581     {
1582       log_error (_("verify CHV%d failed: %s\n"), chvno, gpg_strerror (rc));
1583       xfree (*pinvalue);
1584       *pinvalue = NULL;
1585       flush_cache_after_error (app);
1586     }
1587 
1588   return rc;
1589 }
1590 
1591 
1592 /* Verify CHV2 if required.  Depending on the configuration of the
1593    card CHV1 will also be verified. */
1594 static gpg_error_t
verify_chv2(app_t app,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg)1595 verify_chv2 (app_t app,
1596              gpg_error_t (*pincb)(void*, const char *, char **),
1597              void *pincb_arg)
1598 {
1599   int rc;
1600   char *pinvalue;
1601 
1602   if (app->did_chv2)
1603     return 0;  /* We already verified CHV2.  */
1604 
1605   rc = verify_a_chv (app, pincb, pincb_arg, 2, 0, &pinvalue);
1606   if (rc)
1607     return rc;
1608   app->did_chv2 = 1;
1609 
1610   if (!app->did_chv1 && !app->force_chv1 && pinvalue)
1611     {
1612       /* For convenience we verify CHV1 here too.  We do this only if
1613          the card is not configured to require a verification before
1614          each CHV1 controlled operation (force_chv1) and if we are not
1615          using the keypad (PINVALUE == NULL). */
1616       rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
1617       if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
1618         rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
1619       if (rc)
1620         {
1621           log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
1622           flush_cache_after_error (app);
1623         }
1624       else
1625         app->did_chv1 = 1;
1626     }
1627 
1628   xfree (pinvalue);
1629 
1630   return rc;
1631 }
1632 
1633 
1634 /* Build the prompt to enter the Admin PIN.  The prompt depends on the
1635    current sdtate of the card.  */
1636 static gpg_error_t
build_enter_admin_pin_prompt(app_t app,char ** r_prompt)1637 build_enter_admin_pin_prompt (app_t app, char **r_prompt)
1638 {
1639   void *relptr;
1640   unsigned char *value;
1641   size_t valuelen;
1642   int remaining;
1643   char *prompt;
1644 
1645   *r_prompt = NULL;
1646 
1647   relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
1648   if (!relptr || valuelen < 7)
1649     {
1650       log_error (_("error retrieving CHV status from card\n"));
1651       xfree (relptr);
1652       return gpg_error (GPG_ERR_CARD);
1653     }
1654   if (value[6] == 0)
1655     {
1656       log_info (_("card is permanently locked!\n"));
1657       xfree (relptr);
1658       return gpg_error (GPG_ERR_BAD_PIN);
1659     }
1660   remaining = value[6];
1661   xfree (relptr);
1662 
1663   log_info(_("%d Admin PIN attempts remaining before card"
1664              " is permanently locked\n"), remaining);
1665 
1666   if (remaining < 3)
1667     {
1668       /* TRANSLATORS: Do not translate the "|A|" prefix but keep it at
1669          the start of the string.  Use %%0A to force a linefeed.  */
1670       prompt = xtryasprintf (_("|A|Please enter the Admin PIN%%0A"
1671                                "[remaining attempts: %d]"), remaining);
1672     }
1673   else
1674     prompt = xtrystrdup (_("|A|Please enter the Admin PIN"));
1675 
1676   if (!prompt)
1677     return gpg_error_from_syserror ();
1678 
1679   *r_prompt = prompt;
1680   return 0;
1681 }
1682 
1683 
1684 /* Verify CHV3 if required. */
1685 static gpg_error_t
verify_chv3(app_t app,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg)1686 verify_chv3 (app_t app,
1687              gpg_error_t (*pincb)(void*, const char *, char **),
1688              void *pincb_arg)
1689 {
1690   int rc = 0;
1691 
1692 #if GNUPG_MAJOR_VERSION != 1
1693   if (!opt.allow_admin)
1694     {
1695       log_info (_("access to admin commands is not configured\n"));
1696       return gpg_error (GPG_ERR_EACCES);
1697     }
1698 #endif
1699 
1700   if (!app->did_chv3)
1701     {
1702       iso7816_pininfo_t pininfo;
1703       int minlen = 8;
1704       char *prompt;
1705 
1706       memset (&pininfo, 0, sizeof pininfo);
1707       pininfo.mode = 1;
1708       pininfo.minlen = minlen;
1709 
1710       rc = build_enter_admin_pin_prompt (app, &prompt);
1711       if (rc)
1712         return rc;
1713 
1714       if (!opt.disable_keypad
1715           && !iso7816_check_keypad (app->slot, ISO7816_VERIFY, &pininfo) )
1716         {
1717           /* The reader supports the verify command through the keypad. */
1718           rc = pincb (pincb_arg, prompt, NULL);
1719           xfree (prompt);
1720           prompt = NULL;
1721           if (rc)
1722             {
1723               log_info (_("PIN callback returned error: %s\n"),
1724                         gpg_strerror (rc));
1725               return rc;
1726             }
1727           rc = iso7816_verify_kp (app->slot, 0x83, "", 0, &pininfo);
1728           /* Dismiss the prompt. */
1729           pincb (pincb_arg, NULL, NULL);
1730         }
1731       else
1732         {
1733           char *pinvalue;
1734 
1735           rc = pincb (pincb_arg, prompt, &pinvalue);
1736           xfree (prompt);
1737           prompt = NULL;
1738           if (rc)
1739             {
1740               log_info (_("PIN callback returned error: %s\n"),
1741                         gpg_strerror (rc));
1742               return rc;
1743             }
1744 
1745           if (strlen (pinvalue) < minlen)
1746             {
1747               log_error (_("PIN for CHV%d is too short;"
1748                            " minimum length is %d\n"), 3, minlen);
1749               xfree (pinvalue);
1750               return gpg_error (GPG_ERR_BAD_PIN);
1751             }
1752 
1753           rc = iso7816_verify (app->slot, 0x83, pinvalue, strlen (pinvalue));
1754           xfree (pinvalue);
1755         }
1756 
1757       if (rc)
1758         {
1759           log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
1760           flush_cache_after_error (app);
1761           return rc;
1762         }
1763       app->did_chv3 = 1;
1764     }
1765   return rc;
1766 }
1767 
1768 
1769 /* Handle the SETATTR operation. All arguments are already basically
1770    checked. */
1771 static gpg_error_t
do_setattr(app_t app,const char * name,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg,const unsigned char * value,size_t valuelen)1772 do_setattr (app_t app, const char *name,
1773             gpg_error_t (*pincb)(void*, const char *, char **),
1774             void *pincb_arg,
1775             const unsigned char *value, size_t valuelen)
1776 {
1777   gpg_error_t rc;
1778   int idx;
1779   static struct {
1780     const char *name;
1781     int tag;
1782     int need_chv;
1783     int special;
1784     unsigned int need_v2:1;
1785   } table[] = {
1786     { "DISP-NAME",    0x005B, 3 },
1787     { "LOGIN-DATA",   0x005E, 3, 2 },
1788     { "DISP-LANG",    0x5F2D, 3 },
1789     { "DISP-SEX",     0x5F35, 3 },
1790     { "PUBKEY-URL",   0x5F50, 3 },
1791     { "CHV-STATUS-1", 0x00C4, 3, 1 },
1792     { "CA-FPR-1",     0x00CA, 3 },
1793     { "CA-FPR-2",     0x00CB, 3 },
1794     { "CA-FPR-3",     0x00CC, 3 },
1795     { "PRIVATE-DO-1", 0x0101, 2 },
1796     { "PRIVATE-DO-2", 0x0102, 3 },
1797     { "PRIVATE-DO-3", 0x0103, 2 },
1798     { "PRIVATE-DO-4", 0x0104, 3 },
1799     { "CERT-3",       0x7F21, 3, 0, 1 },
1800     { "SM-KEY-ENC",   0x00D1, 3, 0, 1 },
1801     { "SM-KEY-MAC",   0x00D2, 3, 0, 1 },
1802     { "KEY-ATTR",     0,      0, 3, 1 },
1803     { NULL, 0 }
1804   };
1805   int exmode;
1806 
1807   for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
1808     ;
1809   if (!table[idx].name)
1810     return gpg_error (GPG_ERR_INV_NAME);
1811   if (table[idx].need_v2 && !app->app_local->extcap.is_v2)
1812     return gpg_error (GPG_ERR_NOT_SUPPORTED); /* Not yet supported.  */
1813 
1814   if (table[idx].special == 3)
1815     return change_keyattr_from_string (app, pincb, pincb_arg, value, valuelen);
1816 
1817   switch (table[idx].need_chv)
1818     {
1819     case 2:
1820       rc = verify_chv2 (app, pincb, pincb_arg);
1821       break;
1822     case 3:
1823       rc = verify_chv3 (app, pincb, pincb_arg);
1824       break;
1825     default:
1826       rc = 0;
1827     }
1828   if (rc)
1829     return rc;
1830 
1831   /* Flush the cache before writing it, so that the next get operation
1832      will reread the data from the card and thus get synced in case of
1833      errors (e.g. data truncated by the card). */
1834   flush_cache_item (app, table[idx].tag);
1835 
1836   if (app->app_local->cardcap.ext_lc_le && valuelen > 254)
1837     exmode = 1;    /* Use extended length w/o a limit.  */
1838   else if (app->app_local->cardcap.cmd_chaining && valuelen > 254)
1839     exmode = -254; /* Command chaining with max. 254 bytes.  */
1840   else
1841     exmode = 0;
1842   rc = iso7816_put_data (app->slot, exmode, table[idx].tag, value, valuelen);
1843   if (rc)
1844     log_error ("failed to set `%s': %s\n", table[idx].name, gpg_strerror (rc));
1845 
1846   if (table[idx].special == 1)
1847     app->force_chv1 = (valuelen && *value == 0);
1848   else if (table[idx].special == 2)
1849     parse_login_data (app);
1850 
1851   return rc;
1852 }
1853 
1854 
1855 /* Handle the WRITECERT command for OpenPGP.  This rites the standard
1856    certifciate to the card; CERTID needs to be set to "OPENPGP.3".
1857    PINCB and PINCB_ARG are the usual arguments for the pinentry
1858    callback.  */
1859 static gpg_error_t
do_writecert(app_t app,ctrl_t ctrl,const char * certidstr,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg,const unsigned char * certdata,size_t certdatalen)1860 do_writecert (app_t app, ctrl_t ctrl,
1861               const char *certidstr,
1862               gpg_error_t (*pincb)(void*, const char *, char **),
1863               void *pincb_arg,
1864               const unsigned char *certdata, size_t certdatalen)
1865 {
1866   (void)ctrl;
1867 #if GNUPG_MAJOR_VERSION > 1
1868   if (strcmp (certidstr, "OPENPGP.3"))
1869     return gpg_error (GPG_ERR_INV_ID);
1870   if (!certdata || !certdatalen)
1871     return gpg_error (GPG_ERR_INV_ARG);
1872   if (!app->app_local->extcap.is_v2)
1873     return gpg_error (GPG_ERR_NOT_SUPPORTED);
1874   if (certdatalen > app->app_local->extcap.max_certlen_3)
1875     return gpg_error (GPG_ERR_TOO_LARGE);
1876   return do_setattr (app, "CERT-3", pincb, pincb_arg, certdata, certdatalen);
1877 #else
1878   return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1879 #endif
1880 }
1881 
1882 
1883 
1884 /* Handle the PASSWD command.  The following combinations are
1885    possible:
1886 
1887     Flags  CHVNO Vers.  Description
1888     RESET    1   1      Verify CHV3 and set a new CHV1 and CHV2
1889     RESET    1   2      Verify PW3 and set a new PW1.
1890     RESET    2   1      Verify CHV3 and set a new CHV1 and CHV2.
1891     RESET    2   2      Verify PW3 and set a new Reset Code.
1892     RESET    3   any    Returns GPG_ERR_INV_ID.
1893      -       1   1      Verify CHV2 and set a new CHV1 and CHV2.
1894      -       1   2      Verify PW1 and set a new PW1.
1895      -       2   1      Verify CHV2 and set a new CHV1 and CHV2.
1896      -       2   2      Verify Reset Code and set a new PW1.
1897      -       3   any    Verify CHV3/PW3 and set a new CHV3/PW3.
1898  */
1899 static gpg_error_t
do_change_pin(app_t app,ctrl_t ctrl,const char * chvnostr,unsigned int flags,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg)1900 do_change_pin (app_t app, ctrl_t ctrl,  const char *chvnostr,
1901                unsigned int flags,
1902                gpg_error_t (*pincb)(void*, const char *, char **),
1903                void *pincb_arg)
1904 {
1905   int rc = 0;
1906   int chvno = atoi (chvnostr);
1907   char *resetcode = NULL;
1908   char *oldpinvalue = NULL;
1909   char *pinvalue;
1910   int reset_mode = !!(flags & APP_CHANGE_FLAG_RESET);
1911   int set_resetcode = 0;
1912 
1913   (void)ctrl;
1914 
1915   if (reset_mode && chvno == 3)
1916     {
1917       rc = gpg_error (GPG_ERR_INV_ID);
1918       goto leave;
1919     }
1920 
1921   if (!app->app_local->extcap.is_v2)
1922     {
1923       /* Version 1 cards.  */
1924 
1925       if (reset_mode || chvno == 3)
1926         {
1927           /* We always require that the PIN is entered. */
1928           app->did_chv3 = 0;
1929           rc = verify_chv3 (app, pincb, pincb_arg);
1930           if (rc)
1931             goto leave;
1932         }
1933       else if (chvno == 1 || chvno == 2)
1934         {
1935           /* On a v1.x card CHV1 and CVH2 should always have the same
1936              value, thus we enforce it here.  */
1937           int save_force = app->force_chv1;
1938 
1939           app->force_chv1 = 0;
1940           app->did_chv1 = 0;
1941           app->did_chv2 = 0;
1942           rc = verify_chv2 (app, pincb, pincb_arg);
1943           app->force_chv1 = save_force;
1944           if (rc)
1945             goto leave;
1946         }
1947       else
1948         {
1949           rc = gpg_error (GPG_ERR_INV_ID);
1950           goto leave;
1951         }
1952     }
1953   else
1954     {
1955       /* Version 2 cards.  */
1956 
1957       if (reset_mode)
1958         {
1959           /* To reset a PIN the Admin PIN is required. */
1960           app->did_chv3 = 0;
1961           rc = verify_chv3 (app, pincb, pincb_arg);
1962           if (rc)
1963             goto leave;
1964 
1965           if (chvno == 2)
1966             set_resetcode = 1;
1967         }
1968       else if (chvno == 1 || chvno == 3)
1969         {
1970           int minlen = (chvno ==3)? 8 : 6;
1971           char *promptbuf = NULL;
1972           const char *prompt;
1973 
1974           if (chvno == 3)
1975             {
1976               rc = build_enter_admin_pin_prompt (app, &promptbuf);
1977               if (rc)
1978                 goto leave;
1979               prompt = promptbuf;
1980             }
1981           else
1982             prompt = _("||Please enter the PIN");
1983           rc = pincb (pincb_arg, prompt, &oldpinvalue);
1984           xfree (promptbuf);
1985           promptbuf = NULL;
1986           if (rc)
1987             {
1988               log_info (_("PIN callback returned error: %s\n"),
1989                         gpg_strerror (rc));
1990               goto leave;
1991             }
1992 
1993           if (strlen (oldpinvalue) < minlen)
1994             {
1995               log_info (_("PIN for CHV%d is too short;"
1996                           " minimum length is %d\n"), chvno, minlen);
1997               rc = gpg_error (GPG_ERR_BAD_PIN);
1998               goto leave;
1999             }
2000         }
2001       else if (chvno == 2)
2002         {
2003           /* There is no PW2 for v2 cards.  We use this condition to
2004              allow a PW reset using the Reset Code.  */
2005           void *relptr;
2006           unsigned char *value;
2007           size_t valuelen;
2008           int remaining;
2009           int minlen = 8;
2010 
2011           relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
2012           if (!relptr || valuelen < 7)
2013             {
2014               log_error (_("error retrieving CHV status from card\n"));
2015               xfree (relptr);
2016               rc = gpg_error (GPG_ERR_CARD);
2017               goto leave;
2018             }
2019           remaining = value[5];
2020           xfree (relptr);
2021           if (!remaining)
2022             {
2023               log_error (_("Reset Code not or not anymore available\n"));
2024               rc = gpg_error (GPG_ERR_BAD_PIN);
2025               goto leave;
2026             }
2027 
2028           rc = pincb (pincb_arg,
2029                       _("||Please enter the Reset Code for the card"),
2030                       &resetcode);
2031           if (rc)
2032             {
2033               log_info (_("PIN callback returned error: %s\n"),
2034                         gpg_strerror (rc));
2035               goto leave;
2036             }
2037           if (strlen (resetcode) < minlen)
2038             {
2039               log_info (_("Reset Code is too short; minimum length is %d\n"),
2040                         minlen);
2041               rc = gpg_error (GPG_ERR_BAD_PIN);
2042               goto leave;
2043             }
2044         }
2045       else
2046         {
2047           rc = gpg_error (GPG_ERR_INV_ID);
2048           goto leave;
2049         }
2050     }
2051 
2052   if (chvno == 3)
2053     app->did_chv3 = 0;
2054   else
2055     app->did_chv1 = app->did_chv2 = 0;
2056 
2057   /* TRANSLATORS: Do not translate the "|*|" prefixes but
2058      keep it at the start of the string.  We need this elsewhere
2059      to get some infos on the string. */
2060   rc = pincb (pincb_arg, set_resetcode? _("|RN|New Reset Code") :
2061               chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
2062               &pinvalue);
2063   if (rc)
2064     {
2065       log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
2066       goto leave;
2067     }
2068 
2069 
2070   if (resetcode)
2071     {
2072       char *buffer;
2073 
2074       buffer = xtrymalloc (strlen (resetcode) + strlen (pinvalue) + 1);
2075       if (!buffer)
2076         rc = gpg_error_from_syserror ();
2077       else
2078         {
2079           strcpy (stpcpy (buffer, resetcode), pinvalue);
2080           rc = iso7816_reset_retry_counter_with_rc (app->slot, 0x81,
2081                                                     buffer, strlen (buffer));
2082           wipememory (buffer, strlen (buffer));
2083           xfree (buffer);
2084         }
2085     }
2086   else if (set_resetcode)
2087     {
2088       if (strlen (pinvalue) < 8)
2089         {
2090           log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
2091           rc = gpg_error (GPG_ERR_BAD_PIN);
2092         }
2093       else
2094         rc = iso7816_put_data (app->slot, 0, 0xD3,
2095                                pinvalue, strlen (pinvalue));
2096     }
2097   else if (reset_mode)
2098     {
2099       rc = iso7816_reset_retry_counter (app->slot, 0x81,
2100                                         pinvalue, strlen (pinvalue));
2101       if (!rc && !app->app_local->extcap.is_v2)
2102         rc = iso7816_reset_retry_counter (app->slot, 0x82,
2103                                           pinvalue, strlen (pinvalue));
2104     }
2105   else if (!app->app_local->extcap.is_v2)
2106     {
2107       /* Version 1 cards.  */
2108       if (chvno == 1 || chvno == 2)
2109         {
2110           rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
2111                                               pinvalue, strlen (pinvalue));
2112           if (!rc)
2113             rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
2114                                                 pinvalue, strlen (pinvalue));
2115         }
2116       else /* CHVNO == 3 */
2117         {
2118           rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
2119                                               pinvalue, strlen (pinvalue));
2120         }
2121     }
2122   else
2123     {
2124       /* Version 2 cards.  */
2125       assert (chvno == 1 || chvno == 3);
2126 
2127       rc = iso7816_change_reference_data (app->slot, 0x80 + chvno,
2128                                           oldpinvalue, strlen (oldpinvalue),
2129                                           pinvalue, strlen (pinvalue));
2130     }
2131 
2132   if (pinvalue)
2133     {
2134       wipememory (pinvalue, strlen (pinvalue));
2135       xfree (pinvalue);
2136     }
2137   if (rc)
2138     flush_cache_after_error (app);
2139 
2140  leave:
2141   if (resetcode)
2142     {
2143       wipememory (resetcode, strlen (resetcode));
2144       xfree (resetcode);
2145     }
2146   if (oldpinvalue)
2147     {
2148       wipememory (oldpinvalue, strlen (oldpinvalue));
2149       xfree (oldpinvalue);
2150     }
2151   return rc;
2152 }
2153 
2154 
2155 /* Check whether a key already exists.  KEYIDX is the index of the key
2156    (0..2).  If FORCE is TRUE a diagnositic will be printed but no
2157    error returned if the key already exists.  The flag GENERATING is
2158    only used to print correct messages. */
2159 static gpg_error_t
does_key_exist(app_t app,int keyidx,int generating,int force)2160 does_key_exist (app_t app, int keyidx, int generating, int force)
2161 {
2162   const unsigned char *fpr;
2163   unsigned char *buffer;
2164   size_t buflen, n;
2165   int i;
2166 
2167   assert (keyidx >=0 && keyidx <= 2);
2168 
2169   if (iso7816_get_data (app->slot, 0, 0x006E, &buffer, &buflen))
2170     {
2171       log_error (_("error reading application data\n"));
2172       return gpg_error (GPG_ERR_GENERAL);
2173     }
2174   fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2175   if (!fpr || n < 60)
2176     {
2177       log_error (_("error reading fingerprint DO\n"));
2178       xfree (buffer);
2179       return gpg_error (GPG_ERR_GENERAL);
2180     }
2181   fpr += 20*keyidx;
2182   for (i=0; i < 20 && !fpr[i]; i++)
2183     ;
2184   xfree (buffer);
2185   if (i!=20 && !force)
2186     {
2187       log_error (_("key already exists\n"));
2188       return gpg_error (GPG_ERR_EEXIST);
2189     }
2190   else if (i!=20)
2191     log_info (_("existing key will be replaced\n"));
2192   else if (generating)
2193     log_info (_("generating new key\n"));
2194   else
2195     log_info (_("writing new key\n"));
2196   return 0;
2197 }
2198 
2199 
2200 /* Create a TLV tag and value and store it at BUFFER.  Return the length
2201    of tag and length.  A LENGTH greater than 65535 is truncated. */
2202 static size_t
add_tlv(unsigned char * buffer,unsigned int tag,size_t length)2203 add_tlv (unsigned char *buffer, unsigned int tag, size_t length)
2204 {
2205   unsigned char *p = buffer;
2206 
2207   assert (tag <= 0xffff);
2208   if ( tag > 0xff )
2209     *p++ = tag >> 8;
2210   *p++ = tag;
2211   if (length < 128)
2212     *p++ = length;
2213   else if (length < 256)
2214     {
2215       *p++ = 0x81;
2216       *p++ = length;
2217     }
2218   else
2219     {
2220       if (length > 0xffff)
2221         length = 0xffff;
2222       *p++ = 0x82;
2223       *p++ = length >> 8;
2224       *p++ = length;
2225     }
2226 
2227   return p - buffer;
2228 }
2229 
2230 
2231 /* Build the private key template as specified in the OpenPGP specs
2232    v2.0 section 4.3.3.7.  */
2233 static gpg_error_t
build_privkey_template(app_t app,int keyno,const unsigned char * rsa_n,size_t rsa_n_len,const unsigned char * rsa_e,size_t rsa_e_len,const unsigned char * rsa_p,size_t rsa_p_len,const unsigned char * rsa_q,size_t rsa_q_len,unsigned char ** result,size_t * resultlen)2234 build_privkey_template (app_t app, int keyno,
2235                         const unsigned char *rsa_n, size_t rsa_n_len,
2236                         const unsigned char *rsa_e, size_t rsa_e_len,
2237                         const unsigned char *rsa_p, size_t rsa_p_len,
2238                         const unsigned char *rsa_q, size_t rsa_q_len,
2239                         unsigned char **result, size_t *resultlen)
2240 {
2241   size_t rsa_e_reqlen;
2242   unsigned char privkey[7*(1+3)];
2243   size_t privkey_len;
2244   unsigned char exthdr[2+2+3];
2245   size_t exthdr_len;
2246   unsigned char suffix[2+3];
2247   size_t suffix_len;
2248   unsigned char *tp;
2249   size_t datalen;
2250   unsigned char *template;
2251   size_t template_size;
2252 
2253   *result = NULL;
2254   *resultlen = 0;
2255 
2256   switch (app->app_local->keyattr[keyno].format)
2257     {
2258     case RSA_STD:
2259     case RSA_STD_N:
2260       break;
2261     case RSA_CRT:
2262     case RSA_CRT_N:
2263       return gpg_error (GPG_ERR_NOT_SUPPORTED);
2264 
2265     default:
2266       return gpg_error (GPG_ERR_INV_VALUE);
2267     }
2268 
2269   /* Get the required length for E.  */
2270   rsa_e_reqlen = app->app_local->keyattr[keyno].e_bits/8;
2271   assert (rsa_e_len <= rsa_e_reqlen);
2272 
2273   /* Build the 7f48 cardholder private key template.  */
2274   datalen = 0;
2275   tp = privkey;
2276 
2277   tp += add_tlv (tp, 0x91, rsa_e_reqlen);
2278   datalen += rsa_e_reqlen;
2279 
2280   tp += add_tlv (tp, 0x92, rsa_p_len);
2281   datalen += rsa_p_len;
2282 
2283   tp += add_tlv (tp, 0x93, rsa_q_len);
2284   datalen += rsa_q_len;
2285 
2286   if (app->app_local->keyattr[keyno].format == RSA_STD_N
2287       || app->app_local->keyattr[keyno].format == RSA_CRT_N)
2288     {
2289       tp += add_tlv (tp, 0x97, rsa_n_len);
2290       datalen += rsa_n_len;
2291     }
2292   privkey_len = tp - privkey;
2293 
2294   /* Build the extended header list without the private key template.  */
2295   tp = exthdr;
2296   *tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4;
2297   *tp++ = 0;
2298   tp += add_tlv (tp, 0x7f48, privkey_len);
2299   exthdr_len = tp - exthdr;
2300 
2301   /* Build the 5f48 suffix of the data.  */
2302   tp = suffix;
2303   tp += add_tlv (tp, 0x5f48, datalen);
2304   suffix_len = tp - suffix;
2305 
2306   /* Now concatenate everything.  */
2307   template_size = (1 + 3   /* 0x4d and len. */
2308                    + exthdr_len
2309                    + privkey_len
2310                    + suffix_len
2311                    + datalen);
2312   tp = template = xtrymalloc_secure (template_size);
2313   if (!template)
2314     return gpg_error_from_syserror ();
2315 
2316   tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen);
2317   memcpy (tp, exthdr, exthdr_len);
2318   tp += exthdr_len;
2319   memcpy (tp, privkey, privkey_len);
2320   tp += privkey_len;
2321   memcpy (tp, suffix, suffix_len);
2322   tp += suffix_len;
2323 
2324   memcpy (tp, rsa_e, rsa_e_len);
2325   if (rsa_e_len < rsa_e_reqlen)
2326     {
2327       /* Right justify E. */
2328       memmove (tp + rsa_e_reqlen - rsa_e_len, tp, rsa_e_len);
2329       memset (tp, 0, rsa_e_reqlen - rsa_e_len);
2330     }
2331   tp += rsa_e_reqlen;
2332 
2333   memcpy (tp, rsa_p, rsa_p_len);
2334   tp += rsa_p_len;
2335 
2336   memcpy (tp, rsa_q, rsa_q_len);
2337   tp += rsa_q_len;
2338 
2339   if (app->app_local->keyattr[keyno].format == RSA_STD_N
2340       || app->app_local->keyattr[keyno].format == RSA_CRT_N)
2341     {
2342       memcpy (tp, rsa_n, rsa_n_len);
2343       tp += rsa_n_len;
2344     }
2345 
2346   /* Sanity check.  We don't know the exact length because we
2347      allocated 3 bytes for the first length header.  */
2348   assert (tp - template <= template_size);
2349 
2350   *result = template;
2351   *resultlen = tp - template;
2352   return 0;
2353 }
2354 
2355 
2356 /* Helper for do_writekley to change the size of a key.  Not ethat
2357    this deletes the entire key without asking.  */
2358 static gpg_error_t
change_keyattr(app_t app,int keyno,unsigned int nbits,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg)2359 change_keyattr (app_t app, int keyno, unsigned int nbits,
2360                 gpg_error_t (*pincb)(void*, const char *, char **),
2361                 void *pincb_arg)
2362 {
2363   gpg_error_t err;
2364   unsigned char *buffer;
2365   size_t buflen;
2366   void *relptr;
2367 
2368   assert (keyno >=0 && keyno <= 2);
2369 
2370   if (nbits > 3072)
2371     return gpg_error (GPG_ERR_TOO_LARGE);
2372 
2373   /* Read the current attributes into a buffer.  */
2374   relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL);
2375   if (!relptr)
2376     return gpg_error (GPG_ERR_CARD);
2377   if (buflen < 6 || buffer[0] != 1)
2378     {
2379       /* Attriutes too short or not an RSA key.  */
2380       xfree (relptr);
2381       return gpg_error (GPG_ERR_CARD);
2382     }
2383 
2384   /* We only change n_bits and don't touch anything else.  Before we
2385      do so, we round up NBITS to a sensible way in the same way as
2386      gpg's key generation does it.  This may help to sort out problems
2387      with a few bits too short keys.  */
2388   nbits = ((nbits + 31) / 32) * 32;
2389   buffer[1] = (nbits >> 8);
2390   buffer[2] = nbits;
2391 
2392   /* Prepare for storing the key.  */
2393   err = verify_chv3 (app, pincb, pincb_arg);
2394   if (err)
2395     {
2396       xfree (relptr);
2397       return err;
2398     }
2399 
2400   /* Change the attribute.  */
2401   err = iso7816_put_data (app->slot, 0, 0xC1+keyno, buffer, buflen);
2402   xfree (relptr);
2403   if (err)
2404     log_error ("error changing size of key %d to %u bits\n", keyno+1, nbits);
2405   else
2406     log_info ("size of key %d changed to %u bits\n", keyno+1, nbits);
2407   flush_cache (app);
2408   parse_algorithm_attribute (app, keyno);
2409   app->did_chv1 = 0;
2410   app->did_chv2 = 0;
2411   app->did_chv3 = 0;
2412   return err;
2413 }
2414 
2415 
2416 /* Helper to process an setattr command for name KEY-ATTR.  It expects
2417    a string "--force <keyno> <algo> <nbits>" in (VALUE,VALUELEN).  */
2418 static gpg_error_t
change_keyattr_from_string(app_t app,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg,const void * value,size_t valuelen)2419 change_keyattr_from_string (app_t app,
2420                             gpg_error_t (*pincb)(void*, const char *, char **),
2421                             void *pincb_arg,
2422                             const void *value, size_t valuelen)
2423 {
2424   gpg_error_t err;
2425   char *string;
2426   int keyno, algo;
2427   unsigned int nbits;
2428 
2429   /* VALUE is expected to be a string but not guaranteed to be
2430      terminated.  Thus copy it to an allocated buffer first. */
2431   string = xtrymalloc (valuelen+1);
2432   if (!string)
2433     return gpg_error_from_syserror ();
2434   memcpy (string, value, valuelen);
2435   string[valuelen] = 0;
2436 
2437   /* Because this function deletes the key we require the string
2438      "--force" in the data to make clear that something serious might
2439      happen.  */
2440   if (sscanf (string, " --force %d %d %u", &keyno, &algo, &nbits) != 3)
2441     err = gpg_error (GPG_ERR_INV_DATA);
2442   else if (keyno < 1 || keyno > 3)
2443     err = gpg_error (GPG_ERR_INV_ID);
2444   else if (algo != 1)
2445     err = gpg_error (GPG_ERR_PUBKEY_ALGO); /* Not RSA.  */
2446   else if (nbits < 1024)
2447     err = gpg_error (GPG_ERR_TOO_SHORT);
2448   else
2449     err = change_keyattr (app, keyno-1, nbits, pincb, pincb_arg);
2450 
2451   xfree (string);
2452   return err;
2453 }
2454 
2455 
2456 /* Handle the WRITEKEY command for OpenPGP.  This function expects a
2457    canonical encoded S-expression with the secret key in KEYDATA and
2458    its length (for assertions) in KEYDATALEN.  KEYID needs to be the
2459    usual keyid which for OpenPGP is the string "OPENPGP.n" with
2460    n=1,2,3.  Bit 0 of FLAGS indicates whether an existing key shall
2461    get overwritten.  PINCB and PINCB_ARG are the usual arguments for
2462    the pinentry callback.  */
2463 static gpg_error_t
do_writekey(app_t app,ctrl_t ctrl,const char * keyid,unsigned int flags,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg,const unsigned char * keydata,size_t keydatalen)2464 do_writekey (app_t app, ctrl_t ctrl,
2465              const char *keyid, unsigned int flags,
2466              gpg_error_t (*pincb)(void*, const char *, char **),
2467              void *pincb_arg,
2468              const unsigned char *keydata, size_t keydatalen)
2469 {
2470   gpg_error_t err;
2471   int force = (flags & 1);
2472   int keyno;
2473   const unsigned char *buf, *tok;
2474   size_t buflen, toklen;
2475   int depth, last_depth1, last_depth2;
2476   const unsigned char *rsa_n = NULL;
2477   const unsigned char *rsa_e = NULL;
2478   const unsigned char *rsa_p = NULL;
2479   const unsigned char *rsa_q = NULL;
2480   size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
2481   unsigned int nbits;
2482   unsigned int maxbits;
2483   unsigned char *template = NULL;
2484   unsigned char *tp;
2485   size_t template_len;
2486   unsigned char fprbuf[20];
2487   u32 created_at = 0;
2488 
2489   (void)ctrl;
2490 
2491   if (!strcmp (keyid, "OPENPGP.1"))
2492     keyno = 0;
2493   else if (!strcmp (keyid, "OPENPGP.2"))
2494     keyno = 1;
2495   else if (!strcmp (keyid, "OPENPGP.3"))
2496     keyno = 2;
2497   else
2498     return gpg_error (GPG_ERR_INV_ID);
2499 
2500   err = does_key_exist (app, keyno, 0, force);
2501   if (err)
2502     return err;
2503 
2504 
2505   /*
2506      Parse the S-expression
2507    */
2508   buf = keydata;
2509   buflen = keydatalen;
2510   depth = 0;
2511   if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2512     goto leave;
2513   if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2514     goto leave;
2515   if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
2516     {
2517       if (!tok)
2518         ;
2519       else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
2520         log_info ("protected-private-key passed to writekey\n");
2521       else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
2522         log_info ("shadowed-private-key passed to writekey\n");
2523       err = gpg_error (GPG_ERR_BAD_SECKEY);
2524       goto leave;
2525     }
2526   if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2527     goto leave;
2528   if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2529     goto leave;
2530   if (!tok || toklen != 3 || memcmp ("rsa", tok, toklen))
2531     {
2532       err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
2533       goto leave;
2534     }
2535   last_depth1 = depth;
2536   while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2537          && depth && depth >= last_depth1)
2538     {
2539       if (tok)
2540         {
2541           err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2542           goto leave;
2543         }
2544       if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2545         goto leave;
2546       if (tok && toklen == 1)
2547         {
2548           const unsigned char **mpi;
2549           size_t *mpi_len;
2550 
2551           switch (*tok)
2552             {
2553             case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
2554             case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
2555             case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break;
2556             case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break;
2557             default: mpi = NULL;  mpi_len = NULL; break;
2558             }
2559           if (mpi && *mpi)
2560             {
2561               err = gpg_error (GPG_ERR_DUP_VALUE);
2562               goto leave;
2563             }
2564           if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2565             goto leave;
2566           if (tok && mpi)
2567             {
2568               /* Strip off leading zero bytes and save. */
2569               for (;toklen && !*tok; toklen--, tok++)
2570                 ;
2571               *mpi = tok;
2572               *mpi_len = toklen;
2573             }
2574         }
2575       /* Skip until end of list. */
2576       last_depth2 = depth;
2577       while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2578              && depth && depth >= last_depth2)
2579         ;
2580       if (err)
2581         goto leave;
2582     }
2583   /* Parse other attributes. */
2584   last_depth1 = depth;
2585   while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2586          && depth && depth >= last_depth1)
2587     {
2588       if (tok)
2589         {
2590           err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
2591           goto leave;
2592         }
2593       if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
2594         goto leave;
2595       if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
2596         {
2597           if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
2598             goto leave;
2599           if (tok)
2600             {
2601               for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
2602                    tok++, toklen--)
2603                 created_at = created_at*10 + (*tok - '0');
2604             }
2605         }
2606       /* Skip until end of list. */
2607       last_depth2 = depth;
2608       while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
2609              && depth && depth >= last_depth2)
2610         ;
2611       if (err)
2612         goto leave;
2613     }
2614 
2615 
2616   /* Check that we have all parameters and that they match the card
2617      description. */
2618   if (!created_at)
2619     {
2620       log_error (_("creation timestamp missing\n"));
2621       err = gpg_error (GPG_ERR_INV_VALUE);
2622       goto leave;
2623     }
2624 
2625   maxbits = app->app_local->keyattr[keyno].n_bits;
2626   nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
2627   if (opt.verbose)
2628     log_info ("RSA modulus size is %u bits (%u bytes)\n",
2629               nbits, (unsigned int)rsa_n_len);
2630   if (nbits && nbits != maxbits
2631       && app->app_local->extcap.algo_attr_change)
2632     {
2633       /* Try to switch the key to a new length.  */
2634       err = change_keyattr (app, keyno, nbits, pincb, pincb_arg);
2635       if (!err)
2636         maxbits = app->app_local->keyattr[keyno].n_bits;
2637     }
2638   if (nbits != maxbits)
2639     {
2640       log_error (_("RSA modulus missing or not of size %d bits\n"),
2641                  (int)maxbits);
2642       err = gpg_error (GPG_ERR_BAD_SECKEY);
2643       goto leave;
2644     }
2645 
2646   maxbits = app->app_local->keyattr[keyno].e_bits;
2647   if (maxbits > 32 && !app->app_local->extcap.is_v2)
2648     maxbits = 32; /* Our code for v1 does only support 32 bits.  */
2649   nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
2650   if (nbits < 2 || nbits > maxbits)
2651     {
2652       log_error (_("RSA public exponent missing or larger than %d bits\n"),
2653                  (int)maxbits);
2654       err = gpg_error (GPG_ERR_BAD_SECKEY);
2655       goto leave;
2656     }
2657 
2658   maxbits = app->app_local->keyattr[keyno].n_bits/2;
2659   nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
2660   if (nbits != maxbits)
2661     {
2662       log_error (_("RSA prime %s missing or not of size %d bits\n"),
2663                  "P", (int)maxbits);
2664       err = gpg_error (GPG_ERR_BAD_SECKEY);
2665       goto leave;
2666     }
2667   nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
2668   if (nbits != maxbits)
2669     {
2670       log_error (_("RSA prime %s missing or not of size %d bits\n"),
2671                  "Q", (int)maxbits);
2672       err = gpg_error (GPG_ERR_BAD_SECKEY);
2673       goto leave;
2674     }
2675 
2676   /* We need to remove the cached public key.  */
2677   xfree (app->app_local->pk[keyno].key);
2678   app->app_local->pk[keyno].key = NULL;
2679   app->app_local->pk[keyno].keylen = 0;
2680   app->app_local->pk[keyno].read_done = 0;
2681 
2682 
2683   if (app->app_local->extcap.is_v2)
2684     {
2685       /* Build the private key template as described in section 4.3.3.7 of
2686          the OpenPGP card specs version 2.0.  */
2687       int exmode;
2688 
2689       err = build_privkey_template (app, keyno,
2690                                     rsa_n, rsa_n_len,
2691                                     rsa_e, rsa_e_len,
2692                                     rsa_p, rsa_p_len,
2693                                     rsa_q, rsa_q_len,
2694                                     &template, &template_len);
2695       if (err)
2696         goto leave;
2697 
2698       /* Prepare for storing the key.  */
2699       err = verify_chv3 (app, pincb, pincb_arg);
2700       if (err)
2701         goto leave;
2702 
2703       /* Store the key. */
2704       if (app->app_local->cardcap.ext_lc_le && template_len > 254)
2705         exmode = 1;    /* Use extended length w/o a limit.  */
2706       else if (app->app_local->cardcap.cmd_chaining && template_len > 254)
2707         exmode = -254;
2708       else
2709         exmode = 0;
2710       err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
2711                                   template, template_len);
2712     }
2713   else
2714     {
2715       /* Build the private key template as described in section 4.3.3.6 of
2716          the OpenPGP card specs version 1.1:
2717          0xC0   <length> public exponent
2718          0xC1   <length> prime p
2719          0xC2   <length> prime q
2720       */
2721       assert (rsa_e_len <= 4);
2722       template_len = (1 + 1 + 4
2723                       + 1 + 1 + rsa_p_len
2724                       + 1 + 1 + rsa_q_len);
2725       template = tp = xtrymalloc_secure (template_len);
2726       if (!template)
2727         {
2728           err = gpg_error_from_syserror ();
2729           goto leave;
2730         }
2731       *tp++ = 0xC0;
2732       *tp++ = 4;
2733       memcpy (tp, rsa_e, rsa_e_len);
2734       if (rsa_e_len < 4)
2735         {
2736           /* Right justify E. */
2737           memmove (tp+4-rsa_e_len, tp, rsa_e_len);
2738           memset (tp, 0, 4-rsa_e_len);
2739         }
2740       tp += 4;
2741 
2742       *tp++ = 0xC1;
2743       *tp++ = rsa_p_len;
2744       memcpy (tp, rsa_p, rsa_p_len);
2745       tp += rsa_p_len;
2746 
2747       *tp++ = 0xC2;
2748       *tp++ = rsa_q_len;
2749       memcpy (tp, rsa_q, rsa_q_len);
2750       tp += rsa_q_len;
2751 
2752       assert (tp - template == template_len);
2753 
2754       /* Prepare for storing the key.  */
2755       err = verify_chv3 (app, pincb, pincb_arg);
2756       if (err)
2757         goto leave;
2758 
2759       /* Store the key. */
2760       err = iso7816_put_data (app->slot, 0,
2761                               (app->card_version > 0x0007? 0xE0:0xE9)+keyno,
2762                               template, template_len);
2763     }
2764   if (err)
2765     {
2766       log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
2767       goto leave;
2768     }
2769 
2770   err = store_fpr (app, keyno, created_at,
2771                   rsa_n, rsa_n_len, rsa_e, rsa_e_len,
2772                   fprbuf, app->card_version);
2773   if (err)
2774     goto leave;
2775 
2776 
2777  leave:
2778   xfree (template);
2779   return err;
2780 }
2781 
2782 
2783 /* Handle the GENKEY command. */
2784 static gpg_error_t
do_genkey(app_t app,ctrl_t ctrl,const char * keynostr,unsigned int flags,time_t createtime,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg)2785 do_genkey (app_t app, ctrl_t ctrl,  const char *keynostr, unsigned int flags,
2786            time_t createtime,
2787            gpg_error_t (*pincb)(void*, const char *, char **),
2788            void *pincb_arg)
2789 {
2790   int rc;
2791   char numbuf[30];
2792   unsigned char fprbuf[20];
2793   const unsigned char *keydata, *m, *e;
2794   unsigned char *buffer = NULL;
2795   size_t buflen, keydatalen, mlen, elen;
2796   time_t created_at;
2797   int keyno = atoi (keynostr);
2798   int force = (flags & 1);
2799   time_t start_at;
2800   int exmode;
2801   int le_value;
2802   unsigned int keybits;
2803 
2804   if (keyno < 1 || keyno > 3)
2805     return gpg_error (GPG_ERR_INV_ID);
2806   keyno--;
2807 
2808   /* We flush the cache to increase the traffic before a key
2809      generation.  This _might_ help a card to gather more entropy. */
2810   flush_cache (app);
2811 
2812   /* Obviously we need to remove the cached public key.  */
2813   xfree (app->app_local->pk[keyno].key);
2814   app->app_local->pk[keyno].key = NULL;
2815   app->app_local->pk[keyno].keylen = 0;
2816   app->app_local->pk[keyno].read_done = 0;
2817 
2818   /* Check whether a key already exists.  */
2819   rc = does_key_exist (app, keyno, 1, force);
2820   if (rc)
2821     return rc;
2822 
2823   /* Because we send the key parameter back via status lines we need
2824      to put a limit on the max. allowed keysize.  2048 bit will
2825      already lead to a 527 byte long status line and thus a 4096 bit
2826      key would exceed the Assuan line length limit.  */
2827   keybits = app->app_local->keyattr[keyno].n_bits;
2828   if (keybits > 3072)
2829     return gpg_error (GPG_ERR_TOO_LARGE);
2830 
2831   /* Prepare for key generation by verifying the Admin PIN.  */
2832   rc = verify_chv3 (app, pincb, pincb_arg);
2833   if (rc)
2834     goto leave;
2835 
2836   /* Test whether we will need extended length mode.  (1900 is an
2837      arbitrary length which for sure fits into a short apdu.)  */
2838   if (app->app_local->cardcap.ext_lc_le && keybits > 1900)
2839     {
2840       exmode = 1;    /* Use extended length w/o a limit.  */
2841       le_value = app->app_local->extcap.max_rsp_data;
2842       /* No need to check le_value because it comes from a 16 bit
2843          value and thus can't create an overflow on a 32 bit
2844          system.  */
2845     }
2846   else
2847     {
2848       exmode = 0;
2849       le_value = 256; /* Use legacy value. */
2850     }
2851 
2852   log_info (_("please wait while key is being generated ...\n"));
2853   start_at = time (NULL);
2854   rc = iso7816_generate_keypair
2855 /* # warning key generation temporary replaced by reading an existing key. */
2856 /*   rc = iso7816_read_public_key */
2857     (app->slot, exmode,
2858      (const unsigned char*)(keyno == 0? "\xB6" :
2859                             keyno == 1? "\xB8" : "\xA4"), 2,
2860      le_value,
2861      &buffer, &buflen);
2862   if (rc)
2863     {
2864       rc = gpg_error (GPG_ERR_CARD);
2865       log_error (_("generating key failed\n"));
2866       goto leave;
2867     }
2868   log_info (_("key generation completed (%d seconds)\n"),
2869             (int)(time (NULL) - start_at));
2870 
2871   keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
2872   if (!keydata)
2873     {
2874       rc = gpg_error (GPG_ERR_CARD);
2875       log_error (_("response does not contain the public key data\n"));
2876       goto leave;
2877     }
2878 
2879   m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
2880   if (!m)
2881     {
2882       rc = gpg_error (GPG_ERR_CARD);
2883       log_error (_("response does not contain the RSA modulus\n"));
2884       goto leave;
2885     }
2886   /* log_printhex ("RSA n:", m, mlen); */
2887   send_key_data (ctrl, "n", m, mlen);
2888 
2889   e = find_tlv (keydata, keydatalen, 0x0082, &elen);
2890   if (!e)
2891     {
2892       rc = gpg_error (GPG_ERR_CARD);
2893       log_error (_("response does not contain the RSA public exponent\n"));
2894       goto leave;
2895     }
2896   /* log_printhex ("RSA e:", e, elen); */
2897   send_key_data (ctrl, "e", e, elen);
2898 
2899   created_at = createtime? createtime : gnupg_get_time ();
2900   sprintf (numbuf, "%lu", (unsigned long)created_at);
2901   send_status_info (ctrl, "KEY-CREATED-AT",
2902                     numbuf, (size_t)strlen(numbuf), NULL, 0);
2903 
2904   rc = store_fpr (app, keyno, (u32)created_at,
2905                   m, mlen, e, elen, fprbuf, app->card_version);
2906   if (rc)
2907     goto leave;
2908   send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
2909 
2910 
2911  leave:
2912   xfree (buffer);
2913   return rc;
2914 }
2915 
2916 
2917 static unsigned long
convert_sig_counter_value(const unsigned char * value,size_t valuelen)2918 convert_sig_counter_value (const unsigned char *value, size_t valuelen)
2919 {
2920   unsigned long ul;
2921 
2922   if (valuelen == 3 )
2923     ul = (value[0] << 16) | (value[1] << 8) | value[2];
2924   else
2925     {
2926       log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
2927       ul = 0;
2928     }
2929   return ul;
2930 }
2931 
2932 static unsigned long
get_sig_counter(app_t app)2933 get_sig_counter (app_t app)
2934 {
2935   void *relptr;
2936   unsigned char *value;
2937   size_t valuelen;
2938   unsigned long ul;
2939 
2940   relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
2941   if (!relptr)
2942     return 0;
2943   ul = convert_sig_counter_value (value, valuelen);
2944   xfree (relptr);
2945   return ul;
2946 }
2947 
2948 static gpg_error_t
compare_fingerprint(app_t app,int keyno,unsigned char * sha1fpr)2949 compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
2950 {
2951   const unsigned char *fpr;
2952   unsigned char *buffer;
2953   size_t buflen, n;
2954   int rc, i;
2955 
2956   assert (keyno >= 1 && keyno <= 3);
2957 
2958   rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0, 0);
2959   if (rc)
2960     {
2961       log_error (_("error reading application data\n"));
2962       return gpg_error (GPG_ERR_GENERAL);
2963     }
2964   fpr = find_tlv (buffer, buflen, 0x00C5, &n);
2965   if (!fpr || n != 60)
2966     {
2967       xfree (buffer);
2968       log_error (_("error reading fingerprint DO\n"));
2969       return gpg_error (GPG_ERR_GENERAL);
2970     }
2971   fpr += (keyno-1)*20;
2972   for (i=0; i < 20; i++)
2973     if (sha1fpr[i] != fpr[i])
2974       {
2975         xfree (buffer);
2976         log_info (_("fingerprint on card does not match requested one\n"));
2977         return gpg_error (GPG_ERR_WRONG_SECKEY);
2978       }
2979   xfree (buffer);
2980   return 0;
2981 }
2982 
2983 
2984 /* If a fingerprint has been specified check it against the one on the
2985    card.  This allows for a meaningful error message in case the key
2986    on the card has been replaced but the shadow information known to
2987    gpg has not been updated.  If there is no fingerprint we assume
2988    that this is okay. */
2989 static gpg_error_t
check_against_given_fingerprint(app_t app,const char * fpr,int keyno)2990 check_against_given_fingerprint (app_t app, const char *fpr, int keyno)
2991 {
2992   unsigned char tmp[20];
2993   const char *s;
2994   int n;
2995 
2996   for (s=fpr, n=0; hexdigitp (s); s++, n++)
2997     ;
2998   if (n != 40)
2999     return gpg_error (GPG_ERR_INV_ID);
3000   else if (!*s)
3001     ; /* okay */
3002   else
3003     return gpg_error (GPG_ERR_INV_ID);
3004 
3005   for (s=fpr, n=0; n < 20; s += 2, n++)
3006         tmp[n] = xtoi_2 (s);
3007   return compare_fingerprint (app, keyno, tmp);
3008 }
3009 
3010 
3011 
3012 /* Compute a digital signature on INDATA which is expected to be the
3013    raw message digest. For this application the KEYIDSTR consists of
3014    the serialnumber and the fingerprint delimited by a slash.
3015 
3016    Note that this function may return the error code
3017    GPG_ERR_WRONG_CARD to indicate that the card currently present does
3018    not match the one required for the requested action (e.g. the
3019    serial number does not match).
3020 
3021    As a special feature a KEYIDSTR of "OPENPGP.3" redirects the
3022    operation to the auth command.
3023 */
3024 static gpg_error_t
do_sign(app_t app,const char * keyidstr,int hashalgo,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg,const void * indata,size_t indatalen,unsigned char ** outdata,size_t * outdatalen)3025 do_sign (app_t app, const char *keyidstr, int hashalgo,
3026          gpg_error_t (*pincb)(void*, const char *, char **),
3027          void *pincb_arg,
3028          const void *indata, size_t indatalen,
3029          unsigned char **outdata, size_t *outdatalen )
3030 {
3031   static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
3032     { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
3033       0x02, 0x01, 0x05, 0x00, 0x04, 0x14  };
3034   static unsigned char sha1_prefix[15] =   /* (1.3.14.3.2.26) */
3035     { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
3036       0x02, 0x1a, 0x05, 0x00, 0x04, 0x14  };
3037   static unsigned char sha224_prefix[19] = /* (2.16.840.1.101.3.4.2.4) */
3038     { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
3039       0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04,
3040       0x1C  };
3041   static unsigned char sha256_prefix[19] = /* (2.16.840.1.101.3.4.2.1) */
3042     { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3043       0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
3044       0x00, 0x04, 0x20  };
3045   static unsigned char sha384_prefix[19] = /* (2.16.840.1.101.3.4.2.2) */
3046     { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3047       0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
3048       0x00, 0x04, 0x30  };
3049   static unsigned char sha512_prefix[19] = /* (2.16.840.1.101.3.4.2.3) */
3050     { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
3051       0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
3052       0x00, 0x04, 0x40  };
3053   int rc;
3054   unsigned char data[19+64];
3055   size_t datalen;
3056   unsigned char tmp_sn[20]; /* Actually 16 bytes but also for the fpr. */
3057   const char *s;
3058   int n;
3059   const char *fpr = NULL;
3060   unsigned long sigcount;
3061   int use_auth = 0;
3062   int exmode, le_value;
3063 
3064   if (!keyidstr || !*keyidstr)
3065     return gpg_error (GPG_ERR_INV_VALUE);
3066 
3067   /* Strip off known prefixes.  */
3068 #define X(a,b,c,d) \
3069   if (hashalgo == GCRY_MD_ ## a                               \
3070       && (d)                                                  \
3071       && indatalen == sizeof b ## _prefix + (c)               \
3072       && !memcmp (indata, b ## _prefix, sizeof b ## _prefix)) \
3073     {                                                         \
3074       indata = (const char*)indata + sizeof b ## _prefix;     \
3075       indatalen -= sizeof b ## _prefix;                       \
3076     }
3077 
3078   if (indatalen == 20)
3079     ;  /* Assume a plain SHA-1 or RMD160 digest has been given.  */
3080   else X(SHA1,   sha1,   20, 1)
3081   else X(RMD160, rmd160, 20, 1)
3082   else X(SHA224, sha224, 28, app->app_local->extcap.is_v2)
3083   else X(SHA256, sha256, 32, app->app_local->extcap.is_v2)
3084   else X(SHA384, sha384, 48, app->app_local->extcap.is_v2)
3085   else X(SHA512, sha512, 64, app->app_local->extcap.is_v2)
3086   else if ((indatalen == 28 || indatalen == 32
3087             || indatalen == 48 || indatalen ==64)
3088            && app->app_local->extcap.is_v2)
3089     ;  /* Assume a plain SHA-3 digest has been given.  */
3090   else
3091     {
3092       log_error (_("card does not support digest algorithm %s\n"),
3093                  gcry_md_algo_name (hashalgo));
3094       /* Or the supplied digest length does not match an algorithm.  */
3095       return gpg_error (GPG_ERR_INV_VALUE);
3096     }
3097 #undef X
3098 
3099   /* Check whether an OpenPGP card of any version has been requested. */
3100   if (!strcmp (keyidstr, "OPENPGP.1"))
3101     ;
3102   else if (!strcmp (keyidstr, "OPENPGP.3"))
3103     use_auth = 1;
3104   else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3105     return gpg_error (GPG_ERR_INV_ID);
3106   else
3107     {
3108       for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3109 	;
3110       if (n != 32)
3111 	return gpg_error (GPG_ERR_INV_ID);
3112       else if (!*s)
3113 	; /* no fingerprint given: we allow this for now. */
3114       else if (*s == '/')
3115 	fpr = s + 1;
3116       else
3117 	return gpg_error (GPG_ERR_INV_ID);
3118 
3119       for (s=keyidstr, n=0; n < 16; s += 2, n++)
3120 	tmp_sn[n] = xtoi_2 (s);
3121 
3122       if (app->serialnolen != 16)
3123 	return gpg_error (GPG_ERR_INV_CARD);
3124       if (memcmp (app->serialno, tmp_sn, 16))
3125 	return gpg_error (GPG_ERR_WRONG_CARD);
3126     }
3127 
3128   /* If a fingerprint has been specified check it against the one on
3129      the card.  This is allows for a meaningful error message in case
3130      the key on the card has been replaced but the shadow information
3131      known to gpg was not updated.  If there is no fingerprint, gpg
3132      will detect a bogus signature anyway due to the
3133      verify-after-signing feature. */
3134   rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
3135   if (rc)
3136     return rc;
3137 
3138   /* Concatenate prefix and digest.  */
3139 #define X(a,b,d) \
3140   if (hashalgo == GCRY_MD_ ## a && (d) )                      \
3141     {                                                         \
3142       datalen = sizeof b ## _prefix + indatalen;              \
3143       assert (datalen <= sizeof data);                        \
3144       memcpy (data, b ## _prefix, sizeof b ## _prefix);       \
3145       memcpy (data + sizeof b ## _prefix, indata, indatalen); \
3146     }
3147 
3148   X(SHA1,   sha1,   1)
3149   else X(RMD160, rmd160, 1)
3150   else X(SHA224, sha224, app->app_local->extcap.is_v2)
3151   else X(SHA256, sha256, app->app_local->extcap.is_v2)
3152   else X(SHA384, sha384, app->app_local->extcap.is_v2)
3153   else X(SHA512, sha512, app->app_local->extcap.is_v2)
3154   else
3155     return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3156 #undef X
3157 
3158   /* Redirect to the AUTH command if asked to. */
3159   if (use_auth)
3160     {
3161       return do_auth (app, "OPENPGP.3", pincb, pincb_arg,
3162                       data, datalen,
3163                       outdata, outdatalen);
3164     }
3165 
3166   /* Show the number of signature done using this key.  */
3167   sigcount = get_sig_counter (app);
3168   log_info (_("signatures created so far: %lu\n"), sigcount);
3169 
3170   /* Check CHV if needed.  */
3171   if (!app->did_chv1 || app->force_chv1 )
3172     {
3173       char *pinvalue;
3174 
3175       rc = verify_a_chv (app, pincb, pincb_arg, 1, sigcount, &pinvalue);
3176       if (rc)
3177         return rc;
3178 
3179       app->did_chv1 = 1;
3180 
3181       /* For cards with versions < 2 we want to keep CHV1 and CHV2 in
3182          sync, thus we verify CHV2 here using the given PIN.  Cards
3183          with version2 to not have the need for a separate CHV2 and
3184          internally use just one.  Obviously we can't do that if the
3185          keypad has been used. */
3186       if (!app->did_chv2 && pinvalue && !app->app_local->extcap.is_v2)
3187         {
3188           rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
3189           if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
3190             rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
3191           if (rc)
3192             {
3193               log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
3194               xfree (pinvalue);
3195               flush_cache_after_error (app);
3196               return rc;
3197             }
3198           app->did_chv2 = 1;
3199         }
3200       xfree (pinvalue);
3201     }
3202 
3203 
3204   if (app->app_local->cardcap.ext_lc_le)
3205     {
3206       exmode = 1;    /* Use extended length.  */
3207       le_value = app->app_local->extcap.max_rsp_data;
3208     }
3209   else
3210     {
3211       exmode = 0;
3212       le_value = 0;
3213     }
3214   rc = iso7816_compute_ds (app->slot, exmode, data, datalen, le_value,
3215                            outdata, outdatalen);
3216   return rc;
3217 }
3218 
3219 /* Compute a digital signature using the INTERNAL AUTHENTICATE command
3220    on INDATA which is expected to be the raw message digest. For this
3221    application the KEYIDSTR consists of the serialnumber and the
3222    fingerprint delimited by a slash.  Optionally the id OPENPGP.3 may
3223    be given.
3224 
3225    Note that this function may return the error code
3226    GPG_ERR_WRONG_CARD to indicate that the card currently present does
3227    not match the one required for the requested action (e.g. the
3228    serial number does not match). */
3229 static gpg_error_t
do_auth(app_t app,const char * keyidstr,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg,const void * indata,size_t indatalen,unsigned char ** outdata,size_t * outdatalen)3230 do_auth (app_t app, const char *keyidstr,
3231          gpg_error_t (*pincb)(void*, const char *, char **),
3232          void *pincb_arg,
3233          const void *indata, size_t indatalen,
3234          unsigned char **outdata, size_t *outdatalen )
3235 {
3236   int rc;
3237   unsigned char tmp_sn[20]; /* Actually 16 but we use it also for the fpr. */
3238   const char *s;
3239   int n;
3240   const char *fpr = NULL;
3241 
3242   if (!keyidstr || !*keyidstr)
3243     return gpg_error (GPG_ERR_INV_VALUE);
3244   if (indatalen > 101) /* For a 2048 bit key. */
3245     return gpg_error (GPG_ERR_INV_VALUE);
3246 
3247   /* Check whether an OpenPGP card of any version has been requested. */
3248   if (!strcmp (keyidstr, "OPENPGP.3"))
3249     ;
3250   else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3251     return gpg_error (GPG_ERR_INV_ID);
3252   else
3253     {
3254       for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3255         ;
3256       if (n != 32)
3257         return gpg_error (GPG_ERR_INV_ID);
3258       else if (!*s)
3259         ; /* no fingerprint given: we allow this for now. */
3260       else if (*s == '/')
3261         fpr = s + 1;
3262       else
3263         return gpg_error (GPG_ERR_INV_ID);
3264 
3265       for (s=keyidstr, n=0; n < 16; s += 2, n++)
3266         tmp_sn[n] = xtoi_2 (s);
3267 
3268       if (app->serialnolen != 16)
3269         return gpg_error (GPG_ERR_INV_CARD);
3270       if (memcmp (app->serialno, tmp_sn, 16))
3271         return gpg_error (GPG_ERR_WRONG_CARD);
3272     }
3273 
3274   /* If a fingerprint has been specified check it against the one on
3275      the card.  This is allows for a meaningful error message in case
3276      the key on the card has been replaced but the shadow information
3277      known to gpg was not updated.  If there is no fingerprint, gpg
3278      will detect a bogus signature anyway due to the
3279      verify-after-signing feature. */
3280   rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
3281   if (rc)
3282     return rc;
3283 
3284   rc = verify_chv2 (app, pincb, pincb_arg);
3285   if (!rc)
3286     {
3287       int exmode, le_value;
3288 
3289       if (app->app_local->cardcap.ext_lc_le)
3290         {
3291           exmode = 1;    /* Use extended length.  */
3292           le_value = app->app_local->extcap.max_rsp_data;
3293         }
3294       else
3295         {
3296           exmode = 0;
3297           le_value = 0;
3298         }
3299       rc = iso7816_internal_authenticate (app->slot, exmode,
3300                                           indata, indatalen, le_value,
3301                                           outdata, outdatalen);
3302     }
3303   return rc;
3304 }
3305 
3306 
3307 static gpg_error_t
do_decipher(app_t app,const char * keyidstr,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg,const void * indata,size_t indatalen,unsigned char ** outdata,size_t * outdatalen)3308 do_decipher (app_t app, const char *keyidstr,
3309              gpg_error_t (*pincb)(void*, const char *, char **),
3310              void *pincb_arg,
3311              const void *indata, size_t indatalen,
3312              unsigned char **outdata, size_t *outdatalen )
3313 {
3314   int rc;
3315   unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
3316   const char *s;
3317   int n;
3318   const char *fpr = NULL;
3319   int exmode, le_value;
3320 
3321   if (!keyidstr || !*keyidstr || !indatalen)
3322     return gpg_error (GPG_ERR_INV_VALUE);
3323 
3324   /* Check whether an OpenPGP card of any version has been requested. */
3325   if (!strcmp (keyidstr, "OPENPGP.2"))
3326     ;
3327   else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3328     return gpg_error (GPG_ERR_INV_ID);
3329   else
3330     {
3331       for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3332 	;
3333       if (n != 32)
3334 	return gpg_error (GPG_ERR_INV_ID);
3335       else if (!*s)
3336 	; /* no fingerprint given: we allow this for now. */
3337       else if (*s == '/')
3338 	fpr = s + 1;
3339       else
3340 	return gpg_error (GPG_ERR_INV_ID);
3341 
3342       for (s=keyidstr, n=0; n < 16; s += 2, n++)
3343 	tmp_sn[n] = xtoi_2 (s);
3344 
3345       if (app->serialnolen != 16)
3346 	return gpg_error (GPG_ERR_INV_CARD);
3347       if (memcmp (app->serialno, tmp_sn, 16))
3348 	return gpg_error (GPG_ERR_WRONG_CARD);
3349     }
3350 
3351   /* If a fingerprint has been specified check it against the one on
3352      the card.  This is allows for a meaningful error message in case
3353      the key on the card has been replaced but the shadow information
3354      known to gpg was not updated.  If there is no fingerprint, the
3355      decryption won't produce the right plaintext anyway. */
3356   rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0;
3357   if (rc)
3358     return rc;
3359 
3360   rc = verify_chv2 (app, pincb, pincb_arg);
3361   if (!rc)
3362     {
3363       size_t fixuplen;
3364       unsigned char *fixbuf = NULL;
3365       int padind = 0;
3366 
3367       /* We might encounter a couple of leading zeroes in the
3368          cryptogram.  Due to internal use of MPIs thease leading
3369          zeroes are stripped.  However the OpenPGP card expects
3370          exactly 128 bytes for the cryptogram (for a 1k key).  Thus we
3371          need to fix it up.  We do this for up to 16 leading zero
3372          bytes; a cryptogram with more than this is with a very high
3373          probability anyway broken.  */
3374       if (indatalen >= (128-16) && indatalen < 128)      /* 1024 bit key.  */
3375         fixuplen = 128 - indatalen;
3376       else if (indatalen >= (192-16) && indatalen < 192) /* 1536 bit key.  */
3377         fixuplen = 192 - indatalen;
3378       else if (indatalen >= (256-16) && indatalen < 256) /* 2048 bit key.  */
3379         fixuplen = 256 - indatalen;
3380       else if (indatalen >= (384-16) && indatalen < 384) /* 3072 bit key.  */
3381         fixuplen = 384 - indatalen;
3382       else
3383         fixuplen = 0;
3384 
3385       if (fixuplen)
3386         {
3387           /* While we have to prepend stuff anyway, we can also
3388              include the padding byte here so that iso1816_decipher
3389              does not need to do another data mangling.  */
3390           fixuplen++;
3391 
3392           fixbuf = xtrymalloc (fixuplen + indatalen);
3393           if (!fixbuf)
3394             return gpg_error_from_syserror ();
3395 
3396           memset (fixbuf, 0, fixuplen);
3397           memcpy (fixbuf+fixuplen, indata, indatalen);
3398           indata = fixbuf;
3399           indatalen = fixuplen + indatalen;
3400           padind = -1; /* Already padded.  */
3401         }
3402 
3403       if (app->app_local->cardcap.ext_lc_le && indatalen > 254 )
3404         {
3405           exmode = 1;    /* Extended length w/o a limit.  */
3406           le_value = app->app_local->extcap.max_rsp_data;
3407         }
3408       else if (app->app_local->cardcap.cmd_chaining && indatalen > 254)
3409         {
3410           exmode = -254; /* Command chaining with max. 254 bytes.  */
3411           le_value = 0;
3412         }
3413       else
3414         exmode = le_value = 0;
3415 
3416       rc = iso7816_decipher (app->slot, exmode,
3417                              indata, indatalen, le_value, padind,
3418                              outdata, outdatalen);
3419       xfree (fixbuf);
3420     }
3421 
3422   return rc;
3423 }
3424 
3425 
3426 /* Perform a simple verify operation for CHV1 and CHV2, so that
3427    further operations won't ask for CHV2 and it is possible to do a
3428    cheap check on the PIN: If there is something wrong with the PIN
3429    entry system, only the regular CHV will get blocked and not the
3430    dangerous CHV3.  KEYIDSTR is the usual card's serial number; an
3431    optional fingerprint part will be ignored.
3432 
3433    There is a special mode if the keyidstr is "<serialno>[CHV3]" with
3434    the "[CHV3]" being a literal string:  The Admin Pin is checked if
3435    and only if the retry counter is still at 3. */
3436 static gpg_error_t
do_check_pin(app_t app,const char * keyidstr,gpg_error_t (* pincb)(void *,const char *,char **),void * pincb_arg)3437 do_check_pin (app_t app, const char *keyidstr,
3438               gpg_error_t (*pincb)(void*, const char *, char **),
3439               void *pincb_arg)
3440 {
3441   unsigned char tmp_sn[20];
3442   const char *s;
3443   int n;
3444   int admin_pin = 0;
3445 
3446   if (!keyidstr || !*keyidstr)
3447     return gpg_error (GPG_ERR_INV_VALUE);
3448 
3449   /* Check whether an OpenPGP card of any version has been requested. */
3450   if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
3451     return gpg_error (GPG_ERR_INV_ID);
3452 
3453   for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
3454     ;
3455   if (n != 32)
3456     return gpg_error (GPG_ERR_INV_ID);
3457   else if (!*s)
3458     ; /* No fingerprint given: we allow this for now. */
3459   else if (*s == '/')
3460     ; /* We ignore a fingerprint. */
3461   else if (!strcmp (s, "[CHV3]") )
3462     admin_pin = 1;
3463   else
3464     return gpg_error (GPG_ERR_INV_ID);
3465 
3466   for (s=keyidstr, n=0; n < 16; s += 2, n++)
3467     tmp_sn[n] = xtoi_2 (s);
3468 
3469   if (app->serialnolen != 16)
3470     return gpg_error (GPG_ERR_INV_CARD);
3471   if (memcmp (app->serialno, tmp_sn, 16))
3472     return gpg_error (GPG_ERR_WRONG_CARD);
3473 
3474   /* Yes, there is a race conditions: The user might pull the card
3475      right here and we won't notice that.  However this is not a
3476      problem and the check above is merely for a graceful failure
3477      between operations. */
3478 
3479   if (admin_pin)
3480     {
3481       void *relptr;
3482       unsigned char *value;
3483       size_t valuelen;
3484       int count;
3485 
3486       relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
3487       if (!relptr || valuelen < 7)
3488         {
3489           log_error (_("error retrieving CHV status from card\n"));
3490           xfree (relptr);
3491           return gpg_error (GPG_ERR_CARD);
3492         }
3493       count = value[6];
3494       xfree (relptr);
3495 
3496       if (!count)
3497         {
3498           log_info (_("card is permanently locked!\n"));
3499           return gpg_error (GPG_ERR_BAD_PIN);
3500         }
3501       else if (count < 3)
3502         {
3503           log_info (_("verification of Admin PIN is currently prohibited "
3504                       "through this command\n"));
3505           return gpg_error (GPG_ERR_GENERAL);
3506         }
3507 
3508       app->did_chv3 = 0; /* Force verification.  */
3509       return verify_chv3 (app, pincb, pincb_arg);
3510     }
3511   else
3512     return verify_chv2 (app, pincb, pincb_arg);
3513 }
3514 
3515 
3516 /* Show information about card capabilities.  */
3517 static void
show_caps(struct app_local_s * s)3518 show_caps (struct app_local_s *s)
3519 {
3520   log_info ("Version-2 ......: %s\n", s->extcap.is_v2? "yes":"no");
3521   log_info ("Get-Challenge ..: %s", s->extcap.get_challenge? "yes":"no");
3522   if (s->extcap.get_challenge)
3523     log_printf (" (%u bytes max)", s->extcap.max_get_challenge);
3524   log_info ("Key-Import .....: %s\n", s->extcap.key_import? "yes":"no");
3525   log_info ("Change-Force-PW1: %s\n", s->extcap.change_force_chv? "yes":"no");
3526   log_info ("Private-DOs ....: %s\n", s->extcap.private_dos? "yes":"no");
3527   log_info ("Algo-Attr-Change: %s\n", s->extcap.algo_attr_change? "yes":"no");
3528   log_info ("SM-Support .....: %s", s->extcap.sm_supported? "yes":"no");
3529   if (s->extcap.sm_supported)
3530     log_printf (" (%s)", s->extcap.sm_aes128? "AES-128":"3DES");
3531   log_info ("Max-Cert3-Len ..: %u\n", s->extcap.max_certlen_3);
3532   log_info ("Max-Cmd-Data ...: %u\n", s->extcap.max_cmd_data);
3533   log_info ("Max-Rsp-Data ...: %u\n", s->extcap.max_rsp_data);
3534   log_info ("Cmd-Chaining ...: %s\n", s->cardcap.cmd_chaining?"yes":"no");
3535   log_info ("Ext-Lc-Le ......: %s\n", s->cardcap.ext_lc_le?"yes":"no");
3536   log_info ("Status Indicator: %02X\n", s->status_indicator);
3537 
3538   log_info ("GnuPG-No-Sync ..: %s\n",  s->flags.no_sync? "yes":"no");
3539   log_info ("GnuPG-Def-PW2 ..: %s\n",  s->flags.def_chv2? "yes":"no");
3540 }
3541 
3542 
3543 /* Parse the historical bytes in BUFFER of BUFLEN and store them in
3544    APPLOC.  */
3545 static void
parse_historical(struct app_local_s * apploc,const unsigned char * buffer,size_t buflen)3546 parse_historical (struct app_local_s *apploc,
3547                   const unsigned char * buffer, size_t buflen)
3548 {
3549   /* Example buffer: 00 31 C5 73 C0 01 80 00 90 00  */
3550   if (buflen < 4)
3551     {
3552       log_error ("warning: historical bytes are too short\n");
3553       return; /* Too short.  */
3554     }
3555   if (*buffer)
3556     {
3557       log_error ("warning: bad category indicator in historical bytes\n");
3558       return;
3559     }
3560 
3561   /* Skip category indicator.  */
3562   buffer++;
3563   buflen--;
3564 
3565   /* Get the status indicator.  */
3566   apploc->status_indicator = buffer[buflen-3];
3567   buflen -= 3;
3568 
3569   /* Parse the compact TLV.  */
3570   while (buflen)
3571     {
3572       unsigned int tag = (*buffer & 0xf0) >> 4;
3573       unsigned int len = (*buffer & 0x0f);
3574       if (len+1 > buflen)
3575         {
3576           log_error ("warning: bad Compact-TLV in historical bytes\n");
3577           return; /* Error.  */
3578         }
3579       buffer++;
3580       buflen--;
3581       if (tag == 7 && len == 3)
3582         {
3583           /* Card capabilities.  */
3584           apploc->cardcap.cmd_chaining = !!(buffer[2] & 0x80);
3585           apploc->cardcap.ext_lc_le    = !!(buffer[2] & 0x40);
3586         }
3587       buffer += len;
3588       buflen -= len;
3589     }
3590 }
3591 
3592 
3593 /* Parse and optionally show the algorithm attributes for KEYNO.
3594    KEYNO must be in the range 0..2.  */
3595 static void
parse_algorithm_attribute(app_t app,int keyno)3596 parse_algorithm_attribute (app_t app, int keyno)
3597 {
3598   unsigned char *buffer;
3599   size_t buflen;
3600   void *relptr;
3601   const char desc[3][5] = {"sign", "encr", "auth"};
3602 
3603   assert (keyno >=0 && keyno <= 2);
3604 
3605   app->app_local->keyattr[keyno].n_bits = 0;
3606 
3607   relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL);
3608   if (!relptr)
3609     {
3610       log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
3611       return;
3612     }
3613   if (buflen < 1)
3614     {
3615       log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
3616       xfree (relptr);
3617       return;
3618     }
3619 
3620   if (opt.verbose)
3621     log_info ("Key-Attr-%s ..: ", desc[keyno]);
3622   if (*buffer == 1 && (buflen == 5 || buflen == 6))
3623     {
3624       app->app_local->keyattr[keyno].n_bits = (buffer[1]<<8 | buffer[2]);
3625       app->app_local->keyattr[keyno].e_bits = (buffer[3]<<8 | buffer[4]);
3626       app->app_local->keyattr[keyno].format = 0;
3627       if (buflen < 6)
3628         app->app_local->keyattr[keyno].format = RSA_STD;
3629       else
3630         app->app_local->keyattr[keyno].format = (buffer[5] == 0? RSA_STD   :
3631                                                  buffer[5] == 1? RSA_STD_N :
3632                                                  buffer[5] == 2? RSA_CRT   :
3633                                                  buffer[5] == 3? RSA_CRT_N :
3634                                                  RSA_UNKNOWN_FMT);
3635 
3636       if (opt.verbose)
3637         log_printf
3638           ("RSA, n=%u, e=%u, fmt=%s\n",
3639            app->app_local->keyattr[keyno].n_bits,
3640            app->app_local->keyattr[keyno].e_bits,
3641            app->app_local->keyattr[keyno].format == RSA_STD?  "std"  :
3642            app->app_local->keyattr[keyno].format == RSA_STD_N?"std+n":
3643            app->app_local->keyattr[keyno].format == RSA_CRT?  "crt"  :
3644            app->app_local->keyattr[keyno].format == RSA_CRT_N?"crt+n":"?");
3645     }
3646   else if (opt.verbose)
3647     log_printhex ("", buffer, buflen);
3648 
3649   xfree (relptr);
3650 }
3651 
3652 /* Select the OpenPGP application on the card in SLOT.  This function
3653    must be used before any other OpenPGP application functions. */
3654 gpg_error_t
app_select_openpgp(app_t app)3655 app_select_openpgp (app_t app)
3656 {
3657   static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
3658   int slot = app->slot;
3659   int rc;
3660   unsigned char *buffer;
3661   size_t buflen;
3662   void *relptr;
3663 
3664   /* Note that the card can't cope with P2=0xCO, thus we need to pass a
3665      special flag value. */
3666   rc = iso7816_select_application (slot, aid, sizeof aid, 0x0001);
3667   if (!rc)
3668     {
3669       unsigned int manufacturer;
3670 
3671       app->apptype = "OPENPGP";
3672 
3673       app->did_chv1 = 0;
3674       app->did_chv2 = 0;
3675       app->did_chv3 = 0;
3676       app->app_local = NULL;
3677 
3678       /* The OpenPGP card returns the serial number as part of the
3679          AID; because we prefer to use OpenPGP serial numbers, we
3680          replace a possibly already set one from a EF.GDO with this
3681          one.  Note, that for current OpenPGP cards, no EF.GDO exists
3682          and thus it won't matter at all. */
3683       rc = iso7816_get_data (slot, 0, 0x004F, &buffer, &buflen);
3684       if (rc)
3685         goto leave;
3686       if (opt.verbose)
3687         {
3688           log_info ("AID: ");
3689           log_printhex ("", buffer, buflen);
3690         }
3691 
3692       app->card_version = buffer[6] << 8;
3693       app->card_version |= buffer[7];
3694       manufacturer = (buffer[8]<<8 | buffer[9]);
3695 
3696       xfree (app->serialno);
3697       app->serialno = buffer;
3698       app->serialnolen = buflen;
3699       buffer = NULL;
3700       app->app_local = xtrycalloc (1, sizeof *app->app_local);
3701       if (!app->app_local)
3702         {
3703           rc = gpg_error (gpg_err_code_from_errno (errno));
3704           goto leave;
3705         }
3706 
3707       if (app->card_version >= 0x0200)
3708         app->app_local->extcap.is_v2 = 1;
3709 
3710 
3711       /* Read the historical bytes.  */
3712       relptr = get_one_do (app, 0x5f52, &buffer, &buflen, NULL);
3713       if (relptr)
3714         {
3715           if (opt.verbose)
3716             {
3717               log_info ("Historical Bytes: ");
3718               log_printhex ("", buffer, buflen);
3719             }
3720           parse_historical (app->app_local, buffer, buflen);
3721           xfree (relptr);
3722         }
3723 
3724       /* Read the force-chv1 flag.  */
3725       relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL);
3726       if (!relptr)
3727         {
3728           log_error (_("can't access %s - invalid OpenPGP card?\n"),
3729                      "CHV Status Bytes");
3730           goto leave;
3731         }
3732       app->force_chv1 = (buflen && *buffer == 0);
3733       xfree (relptr);
3734 
3735       /* Read the extended capabilities.  */
3736       relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL);
3737       if (!relptr)
3738         {
3739           log_error (_("can't access %s - invalid OpenPGP card?\n"),
3740                      "Extended Capability Flags" );
3741           goto leave;
3742         }
3743       if (buflen)
3744         {
3745           app->app_local->extcap.sm_supported     = !!(*buffer & 0x80);
3746           app->app_local->extcap.get_challenge    = !!(*buffer & 0x40);
3747           app->app_local->extcap.key_import       = !!(*buffer & 0x20);
3748           app->app_local->extcap.change_force_chv = !!(*buffer & 0x10);
3749           app->app_local->extcap.private_dos      = !!(*buffer & 0x08);
3750           app->app_local->extcap.algo_attr_change = !!(*buffer & 0x04);
3751         }
3752       if (buflen >= 10)
3753         {
3754           /* Available with v2 cards.  */
3755           app->app_local->extcap.sm_aes128     = (buffer[1] == 1);
3756           app->app_local->extcap.max_get_challenge
3757                                                = (buffer[2] << 8 | buffer[3]);
3758           app->app_local->extcap.max_certlen_3 = (buffer[4] << 8 | buffer[5]);
3759           app->app_local->extcap.max_cmd_data  = (buffer[6] << 8 | buffer[7]);
3760           app->app_local->extcap.max_rsp_data  = (buffer[8] << 8 | buffer[9]);
3761         }
3762       xfree (relptr);
3763 
3764       /* Some of the first cards accidently don't set the
3765          CHANGE_FORCE_CHV bit but allow it anyway. */
3766       if (app->card_version <= 0x0100 && manufacturer == 1)
3767         app->app_local->extcap.change_force_chv = 1;
3768 
3769       parse_login_data (app);
3770 
3771       if (opt.verbose)
3772         show_caps (app->app_local);
3773 
3774       parse_algorithm_attribute (app, 0);
3775       parse_algorithm_attribute (app, 1);
3776       parse_algorithm_attribute (app, 2);
3777 
3778       if (opt.verbose > 1)
3779         dump_all_do (slot);
3780 
3781       app->fnc.deinit = do_deinit;
3782       app->fnc.learn_status = do_learn_status;
3783       app->fnc.readcert = do_readcert;
3784       app->fnc.readkey = do_readkey;
3785       app->fnc.getattr = do_getattr;
3786       app->fnc.setattr = do_setattr;
3787       app->fnc.writecert = do_writecert;
3788       app->fnc.writekey = do_writekey;
3789       app->fnc.genkey = do_genkey;
3790       app->fnc.sign = do_sign;
3791       app->fnc.auth = do_auth;
3792       app->fnc.decipher = do_decipher;
3793       app->fnc.change_pin = do_change_pin;
3794       app->fnc.check_pin = do_check_pin;
3795    }
3796 
3797 leave:
3798   if (rc)
3799     do_deinit (app);
3800   return rc;
3801 }
3802 
3803 
3804 
3805