Imported Upstream version 2.2.37
[platform/upstream/gpg2.git] / scd / app-p15.c
1 /* app-p15.c - The pkcs#15 card application.
2  *      Copyright (C) 2005 Free Software Foundation, Inc.
3  *      Copyright (C) 2020, 2021 g10 Code GmbH
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 <https://www.gnu.org/licenses/>.
19  * SPDX-License-Identifier: GPL-3.0-or-later
20  */
21
22 /* Information pertaining to the BELPIC developer card samples:
23
24        Unblock PUK: "222222111111"
25        Reset PIN:   "333333111111")
26
27    e.g. the APDUs 00:20:00:02:08:2C:33:33:33:11:11:11:FF
28               and 00:24:01:01:08:24:12:34:FF:FF:FF:FF:FF
29    should change the PIN into 1234.
30 */
31
32 #include <config.h>
33 #include <errno.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <time.h>
38
39 #include "scdaemon.h"
40
41 #include "iso7816.h"
42 #include "../common/i18n.h"
43 #include "../common/tlv.h"
44 #include "../common/host2net.h"
45 #include "../common/openpgpdefs.h"
46 #include "apdu.h" /* fixme: we should move the card detection to a
47                      separate file */
48
49
50 static const char oid_kp_codeSigning[]    = "1.3.6.1.5.5.7.3.3";
51 static const char oid_kp_timeStamping[]   = "1.3.6.1.5.5.7.3.8";
52 static const char oid_kp_ocspSigning[]    = "1.3.6.1.5.5.7.3.9";
53 static const char oid_kp_ms_documentSigning[] = "1.3.6.1.4.1.311.10.3.12";
54 static const char oid_kp_ms_old_documentSigning[] = "1.3.6.1.4.1.311.3.10.3.12";
55
56 static const char oid_kp_emailProtection[]= "1.3.6.1.5.5.7.3.4";
57
58 static const char oid_kp_serverAuth[]     = "1.3.6.1.5.5.7.3.1";
59 static const char oid_kp_clientAuth[]     = "1.3.6.1.5.5.7.3.2";
60 static const char oid_kp_ms_smartcardLogon[] = "1.3.6.1.4.1.311.20.2.2";
61
62 static const char oid_kp_anyExtendedKeyUsage[] = "2.5.29.37.0";
63
64 static const char oid_kp_gpgUsageCert[] = "1.3.6.1.4.1.11591.2.6.1";
65 static const char oid_kp_gpgUsageSign[] = "1.3.6.1.4.1.11591.2.6.2";
66 static const char oid_kp_gpgUsageEncr[] = "1.3.6.1.4.1.11591.2.6.3";
67 static const char oid_kp_gpgUsageAuth[] = "1.3.6.1.4.1.11591.2.6.4";
68
69 /* Types of cards we know and which needs special treatment. */
70 typedef enum
71   {
72     CARD_TYPE_UNKNOWN,
73     CARD_TYPE_TCOS,
74     CARD_TYPE_MICARDO,
75     CARD_TYPE_CARDOS_50,
76     CARD_TYPE_CARDOS_53,
77     CARD_TYPE_AET,     /* A.E.T. Europe JCOP card.  */
78     CARD_TYPE_BELPIC   /* Belgian eID card specs. */
79   }
80 card_type_t;
81
82 /* The OS of card as specified by card_type_t is not always
83  * sufficient.  Thus we also distinguish the actual product build upon
84  * the given OS.  */
85 typedef enum
86   {
87     CARD_PRODUCT_UNKNOWN,
88     CARD_PRODUCT_RSCS,     /* Rohde&Schwarz Cybersecurity       */
89     CARD_PRODUCT_DTRUST,   /* D-Trust GmbH (bundesdruckerei.de) */
90     CARD_PRODUCT_GENUA     /* GeNUA mbH                         */
91   }
92 card_product_t;
93
94
95 /* A list card types with ATRs noticed with these cards. */
96 #define X(a) ((unsigned char const *)(a))
97 static struct
98 {
99   size_t atrlen;
100   unsigned char const *atr;
101   card_type_t type;
102 } card_atr_list[] = {
103   { 19, X("\x3B\xBA\x13\x00\x81\x31\x86\x5D\x00\x64\x05\x0A\x02\x01\x31\x80"
104           "\x90\x00\x8B"),
105     CARD_TYPE_TCOS },  /* SLE44 */
106   { 19, X("\x3B\xBA\x14\x00\x81\x31\x86\x5D\x00\x64\x05\x14\x02\x02\x31\x80"
107           "\x90\x00\x91"),
108     CARD_TYPE_TCOS }, /* SLE66S */
109   { 19, X("\x3B\xBA\x96\x00\x81\x31\x86\x5D\x00\x64\x05\x60\x02\x03\x31\x80"
110           "\x90\x00\x66"),
111     CARD_TYPE_TCOS }, /* SLE66P */
112   { 27, X("\x3B\xFF\x94\x00\xFF\x80\xB1\xFE\x45\x1F\x03\x00\x68\xD2\x76\x00"
113           "\x00\x28\xFF\x05\x1E\x31\x80\x00\x90\x00\x23"),
114     CARD_TYPE_MICARDO }, /* German BMI card */
115   { 19, X("\x3B\x6F\x00\xFF\x00\x68\xD2\x76\x00\x00\x28\xFF\x05\x1E\x31\x80"
116           "\x00\x90\x00"),
117     CARD_TYPE_MICARDO }, /* German BMI card (ATR due to reader problem) */
118   { 26, X("\x3B\xFE\x94\x00\xFF\x80\xB1\xFA\x45\x1F\x03\x45\x73\x74\x45\x49"
119           "\x44\x20\x76\x65\x72\x20\x31\x2E\x30\x43"),
120     CARD_TYPE_MICARDO }, /* EstEID (Estonian Big Brother card) */
121   { 11, X("\x3b\xd2\x18\x00\x81\x31\xfe\x58\xc9\x01\x14"),
122     CARD_TYPE_CARDOS_50 }, /* CardOS 5.0 */
123   { 11, X("\x3b\xd2\x18\x00\x81\x31\xfe\x58\xc9\x03\x16"),
124     CARD_TYPE_CARDOS_53 }, /* CardOS 5.3 */
125   { 24, X("\x3b\xfe\x18\x00\x00\x80\x31\xfe\x45\x53\x43\x45"
126           "\x36\x30\x2d\x43\x44\x30\x38\x31\x2d\x6e\x46\xa9"),
127     CARD_TYPE_AET },
128   { 0 }
129 };
130 #undef X
131
132
133 /* Macro to test for CardOS 5.0 and 5.3.  */
134 #define IS_CARDOS_5(a) ((a)->app_local->card_type == CARD_TYPE_CARDOS_50 \
135                         || (a)->app_local->card_type == CARD_TYPE_CARDOS_53)
136
137 /* The default PKCS-15 home DF */
138 #define DEFAULT_HOME_DF 0x5015
139
140 /* The AID of PKCS15. */
141 static char const pkcs15_aid[] = { 0xA0, 0, 0, 0, 0x63,
142                                    0x50, 0x4B, 0x43, 0x53, 0x2D, 0x31, 0x35 };
143
144 /* The Belgian eID variant - they didn't understood why a shared AID
145    is useful for a standard.  Oh well. */
146 static char const pkcs15be_aid[] = { 0xA0, 0, 0, 0x01, 0x77,
147                                    0x50, 0x4B, 0x43, 0x53, 0x2D, 0x31, 0x35 };
148
149
150 /* The PIN types as defined in pkcs#15 v1.1 */
151 typedef enum
152   {
153     PIN_TYPE_BCD = 0,
154     PIN_TYPE_ASCII_NUMERIC = 1,
155     PIN_TYPE_UTF8 = 2,
156     PIN_TYPE_HALF_NIBBLE_BCD = 3,
157     PIN_TYPE_ISO9564_1 = 4
158   } pin_type_t;
159
160 /* The AuthenticationTypes as defined in pkcs#15 v1.1 (6.8.1) */
161 typedef enum
162   {
163     AUTH_TYPE_PIN = -1,
164     AUTH_TYPE_BIOMETRIC = 0,
165     AUTH_TYPE_AUTHKEY = 1,
166     AUTH_TYPE_EXTERNAL = 2,
167   } auth_type_t;
168
169 /* A bit array with for the key usage flags from the
170    commonKeyAttributes. */
171 struct keyusage_flags_s
172 {
173     unsigned int encrypt: 1;
174     unsigned int decrypt: 1;
175     unsigned int sign: 1;
176     unsigned int sign_recover: 1;
177     unsigned int wrap: 1;
178     unsigned int unwrap: 1;
179     unsigned int verify: 1;
180     unsigned int verify_recover: 1;
181     unsigned int derive: 1;
182     unsigned int non_repudiation: 1;
183 };
184 typedef struct keyusage_flags_s keyusage_flags_t;
185
186
187 /* A bit array with for the key access flags from the
188    commonKeyAttributes. */
189 struct keyaccess_flags_s
190 {
191   unsigned int any:1;    /* Any access flag set.  */
192   unsigned int sensitive:1;
193   unsigned int extractable:1;
194   unsigned int always_sensitive:1;
195   unsigned int never_extractable:1;
196   unsigned int local:1;
197 };
198 typedef struct keyaccess_flags_s keyaccess_flags_t;
199
200
201 /* A bit array with for the gpg usage flags.  */
202 struct gpgusage_flags_s
203 {
204   unsigned int any:1;    /* Any of the next flags are set.  */
205   unsigned int cert:1;   /* 1.3.6.1.4.1.11591.2.6.1 */
206   unsigned int sign:1;   /* 1.3.6.1.4.1.11591.2.6.2 */
207   unsigned int encr:1;   /* 1.3.6.1.4.1.11591.2.6.3 */
208   unsigned int auth:1;   /* 1.3.6.1.4.1.11591.2.6.4 */
209 };
210 typedef struct gpgusage_flags_s gpgusage_flags_t;
211
212
213 /* This is an object to store information about a Certificate
214    Directory File (CDF) in a format suitable for further processing by
215    us. To keep memory management, simple we use a linked list of
216    items; i.e. one such object represents one certificate and the list
217    the entire CDF. */
218 struct cdf_object_s
219 {
220   /* Link to next item when used in a linked list. */
221   struct cdf_object_s *next;
222
223   /* Flags to indicate whether fields are valid.  */
224   unsigned int have_off:1;
225
226   /* Length and allocated buffer with the Id of this object.
227    * This field is used for X.509 in PKCS#11 to make it easier to
228    * match a private key with a certificate.  */
229   size_t objidlen;
230   unsigned char *objid;
231
232   /* Length and allocated buffer with the authId of this object or
233      NULL if no authID is known. */
234   size_t authidlen;
235   unsigned char *authid;
236
237   /* NULL or the malloced label of this object.  */
238   char *label;
239
240   /* To avoid reading and parsing a certificate more than once, we
241    * cache the ksba object.  */
242   ksba_cert_t cert;
243
244   /* The offset and length of the object.  They are only valid if
245      HAVE_OFF is true and set to 0 if HAVE_OFF is false. */
246   unsigned long off, len;
247
248   /* The length of the path as given in the CDF and the path itself.
249      path[0] is the top DF (usually 0x3f00). The path will never be
250      empty. */
251   size_t pathlen;
252   unsigned short path[1];
253 };
254 typedef struct cdf_object_s *cdf_object_t;
255
256
257 /* This is an object to store information about a Private Key
258    Directory File (PrKDF) in a format suitable for further processing
259    by us. To keep memory management, simple we use a linked list of
260    items; i.e. one such object represents one certificate and the list
261    the entire PrKDF. */
262 struct prkdf_object_s
263 {
264   /* Link to next item when used in a linked list. */
265   struct prkdf_object_s *next;
266
267   /* Flags to indicate whether fields are valid.  */
268   unsigned int keygrip_valid:1;
269   unsigned int key_reference_valid:1;
270   unsigned int have_off:1;
271   unsigned int have_keytime:1;
272
273   /* Flag indicating that the corresponding PIN has already been
274    * verified.  Note that for cards which are able to return the
275    * verification stus, this flag is not used.  */
276   unsigned int pin_verified:1;
277
278   /* PKCS#15 info whether this is an EC key.  Default is RSA.  Note
279    * that there is also a KEYALGO field which is derived from the
280    * publick key via Libgcrypt.  */
281   unsigned int is_ecc:1;
282
283   /* The key's usage flags. */
284   keyusage_flags_t usageflags;
285
286   /* The key's access flags. */
287   keyaccess_flags_t accessflags;
288
289   /* Extended key usage flags.  Only used if .valid is set.  This
290    * information is computed from an associated certificate15.  */
291   struct {
292     unsigned int valid:1;
293     unsigned int sign:1;
294     unsigned int encr:1;
295     unsigned int auth:1;
296   } extusage;
297
298   /* OpenPGP key features for this key.  This is taken from special
299    * extended key usage flags different from those tracked in EXTUSAGE
300    * above.  There is also no valid flag as in EXTUSAGE.  */
301   gpgusage_flags_t gpgusage;
302
303   /* The keygrip of the key.  This is used as a cache.  */
304   char keygrip[2*KEYGRIP_LEN+1];
305
306   /* A malloced algorithm string or NULL if not known.  */
307   char *keyalgostr;
308
309   /* The Gcrypt algo identifier for the key.  It is valid if the
310    * keygrip is also valid.  See also is_ecc above.  */
311   int keyalgo;
312
313   /* The length of the key in bits (e.g. for RSA the length of the
314    * modulus).  It is valid if the keygrip is also valid.  */
315   unsigned int keynbits;
316
317   /* The creation time of the key or 0 if not known.  */
318   u32 keytime;
319
320   /* Malloced CN from the Subject-DN of the corresponding certificate
321    * or NULL if not known.  */
322   char *common_name;
323
324   /* Malloced SerialNumber from the Subject-DN of the corresponding
325    * certificate or NULL if not known.  */
326   char *serial_number;
327
328   /* KDF/KEK parameter for OpenPGP's ECDH.  First byte is zero if not
329    * availabale. .*/
330   unsigned char ecdh_kdf[4];
331
332   /* Length and allocated buffer with the Id of this object. */
333   size_t objidlen;
334   unsigned char *objid;
335
336   /* Length and allocated buffer with the authId of this object or
337      NULL if no authID is known. */
338   size_t authidlen;
339   unsigned char *authid;
340
341   /* NULL or the malloced label of this object.  */
342   char *label;
343
344   /* The keyReference and a flag telling whether it is valid. */
345   unsigned long key_reference;
346
347   /* The offset and length of the object.  They are only valid if
348    * HAVE_OFF is true otherwise they are set to 0. */
349   unsigned long off, len;
350
351   /* The length of the path as given in the PrKDF and the path itself.
352      path[0] is the top DF (usually 0x3f00). */
353   size_t pathlen;
354   unsigned short path[1];
355 };
356 typedef struct prkdf_object_s *prkdf_object_t;
357 typedef struct prkdf_object_s *pukdf_object_t;
358
359
360 /* This is an object to store information about a Authentication
361    Object Directory File (AODF) in a format suitable for further
362    processing by us. To keep memory management, simple we use a linked
363    list of items; i.e. one such object represents one authentication
364    object and the list the entire AOKDF. */
365 struct aodf_object_s
366 {
367   /* Link to next item when used in a linked list. */
368   struct aodf_object_s *next;
369
370   /* Flags to indicate whether fields are valid.  */
371   unsigned int have_off:1;
372
373   /* Length and allocated buffer with the Id of this object. */
374   size_t objidlen;
375   unsigned char *objid;
376
377   /* Length and allocated buffer with the authId of this object or
378      NULL if no authID is known. */
379   size_t authidlen;
380   unsigned char *authid;
381
382   /* NULL or the malloced label of this object.  */
383   char *label;
384
385   /* The file ID of this AODF.  */
386   unsigned short fid;
387
388   /* The type of this authentication object.  */
389   auth_type_t auth_type;
390
391   /* Info used for AUTH_TYPE_PIN: */
392
393   /* The PIN Flags. */
394   struct
395   {
396     unsigned int case_sensitive: 1;
397     unsigned int local: 1;
398     unsigned int change_disabled: 1;
399     unsigned int unblock_disabled: 1;
400     unsigned int initialized: 1;
401     unsigned int needs_padding: 1;
402     unsigned int unblocking_pin: 1;
403     unsigned int so_pin: 1;
404     unsigned int disable_allowed: 1;
405     unsigned int integrity_protected: 1;
406     unsigned int confidentiality_protected: 1;
407     unsigned int exchange_ref_data: 1;
408   } pinflags;
409
410   /* The PIN Type. */
411   pin_type_t pintype;
412
413   /* The minimum length of a PIN. */
414   unsigned long min_length;
415
416   /* The stored length of a PIN. */
417   unsigned long stored_length;
418
419   /* The maximum length of a PIN and a flag telling whether it is valid. */
420   unsigned long max_length;
421   int max_length_valid;
422
423   /* The pinReference and a flag telling whether it is valid. */
424   unsigned long pin_reference;
425   int pin_reference_valid;
426
427   /* The padChar and a flag telling whether it is valid. */
428   char pad_char;
429   int pad_char_valid;
430
431   /* The offset and length of the object.  They are only valid if
432      HAVE_OFF is true and set to 0 if HAVE_OFF is false. */
433   unsigned long off, len;
434
435   /* The length of the path as given in the Aodf and the path itself.
436      path[0] is the top DF (usually 0x3f00). PATH is optional and thus
437      may be NULL.  Malloced.*/
438   size_t pathlen;
439   unsigned short *path;
440
441   /* Info used for AUTH_TYPE_AUTHKEY: */
442
443 };
444 typedef struct aodf_object_s *aodf_object_t;
445
446
447 /* Context local to this application. */
448 struct app_local_s
449 {
450   /* The home DF. Note, that we don't yet support a multilevel
451      hierarchy.  Thus we assume this is directly below the MF.  */
452   unsigned short home_df;
453
454   /* The type of the card's OS. */
455   card_type_t card_type;
456
457   /* The vendor's product.  */
458   card_product_t card_product;
459
460   /* Flag indicating that extended_mode is not supported.  */
461   unsigned int no_extended_mode : 1;
462
463   /* Flag indicating whether we may use direct path selection. */
464   unsigned int direct_path_selection : 1;
465
466   /* Flag indicating whether the card has any key with a gpgusage set.  */
467   unsigned int any_gpgusage : 1;
468
469   /* Structure with the EFIDs of the objects described in the ODF
470      file. */
471   struct
472   {
473     unsigned short private_keys;
474     unsigned short public_keys;
475     unsigned short trusted_public_keys;
476     unsigned short secret_keys;
477     unsigned short certificates;
478     unsigned short trusted_certificates;
479     unsigned short useful_certificates;
480     unsigned short data_objects;
481     unsigned short auth_objects;
482   } odf;
483
484   /* The PKCS#15 serialnumber from EF(TokenInfo) or NULL.  Malloced. */
485   unsigned char *serialno;
486   size_t serialnolen;
487
488   /* The manufacturerID from the TokenInfo EF.  Malloced or NULL. */
489   char *manufacturer_id;
490
491   /* The label from the TokenInfo EF.  Malloced or NULL.  */
492   char *token_label;
493
494   /* The tokenflags from the TokenInfo EF.  Malloced or NULL.  */
495   unsigned char *tokenflags;
496   unsigned int tokenflagslen;
497
498   /* Information on all certificates. */
499   cdf_object_t certificate_info;
500   /* Information on all trusted certificates. */
501   cdf_object_t trusted_certificate_info;
502   /* Information on all useful certificates. */
503   cdf_object_t useful_certificate_info;
504
505   /* Information on all public keys. */
506   prkdf_object_t public_key_info;
507
508   /* Information on all private keys. */
509   pukdf_object_t private_key_info;
510
511   /* Information on all authentication objects. */
512   aodf_object_t auth_object_info;
513
514 };
515
516
517 /*** Local prototypes.  ***/
518 static gpg_error_t select_ef_by_path (app_t app, const unsigned short *path,
519                                       size_t pathlen);
520 static gpg_error_t keygrip_from_prkdf (app_t app, prkdf_object_t prkdf);
521 static gpg_error_t readcert_by_cdf (app_t app, cdf_object_t cdf,
522                                     unsigned char **r_cert, size_t *r_certlen);
523 static char *get_dispserialno (app_t app, prkdf_object_t prkdf);
524 static gpg_error_t do_getattr (app_t app, ctrl_t ctrl, const char *name);
525
526
527 \f
528 static const char *
529 cardtype2str (card_type_t cardtype)
530 {
531   switch (cardtype)
532     {
533     case CARD_TYPE_UNKNOWN:   return "";
534     case CARD_TYPE_TCOS:      return "TCOS";
535     case CARD_TYPE_MICARDO:   return "Micardo";
536     case CARD_TYPE_CARDOS_50: return "CardOS 5.0";
537     case CARD_TYPE_CARDOS_53: return "CardOS 5.3";
538     case CARD_TYPE_BELPIC:    return "Belgian eID";
539     case CARD_TYPE_AET:       return "AET";
540     }
541   return "";
542 }
543
544 static const char *
545 cardproduct2str (card_product_t cardproduct)
546 {
547   switch (cardproduct)
548     {
549     case CARD_PRODUCT_UNKNOWN: return "";
550     case CARD_PRODUCT_RSCS:    return "R&S";
551     case CARD_PRODUCT_DTRUST:  return "D-Trust";
552     case CARD_PRODUCT_GENUA:   return "GeNUA";
553     }
554   return "";
555 }
556
557 /* Release the CDF object A  */
558 static void
559 release_cdflist (cdf_object_t a)
560 {
561   while (a)
562     {
563       cdf_object_t tmp = a->next;
564       ksba_free (a->cert);
565       xfree (a->objid);
566       xfree (a->authid);
567       xfree (a->label);
568       xfree (a);
569       a = tmp;
570     }
571 }
572
573 /* Release the PrKDF object A.  */
574 static void
575 release_prkdflist (prkdf_object_t a)
576 {
577   while (a)
578     {
579       prkdf_object_t tmp = a->next;
580       xfree (a->keyalgostr);
581       xfree (a->common_name);
582       xfree (a->serial_number);
583       xfree (a->objid);
584       xfree (a->authid);
585       xfree (a->label);
586       xfree (a);
587       a = tmp;
588     }
589 }
590
591 static void
592 release_pukdflist (pukdf_object_t a)
593 {
594   release_prkdflist (a);
595 }
596
597 /* Release just one aodf object. */
598 void
599 release_aodf_object (aodf_object_t a)
600 {
601   if (a)
602     {
603       xfree (a->objid);
604       xfree (a->authid);
605       xfree (a->label);
606       xfree (a->path);
607       xfree (a);
608     }
609 }
610
611 /* Release the AODF list A.  */
612 static void
613 release_aodflist (aodf_object_t a)
614 {
615   while (a)
616     {
617       aodf_object_t tmp = a->next;
618       release_aodf_object (a);
619       a = tmp;
620     }
621 }
622
623
624 static void
625 release_lists (app_t app)
626 {
627   release_cdflist (app->app_local->certificate_info);
628   app->app_local->certificate_info = NULL;
629   release_cdflist (app->app_local->trusted_certificate_info);
630   app->app_local->trusted_certificate_info = NULL;
631   release_cdflist (app->app_local->useful_certificate_info);
632   app->app_local->useful_certificate_info = NULL;
633   release_pukdflist (app->app_local->public_key_info);
634   app->app_local->public_key_info = NULL;
635   release_prkdflist (app->app_local->private_key_info);
636   app->app_local->private_key_info = NULL;
637   release_aodflist (app->app_local->auth_object_info);
638   app->app_local->auth_object_info = NULL;
639 }
640
641
642 static void
643 release_tokeninfo (app_t app)
644 {
645   xfree (app->app_local->manufacturer_id);
646   app->app_local->manufacturer_id = NULL;
647   xfree (app->app_local->token_label);
648   app->app_local->token_label = NULL;
649   xfree (app->app_local->tokenflags);
650   app->app_local->tokenflags = NULL;
651   xfree (app->app_local->serialno);
652   app->app_local->serialno = NULL;
653 }
654
655
656 /* Release all local resources.  */
657 static void
658 do_deinit (app_t app)
659 {
660   if (app && app->app_local)
661     {
662       release_lists (app);
663       release_tokeninfo (app);
664       xfree (app->app_local);
665       app->app_local = NULL;
666     }
667 }
668
669
670 /* Do a select and a read for the file with EFID.  EFID_DESC is a
671    desctription of the EF to be used with error messages.  On success
672    BUFFER and BUFLEN contain the entire content of the EF.  The caller
673    must free BUFFER only on success.  If EFID is 0 no seelct is done. */
674 static gpg_error_t
675 select_and_read_binary (app_t app, unsigned short efid, const char *efid_desc,
676                         unsigned char **buffer, size_t *buflen)
677 {
678   gpg_error_t err;
679   int sw;
680
681   if (efid)
682     {
683       err = select_ef_by_path (app, &efid, 1);
684       if (err)
685         {
686           log_error ("p15: error selecting %s (0x%04X): %s\n",
687                      efid_desc, efid, gpg_strerror (err));
688           return err;
689         }
690     }
691
692   err = iso7816_read_binary_ext (app_get_slot (app),
693                                  0, 0, 0, buffer, buflen, &sw);
694   if (err)
695     log_error ("p15: error reading %s (0x%04X): %s (sw=%04X)\n",
696                efid_desc, efid, gpg_strerror (err), sw);
697   return err;
698 }
699
700
701 /* If EFID is not 0 do a select and then read the record RECNO.
702  * EFID_DESC is a description of the EF to be used with error
703  * messages.  On success BUFFER and BUFLEN contain the entire content
704  * of the EF.  The caller must free BUFFER only on success. */
705 static gpg_error_t
706 select_and_read_record (app_t app, unsigned short efid, int recno,
707                         const char *efid_desc,
708                         unsigned char **buffer, size_t *buflen, int *r_sw)
709 {
710   gpg_error_t err;
711   int sw;
712
713   if (r_sw)
714     *r_sw = 0x9000;
715
716   if (efid)
717     {
718       err = select_ef_by_path (app, &efid, 1);
719       if (err)
720         {
721           log_error ("p15: error selecting %s (0x%04X): %s\n",
722                      efid_desc, efid, gpg_strerror (err));
723           if (r_sw)
724             *r_sw = sw;
725           return err;
726         }
727     }
728
729   err = iso7816_read_record_ext (app_get_slot (app),
730                                  recno, 1, 0, buffer, buflen, &sw);
731   if (err)
732     {
733       if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
734           ;
735       else if (err && sw == SW_FILE_STRUCT)
736         ;
737       else
738         log_error ("p15: error reading %s (0x%04X) record %d: %s (sw=%04X)\n",
739                    efid_desc, efid, recno, gpg_strerror (err), sw);
740       if (r_sw)
741         *r_sw = sw;
742       return err;
743     }
744   /* On CardOS with a Linear TLV file structure the records starts
745    * with some tag (often the record number) followed by the length
746    * byte for this record.  Detect and remove this prefix.  */
747   if (*buflen > 2 && (*buffer)[0] != 0x30 && (*buffer)[1] == *buflen - 2)
748     {
749       memmove (*buffer, *buffer + 2, *buflen - 2);
750       *buflen = *buflen - 2;
751     }
752
753   return 0;
754 }
755
756
757 /* This function calls select file to read a file using a complete
758    path which may or may not start at the master file (MF). */
759 static gpg_error_t
760 select_ef_by_path (app_t app, const unsigned short *path, size_t pathlen)
761 {
762   gpg_error_t err;
763   int i, j;
764
765   if (!pathlen)
766     return gpg_error (GPG_ERR_INV_VALUE);
767
768   /* log_debug ("%s: path=", __func__); */
769   /* for (j=0; j < pathlen; j++) */
770   /*   log_printf ("%s%04hX", j? "/":"", path[j]); */
771   /* log_printf ("%s\n",app->app_local->direct_path_selection?" (direct)":"");*/
772
773   if (app->app_local->direct_path_selection)
774     {
775       if (pathlen && *path == 0x3f00 )
776         {
777           if (pathlen == 1)
778             err = iso7816_select_mf (app_get_slot (app));
779           else
780             err = iso7816_select_path (app_get_slot (app), path+1, pathlen-1,
781                                        0);
782         }
783       else
784         err = iso7816_select_path (app_get_slot (app), path, pathlen,
785                                    app->app_local->home_df);
786       if (err)
787         {
788           log_error ("p15: error selecting path ");
789           goto err_print_path;
790         }
791     }
792   else if (pathlen > 1 && path[0] == 0x3fff)
793     {
794       err = iso7816_select_file (app_get_slot (app), 0x3f00, 0);
795       if (err)
796         {
797           log_error ("p15: error selecting part %d from path ", 0);
798           goto err_print_path;
799         }
800       path++;
801       pathlen--;
802       for (i=0; i < pathlen; i++)
803         {
804           err = iso7816_select_file (app_get_slot (app),
805                                      path[i], (i+1 == pathlen)? 2 : 1);
806           if (err)
807             {
808               log_error ("p15: error selecting part %d from path ", i);
809               goto err_print_path;
810             }
811         }
812     }
813   else
814     {
815       if (pathlen && *path != 0x3f00 )
816         log_error ("p15: warning: relative path select not yet implemented\n");
817
818       /* FIXME: Use home_df.  */
819       for (i=0; i < pathlen; i++)
820         {
821           err = iso7816_select_file (app_get_slot (app),
822                                      path[i], !(i+1 == pathlen));
823           if (err)
824             {
825               log_error ("p15: error selecting part %d from path ", i);
826               goto err_print_path;
827             }
828         }
829     }
830   return 0;
831
832  err_print_path:
833   if (pathlen && *path != 0x3f00 )
834     log_printf ("3F00/");
835   else
836     log_printf ("%04hX/", app->app_local->home_df);
837   for (j=0; j < pathlen; j++)
838     log_printf ("%s%04hX", j? "/":"", path[j]);
839   log_printf (": %s\n", gpg_strerror (err));
840   return err;
841 }
842
843
844 /* Parse a cert Id string (or a key Id string) and return the binary
845    object Id string in a newly allocated buffer stored at R_OBJID and
846    R_OBJIDLEN.  On Error NULL will be stored there and an error code
847    returned. On success caller needs to free the buffer at R_OBJID. */
848 static gpg_error_t
849 parse_certid (app_t app, const char *certid,
850               unsigned char **r_objid, size_t *r_objidlen)
851 {
852   char tmpbuf[10];
853   const char *s;
854   size_t objidlen;
855   unsigned char *objid;
856   int i;
857
858   *r_objid = NULL;
859   *r_objidlen = 0;
860
861   if (certid[0] != 'P' && strlen (certid) == 40)  /* This is a keygrip.  */
862     {
863       prkdf_object_t prkdf;
864
865       for (prkdf = app->app_local->private_key_info;
866            prkdf; prkdf = prkdf->next)
867         if (!keygrip_from_prkdf (app, prkdf)
868             && !strcmp (certid, prkdf->keygrip))
869           break;
870       if (!prkdf || !prkdf->objidlen || !prkdf->objid)
871         return gpg_error (GPG_ERR_NOT_FOUND);
872       objidlen = prkdf->objidlen;
873       objid = xtrymalloc (objidlen);
874       if (!objid)
875         return gpg_error_from_syserror ();
876       memcpy (objid, prkdf->objid, prkdf->objidlen);
877     }
878   else /* This is a usual keyref.  */
879     {
880       if (app->app_local->home_df != DEFAULT_HOME_DF)
881         snprintf (tmpbuf, sizeof tmpbuf, "P15-%04X.",
882                   (unsigned int)(app->app_local->home_df & 0xffff));
883       else
884         strcpy (tmpbuf, "P15.");
885       if (strncmp (certid, tmpbuf, strlen (tmpbuf)) )
886         {
887           if (!strncmp (certid, "P15.", 4)
888               || (!strncmp (certid, "P15-", 4)
889                   && hexdigitp (certid+4)
890                   && hexdigitp (certid+5)
891                   && hexdigitp (certid+6)
892                   && hexdigitp (certid+7)
893                   && certid[8] == '.'))
894             return gpg_error (GPG_ERR_NOT_FOUND);
895           return gpg_error (GPG_ERR_INV_ID);
896         }
897       certid += strlen (tmpbuf);
898       for (s=certid, objidlen=0; hexdigitp (s); s++, objidlen++)
899         ;
900       if (*s || !objidlen || (objidlen%2))
901         return gpg_error (GPG_ERR_INV_ID);
902       objidlen /= 2;
903       objid = xtrymalloc (objidlen);
904       if (!objid)
905         return gpg_error_from_syserror ();
906       for (s=certid, i=0; i < objidlen; i++, s+=2)
907         objid[i] = xtoi_2 (s);
908     }
909
910   *r_objid = objid;
911   *r_objidlen = objidlen;
912   return 0;
913 }
914
915
916 /* Find a certificate object by its object ID and store a pointer to
917  * it at R_CDF. */
918 static gpg_error_t
919 cdf_object_from_objid (app_t app, size_t objidlen, const unsigned char *objid,
920                        cdf_object_t *r_cdf)
921 {
922   cdf_object_t cdf;
923
924   for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
925     if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
926       break;
927   if (!cdf)
928     for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
929       if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
930         break;
931   if (!cdf)
932     for (cdf = app->app_local->useful_certificate_info; cdf; cdf = cdf->next)
933       if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
934         break;
935   if (!cdf)
936     return gpg_error (GPG_ERR_NOT_FOUND);
937   *r_cdf = cdf;
938   return 0;
939 }
940
941
942 /* Find a certificate object by its label and store a pointer to it at
943  * R_CDF. */
944 static gpg_error_t
945 cdf_object_from_label (app_t app, const char *label, cdf_object_t *r_cdf)
946 {
947   cdf_object_t cdf;
948
949   if (!label)
950     return gpg_error (GPG_ERR_NOT_FOUND);
951
952   for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
953     if (cdf->label && !strcmp (cdf->label, label))
954       break;
955   if (!cdf)
956     for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
957       if (cdf->label && !strcmp (cdf->label, label))
958         break;
959   if (!cdf)
960     for (cdf = app->app_local->useful_certificate_info; cdf; cdf = cdf->next)
961       if (cdf->label && !strcmp (cdf->label, label))
962         break;
963   if (!cdf)
964     return gpg_error (GPG_ERR_NOT_FOUND);
965   *r_cdf = cdf;
966   return 0;
967 }
968
969
970 /* Find a certificate object by the certificate ID CERTID and store a
971  * pointer to it at R_CDF. */
972 static gpg_error_t
973 cdf_object_from_certid (app_t app, const char *certid, cdf_object_t *r_cdf)
974 {
975   gpg_error_t err;
976   size_t objidlen;
977   unsigned char *objid;
978   cdf_object_t cdf;
979   prkdf_object_t prkdf;
980
981   err = parse_certid (app, certid, &objid, &objidlen);
982   if (err)
983     return err;
984
985   err = cdf_object_from_objid (app, objidlen, objid, &cdf);
986   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
987     {
988       /* Try again by finding the certid in the prkdf and matching by
989        * label.  */
990       for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
991         if (prkdf->objidlen == objidlen
992             && !memcmp (prkdf->objid, objid, objidlen))
993           break;
994       if (prkdf)
995         err = cdf_object_from_label (app, prkdf->label, &cdf);
996     }
997   xfree (objid);
998   if (err)
999     return err;
1000   *r_cdf = cdf;
1001   return 0;
1002 }
1003
1004
1005 /* Find a private key object by the key Id string KEYIDSTR and store a
1006    pointer to it at R_PRKDF. */
1007 static gpg_error_t
1008 prkdf_object_from_keyidstr (app_t app, const char *keyidstr,
1009                             prkdf_object_t *r_prkdf)
1010 {
1011   gpg_error_t err;
1012   size_t objidlen;
1013   unsigned char *objid;
1014   prkdf_object_t prkdf;
1015
1016   err = parse_certid (app, keyidstr, &objid, &objidlen);
1017   if (err)
1018     return err;
1019
1020   for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
1021     if (prkdf->objidlen == objidlen && !memcmp (prkdf->objid, objid, objidlen))
1022       break;
1023   xfree (objid);
1024   if (!prkdf)
1025     return gpg_error (GPG_ERR_NOT_FOUND);
1026   *r_prkdf = prkdf;
1027   return 0;
1028 }
1029
1030
1031
1032 \f
1033 /* Read and parse the Object Directory File and store away the
1034    pointers. ODF_FID shall contain the FID of the ODF.
1035
1036    Example of such a file:
1037
1038    A0 06 30 04 04 02 60 34  = Private Keys
1039    A4 06 30 04 04 02 60 35  = Certificates
1040    A5 06 30 04 04 02 60 36  = Trusted Certificates
1041    A7 06 30 04 04 02 60 37  = Data Objects
1042    A8 06 30 04 04 02 60 38  = Auth Objects
1043
1044    These are all PathOrObjects using the path CHOICE element.  The
1045    paths are octet strings of length 2.  Using this Path CHOICE
1046    element is recommended, so we only implement that for now.
1047 */
1048 static gpg_error_t
1049 read_ef_odf (app_t app, unsigned short odf_fid)
1050 {
1051   gpg_error_t err;
1052   unsigned char *buffer, *p;
1053   size_t buflen, n;
1054   unsigned short value;
1055   size_t offset;
1056   unsigned short home_df = 0;
1057
1058
1059   app->app_local->odf.private_keys = 0;
1060   app->app_local->odf.public_keys = 0;
1061   app->app_local->odf.trusted_public_keys = 0;
1062   app->app_local->odf.secret_keys = 0;
1063   app->app_local->odf.certificates = 0;
1064   app->app_local->odf.trusted_certificates = 0;
1065   app->app_local->odf.useful_certificates = 0;
1066   app->app_local->odf.data_objects = 0;
1067   app->app_local->odf.auth_objects = 0;
1068
1069   err = select_and_read_binary (app, odf_fid, "ODF",
1070                                 &buffer, &buflen);
1071   if (err)
1072     return err;
1073
1074   if (buflen < 8)
1075     {
1076       log_error ("p15: error: ODF too short\n");
1077       xfree (buffer);
1078       return gpg_error (GPG_ERR_INV_OBJ);
1079     }
1080
1081   home_df = app->app_local->home_df;
1082   p = buffer;
1083   while (buflen && *p && *p != 0xff)
1084     {
1085       if ( buflen >= 8
1086            && (p[0] & 0xf0) == 0xA0
1087            && !memcmp (p+1, "\x06\x30\x04\x04\x02", 5) )
1088         {
1089           offset = 6;
1090         }
1091       else if ( buflen >= 12
1092                 && (p[0] & 0xf0) == 0xA0
1093                 && !memcmp (p+1, "\x0a\x30\x08\x04\x06\x3F\x00", 7)
1094                 && (!home_df || home_df == ((p[8]<<8)|p[9])) )
1095         {
1096           /* FIXME: Is this hack still required?  */
1097           /* If we do not know the home DF, we take it from the first
1098            * ODF object.  Here are sample values:
1099            * a0 0a 30 08 0406 3f00 5015 4401
1100            * a1 0a 30 08 0406 3f00 5015 4411
1101            * a4 0a 30 08 0406 3f00 5015 4441
1102            * a5 0a 30 08 0406 3f00 5015 4451
1103            * a8 0a 30 08 0406 3f00 5015 4481
1104            * 00000000 */
1105           if (!home_df)
1106             {
1107               home_df = ((p[8]<<8)|p[9]);
1108               app->app_local->home_df = home_df;
1109               log_info ("p15: application directory detected as 0x%04hX\n",
1110                         home_df);
1111               /* We assume that direct path selection is possible.  */
1112               app->app_local->direct_path_selection = 1;
1113             }
1114
1115           /* We only allow a full path if all files are at the same
1116              level and below the home directory.  To extend this we
1117              would need to make use of new data type capable of
1118              keeping a full path. */
1119           offset = 10;
1120         }
1121       else
1122         {
1123           log_printhex (p, buflen, "p15: ODF format not supported:");
1124           xfree (buffer);
1125           return gpg_error (GPG_ERR_INV_OBJ);
1126         }
1127       switch ((p[0] & 0x0f))
1128         {
1129         case 0: value = app->app_local->odf.private_keys; break;
1130         case 1: value = app->app_local->odf.public_keys; break;
1131         case 2: value = app->app_local->odf.trusted_public_keys; break;
1132         case 3: value = app->app_local->odf.secret_keys; break;
1133         case 4: value = app->app_local->odf.certificates; break;
1134         case 5: value = app->app_local->odf.trusted_certificates; break;
1135         case 6: value = app->app_local->odf.useful_certificates; break;
1136         case 7: value = app->app_local->odf.data_objects; break;
1137         case 8: value = app->app_local->odf.auth_objects; break;
1138         default: value = 0; break;
1139         }
1140       if (value)
1141         {
1142           log_error ("p15: duplicate object type %d in ODF ignored\n",
1143                      (p[0]&0x0f));
1144           continue;
1145         }
1146       value = ((p[offset] << 8) | p[offset+1]);
1147       switch ((p[0] & 0x0f))
1148         {
1149         case 0: app->app_local->odf.private_keys = value; break;
1150         case 1: app->app_local->odf.public_keys = value; break;
1151         case 2: app->app_local->odf.trusted_public_keys = value; break;
1152         case 3: app->app_local->odf.secret_keys = value; break;
1153         case 4: app->app_local->odf.certificates = value; break;
1154         case 5: app->app_local->odf.trusted_certificates = value; break;
1155         case 6: app->app_local->odf.useful_certificates = value; break;
1156         case 7: app->app_local->odf.data_objects = value; break;
1157         case 8: app->app_local->odf.auth_objects = value; break;
1158         default:
1159           log_error ("p15: unknown object type %d in ODF ignored\n",
1160                      (p[0]&0x0f));
1161         }
1162       offset += 2;
1163
1164       if (buflen < offset)
1165         break;
1166       p += offset;
1167       buflen -= offset;
1168     }
1169
1170   if (buflen)
1171     {
1172       /* Print a warning if non-null garbage is left over.  */
1173       for (n=0; n < buflen && !p[n]; n++)
1174         ;
1175       if (n < buflen)
1176         {
1177           log_info ("p15: warning: garbage detected at end of ODF: ");
1178           log_printhex (p, buflen, "");
1179         }
1180     }
1181
1182   xfree (buffer);
1183   return 0;
1184 }
1185
1186
1187 /* Helper for the read_ef_foo functions to read the first record or
1188  * the entire data.  */
1189 static gpg_error_t
1190 read_first_record (app_t app, unsigned short fid, const char *fid_desc,
1191                    unsigned char **r_buffer, size_t *r_buflen,
1192                    int *r_use_read_record)
1193 {
1194   gpg_error_t err;
1195   int sw;
1196
1197   *r_buffer = NULL;
1198   *r_buflen = 0;
1199   *r_use_read_record = 0;
1200
1201   if (!fid)
1202     return gpg_error (GPG_ERR_NO_DATA); /* No such file. */
1203
1204   if (IS_CARDOS_5 (app))
1205     {
1206       *r_use_read_record = 1;
1207       err = select_and_read_record (app, fid, 1, fid_desc,
1208                                     r_buffer, r_buflen, &sw);
1209       if (err && sw == SW_FILE_STRUCT)
1210         {
1211           *r_use_read_record = 0;
1212           err = select_and_read_binary (app, 0, fid_desc, r_buffer, r_buflen);
1213         }
1214     }
1215   else
1216     err = select_and_read_binary (app, fid, fid_desc, r_buffer, r_buflen);
1217
1218   /* We get a not_found state in read_record mode if the select
1219    * succeeded but reading the record failed.  Map that to no_data
1220    * which is what the caller of the read_ef_foo functions expect.  */
1221   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1222     err = gpg_error (GPG_ERR_NO_DATA);
1223
1224   return err;
1225 }
1226
1227
1228 /* Parse the BIT STRING with the keyUsageFlags from the
1229    CommonKeyAttributes. */
1230 static gpg_error_t
1231 parse_keyusage_flags (const unsigned char *der, size_t derlen,
1232                       keyusage_flags_t *usageflags)
1233 {
1234   unsigned int bits, mask;
1235   int i, unused, full;
1236
1237   memset (usageflags, 0, sizeof *usageflags);
1238   if (!derlen)
1239     return gpg_error (GPG_ERR_INV_OBJ);
1240
1241   unused = *der++; derlen--;
1242   if ((!derlen && unused) || unused/8 > derlen)
1243     return gpg_error (GPG_ERR_ENCODING_PROBLEM);
1244   full = derlen - (unused+7)/8;
1245   unused %= 8;
1246   mask = 0;
1247   for (i=1; unused; i <<= 1, unused--)
1248     mask |= i;
1249
1250   /* First octet */
1251   if (derlen)
1252     {
1253       bits = *der++; derlen--;
1254       if (full)
1255         full--;
1256       else
1257         {
1258           bits &= ~mask;
1259           mask = 0;
1260         }
1261     }
1262   else
1263     bits = 0;
1264   if ((bits & 0x80)) usageflags->encrypt = 1;
1265   if ((bits & 0x40)) usageflags->decrypt = 1;
1266   if ((bits & 0x20)) usageflags->sign = 1;
1267   if ((bits & 0x10)) usageflags->sign_recover = 1;
1268   if ((bits & 0x08)) usageflags->wrap = 1;
1269   if ((bits & 0x04)) usageflags->unwrap = 1;
1270   if ((bits & 0x02)) usageflags->verify = 1;
1271   if ((bits & 0x01)) usageflags->verify_recover = 1;
1272
1273   /* Second octet. */
1274   if (derlen)
1275     {
1276       bits = *der++; derlen--;
1277       if (full)
1278         full--;
1279       else
1280         {
1281           bits &= ~mask;
1282         }
1283     }
1284   else
1285     bits = 0;
1286   if ((bits & 0x80)) usageflags->derive = 1;
1287   if ((bits & 0x40)) usageflags->non_repudiation = 1;
1288
1289   return 0;
1290 }
1291
1292
1293 static void
1294 dump_keyusage_flags (keyusage_flags_t usageflags)
1295 {
1296   const char *s = "";
1297
1298   log_info ("p15:             usage=");
1299   if (usageflags.encrypt)
1300     log_printf ("%sencrypt", s), s = ",";
1301   if (usageflags.decrypt)
1302     log_printf ("%sdecrypt", s), s = ",";
1303   if (usageflags.sign   )
1304     log_printf ("%ssign", s), s = ",";
1305   if (usageflags.sign_recover)
1306     log_printf ("%ssign_recover", s), s = ",";
1307   if (usageflags.wrap   )
1308     log_printf ("%swrap", s), s = ",";
1309   if (usageflags.unwrap )
1310     log_printf ("%sunwrap", s), s = ",";
1311   if (usageflags.verify )
1312     log_printf ("%sverify", s), s = ",";
1313   if (usageflags.verify_recover)
1314     log_printf ("%sverify_recover", s), s = ",";
1315   if (usageflags.derive )
1316     log_printf ("%sderive", s), s = ",";
1317   if (usageflags.non_repudiation)
1318     log_printf ("%snon_repudiation", s), s = ",";
1319 }
1320
1321
1322 static void
1323 dump_keyaccess_flags (keyaccess_flags_t accessflags)
1324 {
1325   const char *s = "";
1326
1327   log_info ("p15:             access=");
1328   if (accessflags.sensitive)
1329     log_printf ("%ssensitive", s), s = ",";
1330   if (accessflags.extractable)
1331     log_printf ("%sextractable", s), s = ",";
1332   if (accessflags.always_sensitive)
1333     log_printf ("%salways_sensitive", s), s = ",";
1334   if (accessflags.never_extractable)
1335     log_printf ("%snever_extractable", s), s = ",";
1336   if (accessflags.local)
1337     log_printf ("%slocal", s), s = ",";
1338 }
1339
1340
1341 static void
1342 dump_gpgusage_flags (gpgusage_flags_t gpgusage)
1343 {
1344   const char *s = "";
1345
1346   log_info ("p15:             gpgusage=");
1347   if (gpgusage.cert)
1348     log_printf ("%scert", s), s = ",";
1349   if (gpgusage.sign)
1350     log_printf ("%ssign", s), s = ",";
1351   if (gpgusage.encr)
1352     log_printf ("%sencr", s), s = ",";
1353   if (gpgusage.auth)
1354     log_printf ("%sauth", s), s = ",";
1355 }
1356
1357
1358 /* Parse the BIT STRING with the keyAccessFlags from the
1359    CommonKeyAttributes. */
1360 static gpg_error_t
1361 parse_keyaccess_flags (const unsigned char *der, size_t derlen,
1362                        keyaccess_flags_t *accessflags)
1363 {
1364   unsigned int bits, mask;
1365   int i, unused, full;
1366
1367   memset (accessflags, 0, sizeof *accessflags);
1368   if (!derlen)
1369     return gpg_error (GPG_ERR_INV_OBJ);
1370
1371   unused = *der++; derlen--;
1372   if ((!derlen && unused) || unused/8 > derlen)
1373     return gpg_error (GPG_ERR_ENCODING_PROBLEM);
1374   full = derlen - (unused+7)/8;
1375   unused %= 8;
1376   mask = 0;
1377   for (i=1; unused; i <<= 1, unused--)
1378     mask |= i;
1379
1380   /* First octet */
1381   if (derlen)
1382     {
1383       bits = *der++; derlen--;
1384       if (full)
1385         full--;
1386       else
1387         {
1388           bits &= ~mask;
1389           mask = 0;
1390         }
1391     }
1392   else
1393     bits = 0;
1394   if ((bits & 0x10)) accessflags->local = 1;
1395   if ((bits & 0x08)) accessflags->never_extractable = 1;
1396   if ((bits & 0x04)) accessflags->always_sensitive = 1;
1397   if ((bits & 0x02)) accessflags->extractable = 1;
1398   if ((bits & 0x01)) accessflags->sensitive = 1;
1399
1400   accessflags->any = 1;
1401   return 0;
1402 }
1403
1404
1405 /* Parse the commonObjectAttributes and store a malloced authid at
1406  * (r_authid,r_authidlen).  (NULL,0) is stored on error or if no
1407  * authid is found.  IF R_LABEL is not NULL the label is stored there
1408  * as a malloced string (spaces are replaced by underscores).
1409  *
1410  * Example data:
1411  *  2 30   17:   SEQUENCE { -- commonObjectAttributes
1412  *  4 0C    8:     UTF8String 'SK.CH.DS'    -- label
1413  * 14 03    2:     BIT STRING 6 unused bits
1414  *           :       '01'B (bit 0)
1415  * 18 04    1:     OCTET STRING --authid
1416  *           :       07
1417  *           :     }
1418  */
1419 static gpg_error_t
1420 parse_common_obj_attr (unsigned char const **buffer, size_t *size,
1421                        unsigned char **r_authid, size_t *r_authidlen,
1422                        char **r_label)
1423 {
1424   gpg_error_t err;
1425   int where;
1426   int class, tag, constructed, ndef;
1427   size_t objlen, hdrlen, nnn;
1428   const unsigned char *ppp;
1429   int ignore_eof = 0;
1430   char *p;
1431
1432   *r_authid = NULL;
1433   *r_authidlen = 0;
1434   if (r_label)
1435     *r_label = NULL;
1436
1437   where = __LINE__;
1438   err = parse_ber_header (buffer, size, &class, &tag, &constructed,
1439                           &ndef, &objlen, &hdrlen);
1440   if (!err && (objlen > *size || tag != TAG_SEQUENCE))
1441     err = gpg_error (GPG_ERR_INV_OBJ);
1442   if (err)
1443     goto leave;
1444
1445   ppp = *buffer;
1446   nnn = objlen;
1447   *buffer += objlen;
1448   *size   -= objlen;
1449
1450   /* Search the optional AuthId.  */
1451   ignore_eof = 1;
1452   where = __LINE__;
1453   err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1454                           &ndef, &objlen, &hdrlen);
1455   if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1456     err = gpg_error (GPG_ERR_INV_OBJ);
1457   if (err)
1458     goto leave;
1459
1460   if (tag == TAG_UTF8_STRING)
1461     {
1462       if (r_label)
1463         {
1464           *r_label = xtrymalloc (objlen + 1);
1465           if (!*r_label)
1466             {
1467               err = gpg_error_from_syserror ();
1468               goto leave;
1469             }
1470           memcpy (*r_label, ppp, objlen);
1471           (*r_label)[objlen] = 0;
1472           /* We don't want spaces in the labels due to the properties
1473            * of CHV-LABEL.  */
1474           for (p = *r_label; *p; p++)
1475             if (ascii_isspace (*p))
1476               *p = '_';
1477         }
1478
1479       ppp += objlen;
1480       nnn -= objlen;
1481
1482       where = __LINE__;
1483       err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1484                               &ndef, &objlen, &hdrlen);
1485       if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1486         err = gpg_error (GPG_ERR_INV_OBJ);
1487       if (err)
1488         goto leave;
1489     }
1490   if (tag == TAG_BIT_STRING)
1491     {
1492       ppp += objlen; /* Skip the CommonObjectFlags.  */
1493       nnn -= objlen;
1494
1495       where = __LINE__;
1496       err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1497                               &ndef, &objlen, &hdrlen);
1498       if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1499         err = gpg_error (GPG_ERR_INV_OBJ);
1500       if (err)
1501         goto leave;
1502     }
1503   if (tag == TAG_OCTET_STRING && objlen)
1504     {
1505       *r_authid = xtrymalloc (objlen);
1506       if (!*r_authid)
1507         {
1508           err = gpg_error_from_syserror ();
1509           goto leave;
1510         }
1511       memcpy (*r_authid, ppp, objlen);
1512       *r_authidlen = objlen;
1513     }
1514
1515  leave:
1516   if (ignore_eof && gpg_err_code (err) == GPG_ERR_EOF)
1517     err = 0;
1518   else if (err)
1519     log_error ("p15: error parsing commonObjectAttributes at %d: %s\n",
1520                where, gpg_strerror (err));
1521
1522   if (err && r_label)
1523     {
1524       xfree (*r_label);
1525       *r_label = NULL;
1526     }
1527
1528   return err;
1529 }
1530
1531
1532 /* Parse the commonKeyAttributes.  On success store the objid at
1533  * (R_OBJID/R_OBJIDLEN), sets the key usage flags at USAGEFLAGS and
1534  * the optiona key refrence at R_KEY_REFERENCE.  The latter is only
1535  * valid if true is also stored at R_KEY_REFERENCE_VALID.
1536  *
1537  * Example data:
1538  *
1539  * 21 30   12:   SEQUENCE { -- commonKeyAttributes
1540  * 23 04    1:     OCTET STRING
1541  *           :       01
1542  * 26 03    3:     BIT STRING 6 unused bits
1543  *           :       '1000000000'B (bit 9)
1544  * 31 02    2:     INTEGER 80  -- keyReference (optional)
1545  *           :     }
1546  */
1547 static gpg_error_t
1548 parse_common_key_attr (unsigned char const **buffer, size_t *size,
1549                        unsigned char **r_objid, size_t *r_objidlen,
1550                        keyusage_flags_t *usageflags,
1551                        keyaccess_flags_t *accessflags,
1552                        unsigned long *r_key_reference,
1553                        int *r_key_reference_valid)
1554 {
1555   gpg_error_t err;
1556   int where;
1557   int class, tag, constructed, ndef;
1558   size_t objlen, hdrlen, nnn;
1559   const unsigned char *ppp;
1560   int ignore_eof = 0;
1561   unsigned long ul;
1562   const unsigned char *objid = NULL;
1563   size_t objidlen;
1564   unsigned long key_reference = 0;
1565   int key_reference_valid = 0;
1566
1567   *r_objid = NULL;
1568   *r_objidlen = 0;
1569   memset (usageflags, 0, sizeof *usageflags);
1570   memset (accessflags, 0, sizeof *accessflags);
1571   *r_key_reference_valid = 0;
1572
1573   where = __LINE__;
1574   err = parse_ber_header (buffer, size, &class, &tag, &constructed,
1575                           &ndef, &objlen, &hdrlen);
1576   if (!err && (objlen > *size || tag != TAG_SEQUENCE))
1577         err = gpg_error (GPG_ERR_INV_OBJ);
1578   if (err)
1579     goto leave;
1580
1581   ppp = *buffer;
1582   nnn = objlen;
1583   *buffer += objlen;
1584   *size   -= objlen;
1585
1586   /* Get the Id. */
1587   where = __LINE__;
1588   err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1589                           &ndef, &objlen, &hdrlen);
1590   if (!err && (objlen > nnn
1591                || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
1592     err = gpg_error (GPG_ERR_INV_OBJ);
1593   if (err)
1594     goto leave;
1595
1596   objid = ppp;
1597   objidlen = objlen;
1598   ppp += objlen;
1599   nnn -= objlen;
1600
1601   /* Get the KeyUsageFlags. */
1602   where = __LINE__;
1603   err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1604                           &ndef, &objlen, &hdrlen);
1605   if (!err && (objlen > nnn
1606                || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
1607     err = gpg_error (GPG_ERR_INV_OBJ);
1608   if (err)
1609     goto leave;
1610
1611   err = parse_keyusage_flags (ppp, objlen, usageflags);
1612   if (err)
1613     goto leave;
1614   ppp += objlen;
1615   nnn -= objlen;
1616
1617   ignore_eof = 1; /* Remaining items are optional.  */
1618
1619   /* Find the keyReference */
1620   where = __LINE__;
1621   err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1622                           &ndef, &objlen, &hdrlen);
1623   if (!err && objlen > nnn)
1624     err = gpg_error (GPG_ERR_INV_OBJ);
1625   if (err)
1626     goto leave;
1627
1628   if (class == CLASS_UNIVERSAL && tag == TAG_BOOLEAN)
1629     {
1630       /* Skip the native element. */
1631       ppp += objlen;
1632       nnn -= objlen;
1633
1634       err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1635                               &ndef, &objlen, &hdrlen);
1636       if (!err && objlen > nnn)
1637         err = gpg_error (GPG_ERR_INV_OBJ);
1638       if (err)
1639         goto leave;
1640     }
1641   if (class == CLASS_UNIVERSAL && tag == TAG_BIT_STRING)
1642     {
1643       /* These are the keyAccessFlags. */
1644       err = parse_keyaccess_flags (ppp, objlen, accessflags);
1645       if (err)
1646         goto leave;
1647       ppp += objlen;
1648       nnn -= objlen;
1649
1650       err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1651                               &ndef, &objlen, &hdrlen);
1652       if (!err && objlen > nnn)
1653         err = gpg_error (GPG_ERR_INV_OBJ);
1654       if (err)
1655         goto leave;
1656     }
1657   if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
1658     {
1659       /* This is the keyReference.  */
1660       for (ul=0; objlen; objlen--)
1661         {
1662           ul <<= 8;
1663           ul |= (*ppp++) & 0xff;
1664           nnn--;
1665         }
1666       key_reference = ul;
1667       key_reference_valid = 1;
1668     }
1669
1670  leave:
1671   if (ignore_eof && gpg_err_code (err) == GPG_ERR_EOF)
1672     err = 0;
1673
1674   if (!err)
1675     {
1676       if (!objid || !objidlen)
1677         err = gpg_error (GPG_ERR_INV_OBJ);
1678       else
1679         {
1680           *r_objid = xtrymalloc (objidlen);
1681           if (!*r_objid)
1682             err = gpg_error_from_syserror ();
1683           else
1684             {
1685               memcpy (*r_objid, objid, objidlen);
1686               *r_objidlen = objidlen;
1687             }
1688         }
1689     }
1690   if (!err && key_reference_valid)
1691     {
1692       *r_key_reference = key_reference;
1693       *r_key_reference_valid = 1;
1694     }
1695
1696   if (err)
1697     log_error ("p15: error parsing commonKeyAttributes at %d: %s\n",
1698                where, gpg_strerror (err));
1699   return err;
1700
1701 }
1702
1703
1704 /* Read and  parse the Private Key Directory Files.
1705  *
1706  * Sample object:
1707  *  SEQUENCE {
1708  *    SEQUENCE { -- commonObjectAttributes
1709  *      UTF8String 'SK.CH.DS'
1710  *      BIT STRING 6 unused bits
1711  *        '01'B (bit 0) -- flags: non-modifiable,private
1712  *      OCTET STRING --authid
1713  *        07
1714  *      }
1715  *    SEQUENCE { -- commonKeyAttributes
1716  *      OCTET STRING
1717  *        01
1718  *      BIT STRING 6 unused bits
1719  *        '1000000000'B (bit 9) -- keyusage: non-repudiation
1720  *      INTEGER 80  -- keyReference (optional)
1721  *      }
1722  *    [1] {  -- keyAttributes
1723  *      SEQUENCE { -- privateRSAKeyAttributes
1724  *        SEQUENCE { -- objectValue
1725  *          OCTET STRING --path
1726  *            3F 00 40 16 00 50
1727  *          }
1728  *        INTEGER 1024 -- modulus
1729  *        }
1730  *      }
1731  *    }
1732  *
1733  * Sample part for EC objects:
1734  *    [1] {  -- keyAttributes
1735  *      [1] { -- privateECkeyAttributes
1736  *        SEQUENCE { -- objectValue
1737  *          SEQUENCE { --path
1738  *            OCTET STRING 50 72 4B 03
1739  *          }
1740  *        INTEGER 33  -- Not in PKCS#15v1.1, need to buy 7816-15?
1741  *        }
1742  *      }
1743  */
1744 static gpg_error_t
1745 read_ef_prkdf (app_t app, unsigned short fid, prkdf_object_t *result)
1746 {
1747   gpg_error_t err;
1748   unsigned char *buffer;
1749   size_t buflen;
1750   const unsigned char *p;
1751   size_t n, objlen, hdrlen;
1752   int class, tag, constructed, ndef;
1753   prkdf_object_t prkdflist = NULL;
1754   int i;
1755   int recno = 1;
1756   unsigned char *authid = NULL;
1757   size_t authidlen = 0;
1758   unsigned char *objid = NULL;
1759   size_t objidlen = 0;
1760   char *label = NULL;
1761   int record_mode;
1762
1763   err = read_first_record (app, fid, "PrKDF", &buffer, &buflen, &record_mode);
1764   if (err)
1765     return err;
1766
1767   p = buffer;
1768   n = buflen;
1769
1770   /* Loop over the records.  We stop as soon as we detect a new record
1771      starting with 0x00 or 0xff as these values are commonly used to
1772      pad data blocks and are no valid ASN.1 encoding.  Note the
1773      special handling for record mode at the end of the loop. */
1774   while (n && *p && *p != 0xff)
1775     {
1776       const unsigned char *pp;
1777       size_t nn;
1778       int where;
1779       const char *errstr = NULL;
1780       prkdf_object_t prkdf = NULL;
1781       unsigned long ul;
1782       keyusage_flags_t usageflags;
1783       keyaccess_flags_t accessflags;
1784       unsigned long key_reference = 0;
1785       int key_reference_valid = 0;
1786       int is_ecc = 0;
1787
1788       where = __LINE__;
1789       err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1790                               &ndef, &objlen, &hdrlen);
1791       if (err)
1792         ;
1793       else if (objlen > n)
1794         err = gpg_error (GPG_ERR_INV_OBJ);
1795       else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
1796         ; /* PrivateRSAKeyAttributes  */
1797       else if (class == CLASS_CONTEXT)
1798         {
1799           switch (tag)
1800             {
1801             case 0: is_ecc = 1; break; /* PrivateECKeyAttributes  */
1802             case 1: errstr = "DH key objects are not supported"; break;
1803             case 2: errstr = "DSA key objects are not supported"; break;
1804             case 3: errstr = "KEA key objects are not supported"; break;
1805             default: errstr = "unknown privateKeyObject"; break;
1806             }
1807           if (errstr)
1808             goto parse_error;
1809         }
1810       else
1811         {
1812           err = gpg_error (GPG_ERR_INV_OBJ);
1813           goto parse_error;
1814         }
1815
1816       if (err)
1817         {
1818           log_error ("p15: error parsing PrKDF record: %s\n",
1819                      gpg_strerror (err));
1820           goto leave;
1821         }
1822
1823       pp = p;
1824       nn = objlen;
1825       p += objlen;
1826       n -= objlen;
1827
1828       /* Parse the commonObjectAttributes.  */
1829       where = __LINE__;
1830       xfree (authid);
1831       xfree (label);
1832       err = parse_common_obj_attr (&pp, &nn, &authid, &authidlen, &label);
1833       if (err)
1834         goto parse_error;
1835
1836       /* Parse the commonKeyAttributes.  */
1837       where = __LINE__;
1838       xfree (objid);
1839       err = parse_common_key_attr (&pp, &nn,
1840                                    &objid, &objidlen,
1841                                    &usageflags, &accessflags,
1842                                    &key_reference, &key_reference_valid);
1843       if (err)
1844         goto parse_error;
1845       log_assert (objid);
1846
1847       /* Skip commonPrivateKeyAttributes.  */
1848       where = __LINE__;
1849       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1850                               &ndef, &objlen, &hdrlen);
1851       if (!err && objlen > nn)
1852         err = gpg_error (GPG_ERR_INV_OBJ);
1853       if (err)
1854         goto parse_error;
1855       if (class == CLASS_CONTEXT && tag == 0)
1856         {
1857           pp += objlen;
1858           nn -= objlen;
1859
1860           where = __LINE__;
1861           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1862                                   &ndef, &objlen, &hdrlen);
1863         }
1864       /* Parse the keyAttributes.  */
1865       if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1866         err = gpg_error (GPG_ERR_INV_OBJ);
1867       if (err)
1868         goto parse_error;
1869       nn = objlen;
1870
1871       where = __LINE__;
1872       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1873                               &ndef, &objlen, &hdrlen);
1874       if (err)
1875         ;
1876       else if (!err && objlen > nn)
1877         err = gpg_error (GPG_ERR_INV_OBJ);
1878       else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
1879         ; /* A typeAttribute always starts with a sequence.  */
1880       else
1881         err = gpg_error (GPG_ERR_INV_OBJ);
1882       if (err)
1883         goto parse_error;
1884
1885       nn = objlen;
1886
1887       /* Check that the reference is a Path object.  */
1888       where = __LINE__;
1889       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1890                               &ndef, &objlen, &hdrlen);
1891       if (!err && objlen > nn)
1892         err = gpg_error (GPG_ERR_INV_OBJ);
1893       if (err)
1894         goto parse_error;
1895       if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
1896         {
1897           errstr = "unsupported reference type";
1898           goto parse_error;
1899         }
1900       nn = objlen;
1901
1902       /* Parse the Path object. */
1903       where = __LINE__;
1904       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1905                               &ndef, &objlen, &hdrlen);
1906       if (!err && objlen > nn)
1907         err = gpg_error (GPG_ERR_INV_OBJ);
1908       if (err)
1909         goto parse_error;
1910
1911       /* Make sure that the next element is a non zero path and of
1912          even length (FID are two bytes each). */
1913       if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
1914           ||  !objlen || (objlen & 1) )
1915         {
1916           errstr = "invalid path reference";
1917           goto parse_error;
1918         }
1919
1920       /* Create a new PrKDF list item. */
1921       prkdf = xtrycalloc (1, (sizeof *prkdf
1922                               - sizeof(unsigned short)
1923                               + objlen/2 * sizeof(unsigned short)));
1924       if (!prkdf)
1925         {
1926           err = gpg_error_from_syserror ();
1927           goto leave;
1928         }
1929       prkdf->is_ecc = is_ecc;
1930
1931       prkdf->objidlen = objidlen;
1932       prkdf->objid = objid;
1933       objid = NULL;
1934       if (authid)
1935         {
1936           prkdf->authidlen = authidlen;
1937           prkdf->authid = authid;
1938           authid = NULL;
1939         }
1940       if (label)
1941         {
1942           prkdf->label = label;
1943           label = NULL;
1944         }
1945
1946       prkdf->pathlen = objlen/2;
1947       for (i=0; i < prkdf->pathlen; i++, pp += 2, nn -= 2)
1948         prkdf->path[i] = ((pp[0] << 8) | pp[1]);
1949
1950       prkdf->usageflags = usageflags;
1951       prkdf->accessflags = accessflags;
1952       prkdf->key_reference = key_reference;
1953       prkdf->key_reference_valid = key_reference_valid;
1954
1955       if (nn)
1956         {
1957           /* An index and length follows. */
1958           prkdf->have_off = 1;
1959           where = __LINE__;
1960           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1961                                   &ndef, &objlen, &hdrlen);
1962           if (!err && (objlen > nn
1963                        || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1964             err = gpg_error (GPG_ERR_INV_OBJ);
1965           if (err)
1966             goto parse_error;
1967
1968           for (ul=0; objlen; objlen--)
1969             {
1970               ul <<= 8;
1971               ul |= (*pp++) & 0xff;
1972               nn--;
1973             }
1974           prkdf->off = ul;
1975
1976           where = __LINE__;
1977           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1978                                   &ndef, &objlen, &hdrlen);
1979           if (!err && (objlen > nn
1980                        || class != CLASS_CONTEXT || tag != 0))
1981             err = gpg_error (GPG_ERR_INV_OBJ);
1982           if (err)
1983             goto parse_error;
1984
1985           for (ul=0; objlen; objlen--)
1986             {
1987               ul <<= 8;
1988               ul |= (*pp++) & 0xff;
1989               nn--;
1990             }
1991           prkdf->len = ul;
1992         }
1993
1994       /* The info is printed later in read_p15_info because we also
1995        * want to look at the certificates.  */
1996
1997       /* Put it into the list. */
1998       prkdf->next = prkdflist;
1999       prkdflist = prkdf;
2000       prkdf = NULL;
2001       goto next_record; /* Ready with this record. */
2002
2003     parse_error:
2004       log_error ("p15: error parsing PrKDF record at %d: %s - skipped\n",
2005                  where, errstr? errstr : gpg_strerror (err));
2006       if (prkdf)
2007         {
2008           xfree (prkdf->objid);
2009           xfree (prkdf->authid);
2010           xfree (prkdf->label);
2011           xfree (prkdf);
2012         }
2013       err = 0;
2014
2015     next_record:
2016       /* If the card uses a record oriented file structure, read the
2017        * next record.  Otherwise we keep on parsing the current buffer.  */
2018       recno++;
2019       if (record_mode)
2020         {
2021           xfree (buffer); buffer = NULL;
2022           err = select_and_read_record (app, 0, recno, "PrKDF",
2023                                         &buffer, &buflen, NULL);
2024           if (err) {
2025             if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2026               err = 0;
2027             goto leave;
2028           }
2029           p = buffer;
2030           n = buflen;
2031         }
2032     } /* End looping over all records. */
2033
2034  leave:
2035   xfree (authid);
2036   xfree (label);
2037   xfree (objid);
2038   xfree (buffer);
2039   if (err)
2040     release_prkdflist (prkdflist);
2041   else
2042     *result = prkdflist;
2043   return err;
2044 }
2045
2046
2047 /* Read and parse the Public Keys Directory File. */
2048 static gpg_error_t
2049 read_ef_pukdf (app_t app, unsigned short fid, pukdf_object_t *result)
2050 {
2051   gpg_error_t err;
2052   unsigned char *buffer;
2053   size_t buflen;
2054   const unsigned char *p;
2055   size_t n, objlen, hdrlen;
2056   int class, tag, constructed, ndef;
2057   pukdf_object_t pukdflist = NULL;
2058   int i;
2059   int recno = 1;
2060   unsigned char *authid = NULL;
2061   size_t authidlen = 0;
2062   unsigned char *objid = NULL;
2063   size_t objidlen = 0;
2064   char *label = NULL;
2065   int record_mode;
2066
2067   err = read_first_record (app, fid, "PuKDF", &buffer, &buflen, &record_mode);
2068   if (err)
2069     return err;
2070
2071   p = buffer;
2072   n = buflen;
2073
2074   /* Loop over the records.  We stop as soon as we detect a new record
2075    * starting with 0x00 or 0xff as these values are commonly used to
2076    * pad data blocks and are no valid ASN.1 encoding.  Note the
2077    * special handling for record mode at the end of the loop. */
2078   while (n && *p && *p != 0xff)
2079     {
2080       const unsigned char *pp;
2081       size_t nn;
2082       int where;
2083       const char *errstr = NULL;
2084       pukdf_object_t pukdf = NULL;
2085       unsigned long ul;
2086       keyusage_flags_t usageflags;
2087       keyaccess_flags_t accessflags;
2088       unsigned long key_reference = 0;
2089       int key_reference_valid = 0;
2090
2091       where = __LINE__;
2092       err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2093                               &ndef, &objlen, &hdrlen);
2094       if (err)
2095         ;
2096       else if (objlen > n)
2097         err = gpg_error (GPG_ERR_INV_OBJ);
2098       else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
2099         ; /* PublicRSAKeyAttributes  */
2100       else if (class == CLASS_CONTEXT)
2101         {
2102           switch (tag)
2103             {
2104             case 0: break; /* EC key object */
2105             case 1: errstr = "DH key objects are not supported"; break;
2106             case 2: errstr = "DSA key objects are not supported"; break;
2107             case 3: errstr = "KEA key objects are not supported"; break;
2108             default: errstr = "unknown publicKeyObject"; break;
2109             }
2110           if (errstr)
2111             goto parse_error;
2112         }
2113       else
2114         {
2115           err = gpg_error (GPG_ERR_INV_OBJ);
2116           goto parse_error;
2117         }
2118
2119       if (err)
2120         {
2121           log_error ("p15: error parsing PuKDF record: %s\n",
2122                      gpg_strerror (err));
2123           goto leave;
2124         }
2125
2126       pp = p;
2127       nn = objlen;
2128       p += objlen;
2129       n -= objlen;
2130
2131       /* Parse the commonObjectAttributes.  */
2132       where = __LINE__;
2133       xfree (authid);
2134       xfree (label);
2135       err = parse_common_obj_attr (&pp, &nn, &authid, &authidlen, &label);
2136       if (err)
2137         goto parse_error;
2138
2139       /* Parse the commonKeyAttributes.  */
2140       where = __LINE__;
2141       xfree (objid);
2142       err = parse_common_key_attr (&pp, &nn,
2143                                    &objid, &objidlen,
2144                                    &usageflags, &accessflags,
2145                                    &key_reference, &key_reference_valid);
2146       if (err)
2147         goto parse_error;
2148       log_assert (objid);
2149
2150       /* Parse the subClassAttributes.  */
2151       where = __LINE__;
2152       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2153                               &ndef, &objlen, &hdrlen);
2154       if (!err && objlen > nn)
2155         err = gpg_error (GPG_ERR_INV_OBJ);
2156       if (err)
2157         goto parse_error;
2158       if (class == CLASS_CONTEXT && tag == 0)
2159         {
2160           /* Skip this CommonPublicKeyAttribute.  */
2161           pp += objlen;
2162           nn -= objlen;
2163
2164           where = __LINE__;
2165           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2166                                   &ndef, &objlen, &hdrlen);
2167         }
2168       /* We expect a typeAttribute.  */
2169       if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
2170         err = gpg_error (GPG_ERR_INV_OBJ);
2171       if (err)
2172         goto parse_error;  /* No typeAttribute.  */
2173       nn = objlen;
2174
2175       where = __LINE__;
2176       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2177                               &ndef, &objlen, &hdrlen);
2178       if (err)
2179         ;
2180       else if (!err && objlen > nn)
2181         err = gpg_error (GPG_ERR_INV_OBJ);
2182       else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
2183         ; /* A typeAttribute always starts with a sequence.  */
2184       else
2185         err = gpg_error (GPG_ERR_INV_OBJ);
2186       if (err)
2187         goto parse_error;
2188
2189       nn = objlen;
2190
2191       /* Check that the reference is a Path object.  */
2192       where = __LINE__;
2193       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2194                               &ndef, &objlen, &hdrlen);
2195       if (!err && objlen > nn)
2196         err = gpg_error (GPG_ERR_INV_OBJ);
2197       if (err)
2198         goto parse_error;
2199       if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
2200         {
2201           errstr = "unsupported reference type";
2202           goto parse_error;
2203         }
2204       nn = objlen;
2205
2206       /* Parse the Path object. */
2207       where = __LINE__;
2208       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2209                               &ndef, &objlen, &hdrlen);
2210       if (!err && objlen > nn)
2211         err = gpg_error (GPG_ERR_INV_OBJ);
2212       if (err)
2213         goto parse_error;
2214
2215       /* Make sure that the next element is a non zero path and of
2216          even length (FID are two bytes each). */
2217       if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
2218           ||  !objlen || (objlen & 1) )
2219         {
2220           errstr = "invalid path reference";
2221           goto parse_error;
2222         }
2223
2224       /* Create a new PuKDF list item. */
2225       pukdf = xtrycalloc (1, (sizeof *pukdf
2226                               - sizeof(unsigned short)
2227                               + objlen/2 * sizeof(unsigned short)));
2228       if (!pukdf)
2229         {
2230           err = gpg_error_from_syserror ();
2231           goto leave;
2232         }
2233       pukdf->objidlen = objidlen;
2234       pukdf->objid = objid;
2235       objid = NULL;
2236       if (authid)
2237         {
2238           pukdf->authidlen = authidlen;
2239           pukdf->authid = authid;
2240           authid = NULL;
2241         }
2242       if (label)
2243         {
2244           pukdf->label = label;
2245           label = NULL;
2246         }
2247
2248       pukdf->pathlen = objlen/2;
2249       for (i=0; i < pukdf->pathlen; i++, pp += 2, nn -= 2)
2250         pukdf->path[i] = ((pp[0] << 8) | pp[1]);
2251
2252       pukdf->usageflags = usageflags;
2253       pukdf->accessflags = accessflags;
2254       pukdf->key_reference = key_reference;
2255       pukdf->key_reference_valid = key_reference_valid;
2256
2257       if (nn)
2258         {
2259           /* An index and length follows. */
2260           pukdf->have_off = 1;
2261           where = __LINE__;
2262           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2263                                   &ndef, &objlen, &hdrlen);
2264           if (!err && (objlen > nn
2265                        || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
2266             err = gpg_error (GPG_ERR_INV_OBJ);
2267           if (err)
2268             goto parse_error;
2269
2270           for (ul=0; objlen; objlen--)
2271             {
2272               ul <<= 8;
2273               ul |= (*pp++) & 0xff;
2274               nn--;
2275             }
2276           pukdf->off = ul;
2277
2278           where = __LINE__;
2279           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2280                                   &ndef, &objlen, &hdrlen);
2281           if (!err && (objlen > nn
2282                        || class != CLASS_CONTEXT || tag != 0))
2283             err = gpg_error (GPG_ERR_INV_OBJ);
2284           if (err)
2285             goto parse_error;
2286
2287           for (ul=0; objlen; objlen--)
2288             {
2289               ul <<= 8;
2290               ul |= (*pp++) & 0xff;
2291               nn--;
2292             }
2293           pukdf->len = ul;
2294         }
2295
2296
2297       if (opt.verbose)
2298         {
2299           log_info ("p15: PuKDF %04hX: id=", fid);
2300           for (i=0; i < pukdf->objidlen; i++)
2301             log_printf ("%02X", pukdf->objid[i]);
2302           if (pukdf->label)
2303             log_printf (" (%s)", pukdf->label);
2304           log_info ("p15:             path=");
2305           for (i=0; i < pukdf->pathlen; i++)
2306             log_printf ("%s%04hX", i?"/":"",pukdf->path[i]);
2307           if (pukdf->have_off)
2308             log_printf ("[%lu/%lu]", pukdf->off, pukdf->len);
2309           if (pukdf->authid)
2310             {
2311               log_printf (" authid=");
2312               for (i=0; i < pukdf->authidlen; i++)
2313                 log_printf ("%02X", pukdf->authid[i]);
2314             }
2315           if (pukdf->key_reference_valid)
2316             log_printf (" keyref=0x%02lX", pukdf->key_reference);
2317           if (pukdf->accessflags.any)
2318             dump_keyaccess_flags (pukdf->accessflags);
2319           dump_keyusage_flags (pukdf->usageflags);
2320           log_printf ("\n");
2321         }
2322
2323       /* Put it into the list. */
2324       pukdf->next = pukdflist;
2325       pukdflist = pukdf;
2326       pukdf = NULL;
2327       goto next_record; /* Ready with this record. */
2328
2329     parse_error:
2330       log_error ("p15: error parsing PuKDF record at %d: %s - skipped\n",
2331                  where, errstr? errstr : gpg_strerror (err));
2332       if (pukdf)
2333         {
2334           xfree (pukdf->objid);
2335           xfree (pukdf->authid);
2336           xfree (pukdf->label);
2337           xfree (pukdf);
2338         }
2339       err = 0;
2340
2341     next_record:
2342       /* If the card uses a record oriented file structure, read the
2343        * next record.  Otherwise we keep on parsing the current buffer.  */
2344       recno++;
2345       if (record_mode)
2346         {
2347           xfree (buffer); buffer = NULL;
2348           err = select_and_read_record (app, 0, recno, "PuKDF",
2349                                         &buffer, &buflen, NULL);
2350           if (err) {
2351             if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2352               err = 0;
2353             goto leave;
2354           }
2355           p = buffer;
2356           n = buflen;
2357         }
2358     } /* End looping over all records. */
2359
2360  leave:
2361   xfree (authid);
2362   xfree (label);
2363   xfree (objid);
2364   xfree (buffer);
2365   if (err)
2366     release_pukdflist (pukdflist);
2367   else
2368     *result = pukdflist;
2369   return err;
2370 }
2371
2372
2373 /* Read and parse the Certificate Directory Files identified by FID.
2374    On success a newlist of CDF object gets stored at RESULT and the
2375    caller is then responsible of releasing this list.  On error a
2376    error code is returned and RESULT won't get changed.  */
2377 static gpg_error_t
2378 read_ef_cdf (app_t app, unsigned short fid, int cdftype, cdf_object_t *result)
2379 {
2380   gpg_error_t err;
2381   unsigned char *buffer;
2382   size_t buflen;
2383   const unsigned char *p;
2384   size_t n, objlen, hdrlen;
2385   int class, tag, constructed, ndef;
2386   cdf_object_t cdflist = NULL;
2387   int i;
2388   int recno = 1;
2389   unsigned char *authid = NULL;
2390   size_t authidlen = 0;
2391   char *label = NULL;
2392   int record_mode;
2393
2394   err = read_first_record (app, fid, "CDF", &buffer, &buflen, &record_mode);
2395   if (err)
2396     return err;
2397
2398   p = buffer;
2399   n = buflen;
2400
2401   /* Loop over the records.  We stop as soon as we detect a new record
2402      starting with 0x00 or 0xff as these values are commonly used to
2403      pad data blocks and are no valid ASN.1 encoding.  Note the
2404      special handling for record mode at the end of the loop. */
2405   while (n && *p && *p != 0xff)
2406     {
2407       const unsigned char *pp;
2408       size_t nn;
2409       int where;
2410       const char *errstr = NULL;
2411       cdf_object_t cdf = NULL;
2412       unsigned long ul;
2413       const unsigned char *objid;
2414       size_t objidlen;
2415
2416       err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2417                               &ndef, &objlen, &hdrlen);
2418       if (!err && (objlen > n || tag != TAG_SEQUENCE))
2419         err = gpg_error (GPG_ERR_INV_OBJ);
2420       if (err)
2421         {
2422           log_error ("p15: error parsing CDF record: %s\n", gpg_strerror (err));
2423           goto leave;
2424         }
2425       pp = p;
2426       nn = objlen;
2427       p += objlen;
2428       n -= objlen;
2429
2430       /* Parse the commonObjectAttributes.  */
2431       where = __LINE__;
2432       xfree (authid);
2433       xfree (label);
2434       err = parse_common_obj_attr (&pp, &nn, &authid, &authidlen, &label);
2435       if (err)
2436         goto parse_error;
2437
2438       /* Parse the commonCertificateAttributes.  */
2439       where = __LINE__;
2440       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2441                               &ndef, &objlen, &hdrlen);
2442       if (!err && (objlen > nn || tag != TAG_SEQUENCE))
2443         err = gpg_error (GPG_ERR_INV_OBJ);
2444       if (err)
2445         goto parse_error;
2446       {
2447         const unsigned char *ppp = pp;
2448         size_t nnn = objlen;
2449
2450         pp += objlen;
2451         nn -= objlen;
2452
2453         /* Get the Id. */
2454         where = __LINE__;
2455         err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
2456                               &ndef, &objlen, &hdrlen);
2457         if (!err && (objlen > nnn
2458                      || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
2459           err = gpg_error (GPG_ERR_INV_OBJ);
2460         if (err)
2461           goto parse_error;
2462         objid = ppp;
2463         objidlen = objlen;
2464       }
2465
2466       /* Parse the certAttribute.  */
2467       where = __LINE__;
2468       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2469                               &ndef, &objlen, &hdrlen);
2470       if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
2471         err = gpg_error (GPG_ERR_INV_OBJ);
2472       if (err)
2473         goto parse_error;
2474       nn = objlen;
2475
2476       where = __LINE__;
2477       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2478                               &ndef, &objlen, &hdrlen);
2479       if (!err && (objlen > nn
2480                    || class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE))
2481         err = gpg_error (GPG_ERR_INV_OBJ);
2482       if (err)
2483         goto parse_error;
2484       nn = objlen;
2485
2486       /* Check that the reference is a Path object.  */
2487       where = __LINE__;
2488       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2489                               &ndef, &objlen, &hdrlen);
2490       if (!err && objlen > nn)
2491         err = gpg_error (GPG_ERR_INV_OBJ);
2492       if (err)
2493         goto parse_error;
2494       if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
2495         {
2496           errstr = "unsupported reference type";
2497           goto parse_error;
2498         }
2499       nn = objlen;
2500
2501       /* Parse the Path object. */
2502       where = __LINE__;
2503       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2504                               &ndef, &objlen, &hdrlen);
2505       if (!err && objlen > nn)
2506         err = gpg_error (GPG_ERR_INV_OBJ);
2507       if (err)
2508         goto parse_error;
2509
2510       /* Make sure that the next element is a non zero path and of
2511          even length (FID are two bytes each). */
2512       if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
2513           ||  !objlen || (objlen & 1) )
2514         {
2515           errstr = "invalid path reference";
2516           goto parse_error;
2517         }
2518       /* Create a new CDF list item. */
2519       cdf = xtrycalloc (1, (sizeof *cdf
2520                             - sizeof(unsigned short)
2521                             + objlen/2 * sizeof(unsigned short)));
2522       if (!cdf)
2523         {
2524           err = gpg_error_from_syserror ();
2525           goto leave;
2526         }
2527       if (authid)
2528         {
2529           cdf->authidlen = authidlen;
2530           cdf->authid = authid;
2531           authid = NULL;
2532         }
2533       if (label)
2534         {
2535           cdf->label = label;
2536           label = NULL;
2537         }
2538
2539       cdf->objidlen = objidlen;
2540       cdf->objid = xtrymalloc (objidlen);
2541       if (!cdf->objid)
2542         {
2543           err = gpg_error_from_syserror ();
2544           xfree (cdf);
2545           goto leave;
2546         }
2547       memcpy (cdf->objid, objid, objidlen);
2548
2549       cdf->pathlen = objlen/2;
2550       for (i=0; i < cdf->pathlen; i++, pp += 2, nn -= 2)
2551         cdf->path[i] = ((pp[0] << 8) | pp[1]);
2552
2553       if (nn)
2554         {
2555           /* An index and length follows. */
2556           cdf->have_off = 1;
2557           where = __LINE__;
2558           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2559                                   &ndef, &objlen, &hdrlen);
2560           if (!err && (objlen > nn
2561                        || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
2562             err = gpg_error (GPG_ERR_INV_OBJ);
2563           if (err)
2564             goto parse_error;
2565
2566           for (ul=0; objlen; objlen--)
2567             {
2568               ul <<= 8;
2569               ul |= (*pp++) & 0xff;
2570               nn--;
2571             }
2572           cdf->off = ul;
2573
2574           where = __LINE__;
2575           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2576                                   &ndef, &objlen, &hdrlen);
2577           if (!err && (objlen > nn
2578                        || class != CLASS_CONTEXT || tag != 0))
2579             err = gpg_error (GPG_ERR_INV_OBJ);
2580           if (err)
2581             goto parse_error;
2582
2583           for (ul=0; objlen; objlen--)
2584             {
2585               ul <<= 8;
2586               ul |= (*pp++) & 0xff;
2587               nn--;
2588             }
2589           cdf->len = ul;
2590         }
2591
2592       if (opt.verbose)
2593         {
2594           log_info ("p15: CDF-%c %04hX: id=", cdftype, fid);
2595           for (i=0; i < cdf->objidlen; i++)
2596             log_printf ("%02X", cdf->objid[i]);
2597           if (cdf->label)
2598             log_printf (" (%s)", cdf->label);
2599           log_info ("p15:             path=");
2600           for (i=0; i < cdf->pathlen; i++)
2601             log_printf ("%s%04hX", i?"/":"", cdf->path[i]);
2602           if (cdf->have_off)
2603             log_printf ("[%lu/%lu]", cdf->off, cdf->len);
2604           if (cdf->authid)
2605             {
2606               log_printf (" authid=");
2607               for (i=0; i < cdf->authidlen; i++)
2608                 log_printf ("%02X", cdf->authid[i]);
2609             }
2610           log_printf ("\n");
2611         }
2612
2613       /* Put it into the list. */
2614       cdf->next = cdflist;
2615       cdflist = cdf;
2616       cdf = NULL;
2617       goto next_record; /* Ready with this record. */
2618
2619     parse_error:
2620       log_error ("p15: error parsing CDF record at %d: %s - skipped\n",
2621                  where, errstr? errstr : gpg_strerror (err));
2622       xfree (cdf);
2623       err = 0;
2624
2625     next_record:
2626       xfree (authid);
2627       xfree (label);
2628       /* If the card uses a record oriented file structure, read the
2629        * next record.  Otherwise we keep on parsing the current buffer.  */
2630       recno++;
2631       if (record_mode)
2632         {
2633           xfree (buffer); buffer = NULL;
2634           err = select_and_read_record (app, 0, recno, "CDF",
2635                                         &buffer, &buflen, NULL);
2636           if (err) {
2637             if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2638               err = 0;
2639             goto leave;
2640           }
2641           p = buffer;
2642           n = buflen;
2643         }
2644     } /* End loop over all records. */
2645
2646  leave:
2647   xfree (authid);
2648   xfree (label);
2649   xfree (buffer);
2650   if (err)
2651     release_cdflist (cdflist);
2652   else
2653     *result = cdflist;
2654   return err;
2655 }
2656
2657
2658 /*
2659  * SEQUENCE {
2660  *   SEQUENCE { -- CommonObjectAttributes
2661  *     UTF8String 'specific PIN for DS'
2662  *     BIT STRING 0 unused bits
2663  *       '00000011'B
2664  *     }
2665  *   SEQUENCE { -- CommonAuthenticationObjectAttributes
2666  *     OCTET STRING
2667  *       07    -- iD
2668  *     }
2669  *
2670  *   [1] { -- typeAttributes
2671  *     SEQUENCE { -- PinAttributes
2672  *       BIT STRING 0 unused bits
2673  *         '0000100000110010'B  -- local,initialized,needs-padding
2674  *                              -- exchangeRefData
2675  *       ENUMERATED 1           -- ascii-numeric
2676  *       INTEGER 6              -- minLength
2677  *       INTEGER 6              -- storedLength
2678  *       INTEGER 8              -- maxLength
2679  *       [0]
2680  *         02                   -- pinReference
2681  *       GeneralizedTime 19/04/2002 12:12 GMT  -- lastPinChange
2682  *       SEQUENCE {
2683  *         OCTET STRING
2684  *           3F 00 40 16        -- path to DF of PIN
2685  *         }
2686  *       }
2687  *     }
2688  *   }
2689  *
2690  * Or for an authKey:
2691  *
2692  *   [1] { -- typeAttributes
2693  *     SEQUENCE { -- AuthKeyAttributes
2694  *       BOOLEAN TRUE    -- derivedKey
2695  *       OCTET STRING 02 -- authKeyId
2696  *       }
2697  *     }
2698  *   }
2699 */
2700 /* Read and parse an Authentication Object Directory File identified
2701    by FID.  On success a newlist of AODF objects gets stored at RESULT
2702    and the caller is responsible of releasing this list.  On error a
2703    error code is returned and RESULT won't get changed.  */
2704 static gpg_error_t
2705 read_ef_aodf (app_t app, unsigned short fid, aodf_object_t *result)
2706 {
2707   gpg_error_t err;
2708   unsigned char *buffer;
2709   size_t buflen;
2710   const unsigned char *p;
2711   size_t n, objlen, hdrlen;
2712   int class, tag, constructed, ndef;
2713   aodf_object_t aodflist = NULL;
2714   int i;
2715   int recno = 1;
2716   int record_mode;
2717
2718   err = read_first_record (app, fid, "AODF", &buffer, &buflen, &record_mode);
2719   if (err)
2720     return err;
2721
2722   p = buffer;
2723   n = buflen;
2724
2725   /* Loop over the records.  We stop as soon as we detect a new record
2726      starting with 0x00 or 0xff as these values are commonly used to
2727      pad data blocks and are no valid ASN.1 encoding.  Note the
2728      special handling for record mode at the end of the loop.  */
2729   while (n && *p && *p != 0xff)
2730     {
2731       const unsigned char *pp;
2732       size_t nn;
2733       int where;
2734       const char *errstr = NULL;
2735       auth_type_t auth_type;
2736       aodf_object_t aodf = NULL;
2737       unsigned long ul;
2738       const char *s;
2739
2740       where = __LINE__;
2741       err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2742                               &ndef, &objlen, &hdrlen);
2743       if (err)
2744         ;
2745       else if (objlen > n)
2746         err = gpg_error (GPG_ERR_INV_OBJ);
2747       else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
2748         auth_type = AUTH_TYPE_PIN;    /* PinAttributes */
2749       else if (class == CLASS_CONTEXT && tag == 1 )
2750         auth_type = AUTH_TYPE_AUTHKEY; /* AuthKeyAttributes */
2751       else if (class == CLASS_CONTEXT)
2752         {
2753           switch (tag)
2754             {
2755             case 0: errstr = "biometric auth types are not supported"; break;
2756             case 2: errstr = "external auth type are not supported"; break;
2757             default: errstr = "unknown privateKeyObject"; break;
2758             }
2759           goto parse_error;
2760         }
2761       else
2762         {
2763           err = gpg_error (GPG_ERR_INV_OBJ);
2764           goto parse_error;
2765         }
2766
2767       if (err)
2768         {
2769           log_error ("p15: error parsing AODF record: %s\n",
2770                      gpg_strerror (err));
2771           goto leave;
2772         }
2773       pp = p;
2774       nn = objlen;
2775       p += objlen;
2776       n -= objlen;
2777
2778       /* Allocate memory for a new AODF list item. */
2779       aodf = xtrycalloc (1, sizeof *aodf);
2780       if (!aodf)
2781         goto no_core;
2782       aodf->fid = fid;
2783       aodf->auth_type = auth_type;
2784
2785       /* Parse the commonObjectAttributes.  */
2786       where = __LINE__;
2787       err = parse_common_obj_attr (&pp, &nn, &aodf->authid, &aodf->authidlen,
2788                                    &aodf->label);
2789       if (err)
2790         goto parse_error;
2791
2792       /* Parse the CommonAuthenticationObjectAttributes.  */
2793       where = __LINE__;
2794       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2795                               &ndef, &objlen, &hdrlen);
2796       if (!err && (objlen > nn || tag != TAG_SEQUENCE))
2797         err = gpg_error (GPG_ERR_INV_OBJ);
2798       if (err)
2799         goto parse_error;
2800       {
2801         const unsigned char *ppp = pp;
2802         size_t nnn = objlen;
2803
2804         pp += objlen;
2805         nn -= objlen;
2806
2807         /* Get the Id. */
2808         where = __LINE__;
2809         err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
2810                                 &ndef, &objlen, &hdrlen);
2811         if (!err && (objlen > nnn
2812                      || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
2813           err = gpg_error (GPG_ERR_INV_OBJ);
2814         if (err)
2815           goto parse_error;
2816
2817         aodf->objidlen = objlen;
2818         aodf->objid = xtrymalloc (objlen);
2819         if (!aodf->objid)
2820           goto no_core;
2821         memcpy (aodf->objid, ppp, objlen);
2822       }
2823
2824       /* Parse the typeAttributes.  */
2825       where = __LINE__;
2826       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2827                               &ndef, &objlen, &hdrlen);
2828       if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
2829         err = gpg_error (GPG_ERR_INV_OBJ);
2830       if (err)
2831         goto parse_error;
2832       nn = objlen;
2833
2834       where = __LINE__;
2835       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2836                               &ndef, &objlen, &hdrlen);
2837       if (err)
2838         ;
2839       else if (!err && objlen > nn)
2840         err = gpg_error (GPG_ERR_INV_OBJ);
2841       else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
2842         ; /* Okay */
2843       else
2844         err = gpg_error (GPG_ERR_INV_OBJ);
2845       if (err)
2846         goto parse_error;
2847
2848       nn = objlen;
2849
2850       if (auth_type == AUTH_TYPE_PIN)
2851         {
2852           /* PinFlags */
2853           where = __LINE__;
2854           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2855                                   &ndef, &objlen, &hdrlen);
2856           if (!err && (objlen > nn || !objlen
2857                        || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
2858             err = gpg_error (GPG_ERR_INV_OBJ);
2859           if (err)
2860             goto parse_error;
2861
2862           {
2863             unsigned int bits, mask;
2864             int unused, full;
2865
2866             unused = *pp++; nn--; objlen--;
2867             if ((!objlen && unused) || unused/8 > objlen)
2868               {
2869                 err = gpg_error (GPG_ERR_ENCODING_PROBLEM);
2870                 goto parse_error;
2871               }
2872             full = objlen - (unused+7)/8;
2873             unused %= 8;
2874             mask = 0;
2875             for (i=1; unused; i <<= 1, unused--)
2876               mask |= i;
2877
2878             /* The first octet */
2879             bits = 0;
2880             if (objlen)
2881               {
2882                 bits = *pp++; nn--; objlen--;
2883                 if (full)
2884                   full--;
2885                 else
2886                   {
2887                     bits &= ~mask;
2888                     mask = 0;
2889                   }
2890               }
2891             if ((bits & 0x80)) /* ASN.1 bit 0. */
2892               aodf->pinflags.case_sensitive = 1;
2893             if ((bits & 0x40)) /* ASN.1 bit 1. */
2894               aodf->pinflags.local = 1;
2895             if ((bits & 0x20))
2896               aodf->pinflags.change_disabled = 1;
2897             if ((bits & 0x10))
2898               aodf->pinflags.unblock_disabled = 1;
2899             if ((bits & 0x08))
2900               aodf->pinflags.initialized = 1;
2901             if ((bits & 0x04))
2902               aodf->pinflags.needs_padding = 1;
2903             if ((bits & 0x02))
2904               aodf->pinflags.unblocking_pin = 1;
2905             if ((bits & 0x01))
2906               aodf->pinflags.so_pin = 1;
2907             /* The second octet. */
2908             bits = 0;
2909             if (objlen)
2910               {
2911                 bits = *pp++; nn--; objlen--;
2912                 if (full)
2913                   full--;
2914                 else
2915                   {
2916                     bits &= ~mask;
2917                   }
2918               }
2919             if ((bits & 0x80))
2920               aodf->pinflags.disable_allowed = 1;
2921             if ((bits & 0x40))
2922               aodf->pinflags.integrity_protected = 1;
2923             if ((bits & 0x20))
2924               aodf->pinflags.confidentiality_protected = 1;
2925             if ((bits & 0x10))
2926               aodf->pinflags.exchange_ref_data = 1;
2927             /* Skip remaining bits. */
2928             pp += objlen;
2929             nn -= objlen;
2930           }
2931
2932           /* PinType */
2933           where = __LINE__;
2934           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2935                                   &ndef, &objlen, &hdrlen);
2936           if (!err && (objlen > nn
2937                        || class != CLASS_UNIVERSAL || tag != TAG_ENUMERATED))
2938             err = gpg_error (GPG_ERR_INV_OBJ);
2939           if (!err && objlen > sizeof (ul))
2940             err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
2941           if (err)
2942             goto parse_error;
2943
2944           for (ul=0; objlen; objlen--)
2945             {
2946               ul <<= 8;
2947               ul |= (*pp++) & 0xff;
2948               nn--;
2949             }
2950           aodf->pintype = ul;
2951
2952           /* minLength */
2953           where = __LINE__;
2954           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2955                                   &ndef, &objlen, &hdrlen);
2956           if (!err && (objlen > nn
2957                        || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
2958             err = gpg_error (GPG_ERR_INV_OBJ);
2959           if (!err && objlen > sizeof (ul))
2960             err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
2961           if (err)
2962             goto parse_error;
2963           for (ul=0; objlen; objlen--)
2964             {
2965               ul <<= 8;
2966               ul |= (*pp++) & 0xff;
2967               nn--;
2968             }
2969           aodf->min_length = ul;
2970
2971           /* storedLength */
2972           where = __LINE__;
2973           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2974                                   &ndef, &objlen, &hdrlen);
2975           if (!err && (objlen > nn
2976                        || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
2977             err = gpg_error (GPG_ERR_INV_OBJ);
2978           if (!err && objlen > sizeof (ul))
2979             err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
2980           if (err)
2981             goto parse_error;
2982           for (ul=0; objlen; objlen--)
2983             {
2984               ul <<= 8;
2985               ul |= (*pp++) & 0xff;
2986               nn--;
2987             }
2988           aodf->stored_length = ul;
2989
2990           /* optional maxLength */
2991           where = __LINE__;
2992           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2993                                   &ndef, &objlen, &hdrlen);
2994           if (gpg_err_code (err) == GPG_ERR_EOF)
2995             goto ready;
2996           if (!err && objlen > nn)
2997             err = gpg_error (GPG_ERR_INV_OBJ);
2998           if (err)
2999             goto parse_error;
3000           if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
3001             {
3002               if (objlen > sizeof (ul))
3003                 {
3004                   err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
3005                   goto parse_error;
3006                 }
3007               for (ul=0; objlen; objlen--)
3008                 {
3009                   ul <<= 8;
3010                   ul |= (*pp++) & 0xff;
3011                   nn--;
3012                 }
3013               aodf->max_length = ul;
3014               aodf->max_length_valid = 1;
3015
3016               where = __LINE__;
3017               err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
3018                                       &ndef, &objlen, &hdrlen);
3019               if (gpg_err_code (err) == GPG_ERR_EOF)
3020                 goto ready;
3021               if (!err && objlen > nn)
3022                 err = gpg_error (GPG_ERR_INV_OBJ);
3023               if (err)
3024                 goto parse_error;
3025             }
3026
3027           /* Optional pinReference. */
3028           if (class == CLASS_CONTEXT && tag == 0)
3029             {
3030               if (objlen > sizeof (ul))
3031                 {
3032                   err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
3033                   goto parse_error;
3034                 }
3035               for (ul=0; objlen; objlen--)
3036                 {
3037                   ul <<= 8;
3038                   ul |= (*pp++) & 0xff;
3039                   nn--;
3040                 }
3041               aodf->pin_reference = ul;
3042               aodf->pin_reference_valid = 1;
3043
3044               where = __LINE__;
3045               err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
3046                                       &ndef, &objlen, &hdrlen);
3047               if (gpg_err_code (err) == GPG_ERR_EOF)
3048                 goto ready;
3049               if (!err && objlen > nn)
3050                 err = gpg_error (GPG_ERR_INV_OBJ);
3051               if (err)
3052                 goto parse_error;
3053             }
3054
3055           /* Optional padChar. */
3056           if (class == CLASS_UNIVERSAL && tag == TAG_OCTET_STRING)
3057             {
3058               if (objlen != 1)
3059                 {
3060                   errstr = "padChar is not of size(1)";
3061                   goto parse_error;
3062                 }
3063               aodf->pad_char = *pp++; nn--;
3064               aodf->pad_char_valid = 1;
3065
3066               where = __LINE__;
3067               err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
3068                                       &ndef, &objlen, &hdrlen);
3069               if (gpg_err_code (err) == GPG_ERR_EOF)
3070                 goto ready;
3071               if (!err && objlen > nn)
3072                 err = gpg_error (GPG_ERR_INV_OBJ);
3073               if (err)
3074                 goto parse_error;
3075             }
3076
3077           /* Skip optional lastPinChange. */
3078           if (class == CLASS_UNIVERSAL && tag == TAG_GENERALIZED_TIME)
3079             {
3080               pp += objlen;
3081               nn -= objlen;
3082
3083               where = __LINE__;
3084               err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
3085                                       &ndef, &objlen, &hdrlen);
3086               if (gpg_err_code (err) == GPG_ERR_EOF)
3087                 goto ready;
3088               if (!err && objlen > nn)
3089                 err = gpg_error (GPG_ERR_INV_OBJ);
3090               if (err)
3091                 goto parse_error;
3092             }
3093
3094           /* Optional Path object.  */
3095           if (class == CLASS_UNIVERSAL || tag == TAG_SEQUENCE)
3096             {
3097               const unsigned char *ppp = pp;
3098               size_t nnn = objlen;
3099
3100               pp += objlen;
3101               nn -= objlen;
3102
3103               where = __LINE__;
3104               err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
3105                                       &ndef, &objlen, &hdrlen);
3106               if (!err && objlen > nnn)
3107                 err = gpg_error (GPG_ERR_INV_OBJ);
3108               if (err)
3109                 goto parse_error;
3110
3111               /* Make sure that the next element has a path of even
3112                * length (FIDs are two bytes each).  */
3113               if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
3114                   || (objlen & 1) )
3115                 {
3116                   errstr = "invalid path reference";
3117                   goto parse_error;
3118                 }
3119
3120               aodf->pathlen = objlen/2;
3121               aodf->path = xtrycalloc (aodf->pathlen, sizeof *aodf->path);
3122               if (!aodf->path)
3123                 goto no_core;
3124               for (i=0; i < aodf->pathlen; i++, ppp += 2, nnn -= 2)
3125                 aodf->path[i] = ((ppp[0] << 8) | ppp[1]);
3126
3127               if (nnn)
3128                 {
3129                   /* An index and length follows. */
3130                   aodf->have_off = 1;
3131                   where = __LINE__;
3132                   err = parse_ber_header (&ppp, &nnn, &class, &tag,
3133                                           &constructed,
3134                                           &ndef, &objlen, &hdrlen);
3135                   if (!err && (objlen > nnn
3136                                || class != CLASS_UNIVERSAL
3137                                || tag != TAG_INTEGER))
3138                     err = gpg_error (GPG_ERR_INV_OBJ);
3139                   if (err)
3140                     goto parse_error;
3141
3142                   for (ul=0; objlen; objlen--)
3143                     {
3144                       ul <<= 8;
3145                       ul |= (*ppp++) & 0xff;
3146                       nnn--;
3147                     }
3148                   aodf->off = ul;
3149
3150                   where = __LINE__;
3151                   err = parse_ber_header (&ppp, &nnn, &class, &tag,
3152                                           &constructed,
3153                                           &ndef, &objlen, &hdrlen);
3154                   if (!err && (objlen > nnn
3155                                || class != CLASS_CONTEXT || tag != 0))
3156                     err = gpg_error (GPG_ERR_INV_OBJ);
3157                   if (err)
3158                     goto parse_error;
3159
3160                   for (ul=0; objlen; objlen--)
3161                     {
3162                       ul <<= 8;
3163                       ul |= (*ppp++) & 0xff;
3164                       nnn--;
3165                     }
3166                   aodf->len = ul;
3167                 }
3168             }
3169         }
3170       else if (auth_type == AUTH_TYPE_AUTHKEY)
3171         {
3172
3173         }
3174
3175       /* Ignore further objects which might be there due to future
3176          extensions of pkcs#15. */
3177
3178     ready:
3179       if (gpg_err_code (err) == GPG_ERR_EOF)
3180         err = 0;
3181       if (opt.verbose)
3182         {
3183           log_info ("p15: AODF %04hX:  id=", fid);
3184           for (i=0; i < aodf->objidlen; i++)
3185             log_printf ("%02X", aodf->objid[i]);
3186           if (aodf->label)
3187             log_printf (" (%s)", aodf->label);
3188           log_info ("p15:            ");
3189           log_printf (" %s",
3190                       aodf->auth_type == AUTH_TYPE_PIN? "pin" :
3191                       aodf->auth_type == AUTH_TYPE_AUTHKEY? "authkey" : "?");
3192           if (aodf->pathlen)
3193             {
3194               log_printf (" path=");
3195               for (i=0; i < aodf->pathlen; i++)
3196                 log_printf ("%s%04hX", i?"/":"",aodf->path[i]);
3197               if (aodf->have_off)
3198                 log_printf ("[%lu/%lu]", aodf->off, aodf->len);
3199             }
3200           if (aodf->authid)
3201             {
3202               log_printf (" authid=");
3203               for (i=0; i < aodf->authidlen; i++)
3204                 log_printf ("%02X", aodf->authid[i]);
3205             }
3206           if (aodf->auth_type == AUTH_TYPE_PIN)
3207             {
3208               if (aodf->pin_reference_valid)
3209                 log_printf (" pinref=0x%02lX", aodf->pin_reference);
3210               log_printf (" min=%lu", aodf->min_length);
3211               log_printf (" stored=%lu", aodf->stored_length);
3212               if (aodf->max_length_valid)
3213                 log_printf (" max=%lu", aodf->max_length);
3214               if (aodf->pad_char_valid)
3215                 log_printf (" pad=0x%02x", aodf->pad_char);
3216
3217               log_info ("p15:             flags=");
3218               s = "";
3219               if (aodf->pinflags.case_sensitive)
3220                 log_printf ("%scase_sensitive", s), s = ",";
3221               if (aodf->pinflags.local)
3222                 log_printf ("%slocal", s), s = ",";
3223               if (aodf->pinflags.change_disabled)
3224                 log_printf ("%schange_disabled", s), s = ",";
3225               if (aodf->pinflags.unblock_disabled)
3226                 log_printf ("%sunblock_disabled", s), s = ",";
3227               if (aodf->pinflags.initialized)
3228                 log_printf ("%sinitialized", s), s = ",";
3229               if (aodf->pinflags.needs_padding)
3230                 log_printf ("%sneeds_padding", s), s = ",";
3231               if (aodf->pinflags.unblocking_pin)
3232                 log_printf ("%sunblocking_pin", s), s = ",";
3233               if (aodf->pinflags.so_pin)
3234                 log_printf ("%sso_pin", s), s = ",";
3235               if (aodf->pinflags.disable_allowed)
3236                 log_printf ("%sdisable_allowed", s), s = ",";
3237               if (aodf->pinflags.integrity_protected)
3238                 log_printf ("%sintegrity_protected", s), s = ",";
3239               if (aodf->pinflags.confidentiality_protected)
3240                 log_printf ("%sconfidentiality_protected", s), s = ",";
3241               if (aodf->pinflags.exchange_ref_data)
3242                 log_printf ("%sexchange_ref_data", s), s = ",";
3243               {
3244                 char numbuf[50];
3245                 const char *s2;
3246
3247                 switch (aodf->pintype)
3248                   {
3249                   case PIN_TYPE_BCD: s2 = "bcd"; break;
3250                   case PIN_TYPE_ASCII_NUMERIC: s2 = "ascii-numeric"; break;
3251                   case PIN_TYPE_UTF8: s2 = "utf8"; break;
3252                   case PIN_TYPE_HALF_NIBBLE_BCD: s2 = "half-nibble-bcd"; break;
3253                   case PIN_TYPE_ISO9564_1: s2 = "iso9564-1"; break;
3254                   default:
3255                     sprintf (numbuf, "%lu", (unsigned long)aodf->pintype);
3256                     s2 = numbuf;
3257                   }
3258                 log_printf ("%stype=%s", s, s2); s = ",";
3259               }
3260             }
3261           else if (aodf->auth_type == AUTH_TYPE_AUTHKEY)
3262             {
3263             }
3264           log_printf ("\n");
3265         }
3266
3267       /* Put it into the list. */
3268       aodf->next = aodflist;
3269       aodflist = aodf;
3270       aodf = NULL;
3271       goto next_record; /* Ready with this record. */
3272
3273     no_core:
3274       err = gpg_error_from_syserror ();
3275       release_aodf_object (aodf);
3276       goto leave;
3277
3278     parse_error:
3279       log_error ("p15: error parsing AODF record at %d: %s - skipped\n",
3280                  where, errstr? errstr : gpg_strerror (err));
3281       err = 0;
3282       release_aodf_object (aodf);
3283
3284     next_record:
3285       /* If the card uses a record oriented file structure, read the
3286        * next record.  Otherwise we keep on parsing the current buffer.  */
3287       recno++;
3288       if (record_mode)
3289         {
3290           xfree (buffer); buffer = NULL;
3291           err = select_and_read_record (app, 0, recno, "AODF",
3292                                         &buffer, &buflen, NULL);
3293           if (err) {
3294             if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
3295               err = 0;
3296             goto leave;
3297           }
3298           p = buffer;
3299           n = buflen;
3300         }
3301     } /* End looping over all records. */
3302
3303  leave:
3304   xfree (buffer);
3305   if (err)
3306     release_aodflist (aodflist);
3307   else
3308     *result = aodflist;
3309   return err;
3310 }
3311
3312
3313 /* Print the BIT STRING with the tokenflags from the TokenInfo.  */
3314 static void
3315 print_tokeninfo_tokenflags (const unsigned char *der, size_t derlen)
3316 {
3317   unsigned int bits, mask;
3318   int i, unused, full;
3319   int other = 0;
3320
3321   if (!derlen)
3322     {
3323       log_printf (" [invalid object]");
3324       return;
3325     }
3326
3327   unused = *der++; derlen--;
3328   if ((!derlen && unused) || unused/8 > derlen)
3329     {
3330       log_printf (" [wrong encoding]");
3331       return;
3332     }
3333   full = derlen - (unused+7)/8;
3334   unused %= 8;
3335   mask = 0;
3336   for (i=1; unused; i <<= 1, unused--)
3337     mask |= i;
3338
3339   /* First octet */
3340   if (derlen)
3341     {
3342       bits = *der++; derlen--;
3343       if (full)
3344         full--;
3345       else
3346         {
3347           bits &= ~mask;
3348           mask = 0;
3349         }
3350     }
3351   else
3352     bits = 0;
3353   if ((bits & 0x80)) log_printf (" readonly");
3354   if ((bits & 0x40)) log_printf (" loginRequired");
3355   if ((bits & 0x20)) log_printf (" prnGeneration");
3356   if ((bits & 0x10)) log_printf (" eidCompliant");
3357   if ((bits & 0x08)) other = 1;
3358   if ((bits & 0x04)) other = 1;
3359   if ((bits & 0x02)) other = 1;
3360   if ((bits & 0x01)) other = 1;
3361
3362   /* Next octet.  */
3363   if (derlen)
3364     other = 1;
3365
3366   if (other)
3367     log_printf (" [unknown]");
3368 }
3369
3370
3371
3372 /* Read and parse the EF(TokenInfo).
3373  *
3374  * TokenInfo ::= SEQUENCE {
3375  *     version          INTEGER {v1(0)} (v1,...),
3376  *     serialNumber     OCTET STRING,
3377  *     manufacturerID   Label OPTIONAL,
3378  *     label            [0] Label OPTIONAL,
3379  *     tokenflags               TokenFlags,
3380  *     seInfo           SEQUENCE OF SecurityEnvironmentInfo OPTIONAL,
3381  *     recordInfo               [1] RecordInfo OPTIONAL,
3382  *     supportedAlgorithms      [2] SEQUENCE OF AlgorithmInfo OPTIONAL,
3383  *     ...,
3384  *     issuerId         [3] Label OPTIONAL,
3385  *     holderId         [4] Label OPTIONAL,
3386  *     lastUpdate               [5] LastUpdate OPTIONAL,
3387  *     preferredLanguage        PrintableString OPTIONAL -- In accordance with
3388  *     -- IETF RFC 1766
3389  * } (CONSTRAINED BY { -- Each AlgorithmInfo.reference value must be unique --})
3390  *
3391  * TokenFlags ::= BIT STRING {
3392  *     readOnly         (0),
3393  *     loginRequired    (1),
3394  *     prnGeneration    (2),
3395  *     eidCompliant     (3)
3396  * }
3397  *
3398  *
3399  * Sample EF 5032:
3400  * 30 31 02 01 00 04 04 05 45  36 9F 0C 0C 44 2D 54   01......E6...D-T
3401  * 72 75 73 74 20 47 6D 62 48  80 14 4F 66 66 69 63   rust GmbH..Offic
3402  * 65 20 69 64 65 6E 74 69 74  79 20 63 61 72 64 03   e identity card.
3403  * 02 00 40 20 63 61 72 64 03  02 00 40 00 00 00 00   ..@ card...@....
3404  * 00 00 00 00 00 00 00 00 00  00 00 00 00 00 00 00   ................
3405  *
3406  *    0   49: SEQUENCE {
3407  *    2    1:   INTEGER 0
3408  *    5    4:   OCTET STRING 05 45 36 9F
3409  *   11   12:   UTF8String 'D-Trust GmbH'
3410  *   25   20:   [0] 'Office identity card'
3411  *   47    2:   BIT STRING
3412  *          :     '00000010'B (bit 1)
3413  *          :     Error: Spurious zero bits in bitstring.
3414  *          :   }
3415  */
3416 static gpg_error_t
3417 read_ef_tokeninfo (app_t app)
3418 {
3419   gpg_error_t err;
3420   unsigned char *buffer = NULL;
3421   size_t buflen;
3422   const unsigned char *p;
3423   size_t n, objlen, hdrlen;
3424   int class, tag, constructed, ndef;
3425   unsigned long ul;
3426
3427   release_tokeninfo (app);
3428   app->app_local->card_product = CARD_PRODUCT_UNKNOWN;
3429
3430   err = select_and_read_binary (app, 0x5032, "TokenInfo", &buffer, &buflen);
3431   if (err)
3432     return err;
3433
3434   p = buffer;
3435   n = buflen;
3436
3437   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3438                           &ndef, &objlen, &hdrlen);
3439   if (!err && (objlen > n || tag != TAG_SEQUENCE))
3440     err = gpg_error (GPG_ERR_INV_OBJ);
3441   if (err)
3442     {
3443       log_error ("p15: error parsing TokenInfo: %s\n", gpg_strerror (err));
3444       goto leave;
3445     }
3446
3447   n = objlen;
3448
3449   /* Version.  */
3450   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3451                           &ndef, &objlen, &hdrlen);
3452   if (!err && (objlen > n || tag != TAG_INTEGER))
3453     err = gpg_error (GPG_ERR_INV_OBJ);
3454   if (err)
3455     goto leave;
3456
3457   for (ul=0; objlen; objlen--)
3458     {
3459       ul <<= 8;
3460       ul |= (*p++) & 0xff;
3461       n--;
3462     }
3463   if (ul)
3464     {
3465       log_error ("p15: invalid version %lu in TokenInfo\n", ul);
3466       err = gpg_error (GPG_ERR_INV_OBJ);
3467       goto leave;
3468     }
3469
3470   /* serialNumber.  */
3471   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3472                           &ndef, &objlen, &hdrlen);
3473   if (!err && (objlen > n || tag != TAG_OCTET_STRING || !objlen))
3474     err = gpg_error (GPG_ERR_INV_OBJ);
3475   if (err)
3476     goto leave;
3477
3478   xfree (app->app_local->serialno);
3479   app->app_local->serialno = xtrymalloc (objlen);
3480   if (!app->app_local->serialno)
3481     {
3482       err = gpg_error_from_syserror ();
3483       goto leave;
3484     }
3485   memcpy (app->app_local->serialno, p, objlen);
3486   app->app_local->serialnolen = objlen;
3487   p += objlen;
3488   n -= objlen;
3489
3490   /* Is there an optional manufacturerID?  */
3491   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3492                           &ndef, &objlen, &hdrlen);
3493   if (!err && (objlen > n || !objlen))
3494     err = gpg_error (GPG_ERR_INV_OBJ);
3495   if (err)
3496     goto leave;
3497   if (class == CLASS_UNIVERSAL && tag == TAG_UTF8_STRING)
3498     {
3499       app->app_local->manufacturer_id = percent_data_escape (0, NULL,
3500                                                              p, objlen);
3501       p += objlen;
3502       n -= objlen;
3503       /* Get next TLV.  */
3504       err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3505                               &ndef, &objlen, &hdrlen);
3506       if (!err && (objlen > n || !objlen))
3507         err = gpg_error (GPG_ERR_INV_OBJ);
3508       if (err)
3509         goto leave;
3510     }
3511   if (class == CLASS_CONTEXT && tag == 0)
3512     {
3513       app->app_local->token_label = percent_data_escape (0, NULL, p, objlen);
3514
3515       p += objlen;
3516       n -= objlen;
3517       /* Get next TLV.  */
3518       err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3519                               &ndef, &objlen, &hdrlen);
3520       if (!err && (objlen > n || !objlen))
3521         err = gpg_error (GPG_ERR_INV_OBJ);
3522       if (err)
3523         goto leave;
3524     }
3525   /* The next is the mandatory tokenflags object.  */
3526   if (class == CLASS_UNIVERSAL && tag == TAG_BIT_STRING)
3527     {
3528       app->app_local->tokenflagslen = objlen;
3529       app->app_local->tokenflags = xtrymalloc (objlen);
3530       if (!app->app_local->tokenflags)
3531         {
3532           err = gpg_error_from_syserror ();
3533           goto leave;
3534         }
3535       memcpy (app->app_local->tokenflags, p, objlen);
3536       p += objlen;
3537       n -= objlen;
3538     }
3539
3540
3541  leave:
3542   xfree (buffer);
3543   return err;
3544 }
3545
3546
3547 /* Get all the basic information from the pkcs#15 card, check the
3548    structure and initialize our local context.  This is used once at
3549    application initialization. */
3550 static gpg_error_t
3551 read_p15_info (app_t app)
3552 {
3553   gpg_error_t err;
3554   prkdf_object_t prkdf;
3555   unsigned int flag;
3556
3557   err = read_ef_tokeninfo (app);
3558   if (err)
3559     return err;
3560   /* If we don't have a serial number yet but the TokenInfo provides
3561    * one, use that. */
3562   if (!APP_CARD(app)->serialno && app->app_local->serialno)
3563     {
3564       APP_CARD(app)->serialno = app->app_local->serialno;
3565       APP_CARD(app)->serialnolen = app->app_local->serialnolen;
3566       app->app_local->serialno = NULL;
3567       app->app_local->serialnolen = 0;
3568       err = app_munge_serialno (APP_CARD(app));
3569       if (err)
3570         return err;
3571     }
3572
3573   release_lists (app);
3574
3575   if (IS_CARDOS_5 (app)
3576       && app->app_local->manufacturer_id
3577       && !ascii_strcasecmp (app->app_local->manufacturer_id, "GeNUA mbH"))
3578     {
3579       if (!app->app_local->card_product)
3580         app->app_local->card_product = CARD_PRODUCT_GENUA;
3581     }
3582
3583   /* Read the ODF so that we know the location of all directory
3584      files. */
3585   /* Fixme: We might need to get a non-standard ODF FID from TokenInfo. */
3586   err = read_ef_odf (app, 0x5031);
3587   if (err)
3588     return err;
3589
3590   /* Read certificate information. */
3591   log_assert (!app->app_local->certificate_info);
3592   log_assert (!app->app_local->trusted_certificate_info);
3593   log_assert (!app->app_local->useful_certificate_info);
3594   err = read_ef_cdf (app, app->app_local->odf.certificates, 'c',
3595                      &app->app_local->certificate_info);
3596   if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
3597     err = read_ef_cdf (app, app->app_local->odf.trusted_certificates, 't',
3598                        &app->app_local->trusted_certificate_info);
3599   if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
3600     err = read_ef_cdf (app, app->app_local->odf.useful_certificates, 'u',
3601                        &app->app_local->useful_certificate_info);
3602   if (gpg_err_code (err) == GPG_ERR_NO_DATA)
3603     err = 0;
3604   if (err)
3605     return err;
3606
3607   /* Read information about public keys. */
3608   log_assert (!app->app_local->public_key_info);
3609   err = read_ef_pukdf (app, app->app_local->odf.public_keys,
3610                        &app->app_local->public_key_info);
3611   if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
3612     err = read_ef_pukdf (app, app->app_local->odf.trusted_public_keys,
3613                          &app->app_local->public_key_info);
3614   if (gpg_err_code (err) == GPG_ERR_NO_DATA)
3615     err = 0;
3616   if (err)
3617     return err;
3618
3619   /* Read information about private keys. */
3620   log_assert (!app->app_local->private_key_info);
3621   err = read_ef_prkdf (app, app->app_local->odf.private_keys,
3622                        &app->app_local->private_key_info);
3623   if (gpg_err_code (err) == GPG_ERR_NO_DATA)
3624     err = 0;
3625   if (err)
3626     return err;
3627
3628   /* Read information about authentication objects. */
3629   log_assert (!app->app_local->auth_object_info);
3630   err = read_ef_aodf (app, app->app_local->odf.auth_objects,
3631                       &app->app_local->auth_object_info);
3632   if (gpg_err_code (err) == GPG_ERR_NO_DATA)
3633     err = 0;
3634
3635
3636   /* See whether we can extend the private key information using
3637    * information from certificates.  We use only the first matching
3638    * certificate; if we want to change this strategy we should walk
3639    * over the certificates and then find the corresponsing private key
3640    * objects.  */
3641   app->app_local->any_gpgusage = 0;
3642   for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
3643     {
3644       cdf_object_t cdf;
3645       char *extusage;
3646       char *p, *pend;
3647       int seen, i;
3648
3649       if (opt.debug)
3650         log_printhex (prkdf->objid, prkdf->objidlen, "p15: prkdf id=");
3651       if (cdf_object_from_objid (app, prkdf->objidlen, prkdf->objid, &cdf)
3652           && cdf_object_from_label (app, prkdf->label, &cdf))
3653         continue; /* No matching certificate.  */
3654       if (!cdf->cert)  /* Read and parse the certificate.  */
3655         readcert_by_cdf (app, cdf, NULL, NULL);
3656       if (!cdf->cert)
3657         continue; /* Unsupported or broken certificate.  */
3658
3659       if (prkdf->is_ecc)
3660         {
3661           const char *oid;
3662           const unsigned char *der;
3663           size_t off, derlen, objlen, hdrlen;
3664           int class, tag, constructed, ndef;
3665
3666           for (i=0; !(err = ksba_cert_get_extension
3667                       (cdf->cert, i, &oid, NULL, &off, &derlen)); i++)
3668             if (!strcmp (oid, "1.3.6.1.4.1.11591.2.2.10") )
3669               break;
3670           if (!err && (der = ksba_cert_get_image (cdf->cert, NULL)))
3671             {
3672               der += off;
3673               err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
3674                                       &ndef, &objlen, &hdrlen);
3675               if (!err && (objlen > derlen || tag != TAG_OCTET_STRING || ndef))
3676                 err = gpg_error (GPG_ERR_INV_OBJ);
3677               if (!err)
3678                 {
3679                   derlen = objlen;
3680                   if (opt.debug)
3681                     log_printhex (der, derlen, "p15: OpenPGP KDF parms:");
3682                   /* Store them if they match the known OpenPGP format. */
3683                   if (derlen == 4 && der[0] == 3 && der[1]  == 1)
3684                     memcpy (prkdf->ecdh_kdf, der, 4);
3685                 }
3686             }
3687           err = 0;
3688         }
3689
3690       if (ksba_cert_get_ext_key_usages (cdf->cert, &extusage))
3691         continue; /* No extended key usage attribute.  */
3692
3693       if (opt.debug)
3694         log_debug ("p15: ExtKeyUsages: %s\n", extusage);
3695       p = extusage;
3696       while (p && (pend=strchr (p, ':')))
3697         {
3698           *pend++ = 0;
3699           if ( *pend == 'C' ) /* Look only at critical usages.  */
3700             {
3701               prkdf->extusage.valid = 1;
3702               seen = 1;
3703               if (!strcmp (p, oid_kp_codeSigning)
3704                   || !strcmp (p, oid_kp_timeStamping)
3705                   || !strcmp (p, oid_kp_ocspSigning)
3706                   || !strcmp (p, oid_kp_ms_documentSigning)
3707                   || !strcmp (p, oid_kp_ms_old_documentSigning))
3708                 prkdf->extusage.sign = 1;
3709               else if (!strcmp (p, oid_kp_emailProtection))
3710                 prkdf->extusage.encr = 1;
3711               else if (!strcmp (p, oid_kp_serverAuth)
3712                        || !strcmp (p, oid_kp_clientAuth)
3713                        || !strcmp (p, oid_kp_ms_smartcardLogon))
3714                 prkdf->extusage.auth = 1;
3715               else if (!strcmp (p, oid_kp_anyExtendedKeyUsage))
3716                 {
3717                   prkdf->extusage.sign = 1;
3718                   prkdf->extusage.encr = 1;
3719                   prkdf->extusage.auth = 1;
3720                 }
3721               else
3722                 seen = 0;
3723             }
3724           else
3725             seen = 0;
3726
3727           /* Now check the gpg Usage.  Here we don't care about
3728            * critical or non-critical here. */
3729           if (seen)
3730             ; /* No more need to look for other caps.  */
3731           else if (!strcmp (p, oid_kp_gpgUsageCert))
3732             {
3733               prkdf->gpgusage.cert = 1;
3734               prkdf->gpgusage.any = 1;
3735               app->app_local->any_gpgusage = 1;
3736             }
3737           else if (!strcmp (p, oid_kp_gpgUsageSign))
3738             {
3739               prkdf->gpgusage.sign = 1;
3740               prkdf->gpgusage.any = 1;
3741               app->app_local->any_gpgusage = 1;
3742             }
3743           else if (!strcmp (p, oid_kp_gpgUsageEncr))
3744             {
3745               prkdf->gpgusage.encr = 1;
3746               prkdf->gpgusage.any = 1;
3747               app->app_local->any_gpgusage = 1;
3748             }
3749           else if (!strcmp (p, oid_kp_gpgUsageAuth))
3750             {
3751               prkdf->gpgusage.auth = 1;
3752               prkdf->gpgusage.any = 1;
3753               app->app_local->any_gpgusage = 1;
3754             }
3755
3756           /* Skip to next item.  */
3757           if ((p = strchr (pend, '\n')))
3758             p++;
3759         }
3760       xfree (extusage);
3761     }
3762
3763   /* See whether we can figure out something about the card.  */
3764   if (!app->app_local->card_product
3765       && app->app_local->manufacturer_id
3766       && !strcmp (app->app_local->manufacturer_id, "www.atos.net/cardos")
3767       && IS_CARDOS_5 (app))
3768     {
3769       /* This is a modern CARDOS card. */
3770       flag = 0;
3771       for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
3772         {
3773           if (prkdf->label && !strcmp (prkdf->label, "IdentityKey")
3774               && prkdf->key_reference_valid && prkdf->key_reference == 1
3775               && !prkdf->authid)
3776             flag |= 1;
3777           else if (prkdf->label && !strcmp (prkdf->label, "TransportKey")
3778                    && prkdf->key_reference_valid && prkdf->key_reference==2
3779                    && prkdf->authid)
3780             flag |= 2;
3781         }
3782       if (flag == 3)
3783         app->app_local->card_product = CARD_PRODUCT_RSCS;
3784
3785     }
3786   if (!app->app_local->card_product
3787       && app->app_local->token_label
3788       && !strncmp (app->app_local->token_label, "D-TRUST Card V3", 15)
3789       && app->app_local->card_type == CARD_TYPE_CARDOS_50)
3790     {
3791       app->app_local->card_product = CARD_PRODUCT_DTRUST;
3792     }
3793
3794
3795   /* Now print the info about the PrKDF.  */
3796   if (opt.verbose)
3797     {
3798       int i;
3799       unsigned char *atr;
3800       size_t atrlen;
3801       const char *cardstr;
3802
3803       for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
3804         {
3805           log_info ("p15: PrKDF %04hX: id=", app->app_local->odf.private_keys);
3806           for (i=0; i < prkdf->objidlen; i++)
3807             log_printf ("%02X", prkdf->objid[i]);
3808           if (prkdf->label)
3809             log_printf (" (%s)", prkdf->label);
3810           log_info ("p15:             path=");
3811           for (i=0; i < prkdf->pathlen; i++)
3812             log_printf ("%s%04hX", i?"/":"",prkdf->path[i]);
3813           if (prkdf->have_off)
3814             log_printf ("[%lu/%lu]", prkdf->off, prkdf->len);
3815           if (prkdf->authid)
3816             {
3817               log_printf (" authid=");
3818               for (i=0; i < prkdf->authidlen; i++)
3819                 log_printf ("%02X", prkdf->authid[i]);
3820             }
3821           if (prkdf->key_reference_valid)
3822             log_printf (" keyref=0x%02lX", prkdf->key_reference);
3823           log_printf (" type=%s", prkdf->is_ecc? "ecc":"rsa");
3824           if (prkdf->accessflags.any)
3825             dump_keyaccess_flags (prkdf->accessflags);
3826           dump_keyusage_flags (prkdf->usageflags);
3827           if (prkdf->extusage.valid)
3828             log_info ("p15:             extusage=%s%s%s%s%s",
3829                       prkdf->extusage.sign? "sign":"",
3830                       (prkdf->extusage.sign
3831                        && prkdf->extusage.encr)?",":"",
3832                       prkdf->extusage.encr? "encr":"",
3833                       ((prkdf->extusage.sign || prkdf->extusage.encr)
3834                        && prkdf->extusage.auth)?",":"",
3835                       prkdf->extusage.auth? "auth":"");
3836           if (prkdf->gpgusage.any)
3837             dump_gpgusage_flags (prkdf->gpgusage);
3838
3839           log_printf ("\n");
3840         }
3841
3842       log_info ("p15: TokenInfo:\n");
3843       if (app->app_local->serialno)
3844         {
3845           log_info ("p15:  serialNumber .: ");
3846           log_printhex (app->app_local->serialno, app->app_local->serialnolen,
3847                         "");
3848         }
3849       else if (APP_CARD(app)->serialno)
3850         {
3851           log_info ("p15:  serialNumber .: ");
3852           log_printhex (APP_CARD(app)->serialno, APP_CARD(app)->serialnolen,
3853                         "");
3854         }
3855
3856       if (app->app_local->manufacturer_id)
3857         log_info ("p15:  manufacturerID: %s\n",
3858                   app->app_local->manufacturer_id);
3859       if (app->app_local->card_product)
3860         {
3861           cardstr = cardproduct2str (app->app_local->card_product);
3862           log_info ("p15:  product ......: %d%s%s%s\n",
3863                     app->app_local->card_product,
3864                     *cardstr? " (":"", cardstr, *cardstr? ")":"");
3865         }
3866       if (app->app_local->token_label)
3867         log_info ("p15:  label ........: %s\n", app->app_local->token_label);
3868       if (app->app_local->tokenflags)
3869         {
3870           log_info ("p15:  tokenflags ...:");
3871           print_tokeninfo_tokenflags (app->app_local->tokenflags,
3872                                       app->app_local->tokenflagslen);
3873           log_printf ("\n");
3874         }
3875
3876       log_info ("p15:  atr ..........: ");
3877       atr = apdu_get_atr (app_get_slot (app), &atrlen);
3878       if (!atr)
3879         log_printf ("[error]\n");
3880       else
3881         {
3882           log_printhex (atr, atrlen, "");
3883           xfree (atr);
3884         }
3885
3886       cardstr = cardtype2str (app->app_local->card_type);
3887       log_info ("p15:  cardtype .....: %d%s%s%s\n",
3888                 app->app_local->card_type,
3889                 *cardstr? " (":"", cardstr, *cardstr? ")":"");
3890     }
3891
3892   return err;
3893 }
3894
3895
3896 /* Helper to do_learn_status: Send information about all certificates
3897    listed in CERTINFO back.  Use CERTTYPE as type of the
3898    certificate. */
3899 static gpg_error_t
3900 send_certinfo (app_t app, ctrl_t ctrl, const char *certtype,
3901                cdf_object_t certinfo)
3902 {
3903   for (; certinfo; certinfo = certinfo->next)
3904     {
3905       char *buf, *p;
3906       const char *label;
3907       char *labelbuf;
3908
3909       buf = xtrymalloc (9 + certinfo->objidlen*2 + 1);
3910       if (!buf)
3911         return gpg_error_from_syserror ();
3912       p = stpcpy (buf, "P15");
3913       if (app->app_local->home_df != DEFAULT_HOME_DF)
3914         {
3915           snprintf (p, 6, "-%04X",
3916                     (unsigned int)(app->app_local->home_df & 0xffff));
3917           p += 5;
3918         }
3919       p = stpcpy (p, ".");
3920       bin2hex (certinfo->objid, certinfo->objidlen, p);
3921
3922       label = (certinfo->label && *certinfo->label)? certinfo->label : "-";
3923       labelbuf = percent_data_escape (0, NULL, label, strlen (label));
3924       if (!labelbuf)
3925         {
3926           xfree (buf);
3927           return gpg_error_from_syserror ();
3928         }
3929
3930       send_status_info (ctrl, "CERTINFO",
3931                         certtype, strlen (certtype),
3932                         buf, strlen (buf),
3933                         labelbuf, strlen (labelbuf),
3934                         NULL, (size_t)0);
3935       xfree (buf);
3936       xfree (labelbuf);
3937     }
3938   return 0;
3939 }
3940
3941
3942 /* Get the keygrip of the private key object PRKDF.  On success the
3943  * keygrip, the algo and the length are stored in the KEYGRIP,
3944  * KEYALGO, and KEYNBITS fields of the PRKDF object.  */
3945 static gpg_error_t
3946 keygrip_from_prkdf (app_t app, prkdf_object_t prkdf)
3947 {
3948   gpg_error_t err;
3949   cdf_object_t cdf;
3950   unsigned char *der;
3951   size_t derlen;
3952   ksba_cert_t cert;
3953   gcry_sexp_t s_pkey = NULL;
3954
3955   /* Easy if we got a cached version.  */
3956   if (prkdf->keygrip_valid)
3957     return 0;
3958
3959   xfree (prkdf->common_name);
3960   prkdf->common_name = NULL;
3961   xfree (prkdf->serial_number);
3962   prkdf->serial_number = NULL;
3963
3964   /* We could have also checked whether a public key directory file
3965    * and a matching public key for PRKDF is available.  This would
3966    * make extraction of the key faster.  However, this way we don't
3967    * have a way to look at extended key attributes to check gpgusage.
3968    * FIXME: Add public key lookup if no certificate was found. */
3969
3970   /* Look for a matching certificate. A certificate matches if the id
3971    * matches the one of the private key info.  If none was found we
3972    * also try to match on the label.  */
3973   err = cdf_object_from_objid (app, prkdf->objidlen, prkdf->objid, &cdf);
3974   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
3975     err = cdf_object_from_label (app, prkdf->label, &cdf);
3976   if (!err && !cdf)
3977     err = gpg_error (GPG_ERR_NOT_FOUND);
3978   if (err)
3979     goto leave;
3980
3981   err = readcert_by_cdf (app, cdf, &der, &derlen);
3982   if (err)
3983     goto leave;
3984
3985   err = ksba_cert_new (&cert);
3986   if (!err)
3987     err = ksba_cert_init_from_mem (cert, der, derlen);
3988   xfree (der);
3989   if (!err)
3990     err = app_help_get_keygrip_string (cert, prkdf->keygrip, &s_pkey, NULL);
3991   if (!err && !prkdf->gpgusage.any)
3992     {
3993       /* Try to get the CN and the SerialNumber from the certificate;
3994        * we use a very simple approach here which should work in many
3995        * cases.  Eventually we should add a rfc-2253 parser into
3996        * libksba to make it easier to parse such a string.
3997        * We don't do this if this is marked as gpg key and thus
3998        * has only a dummy certificate.
3999        *
4000        * First example string:
4001        *   "CN=Otto Schily,O=Miniluv,C=DE"
4002        * Second example string:
4003        *   "2.5.4.5=#445452323030303236333531,2.5.4.4=#4B6F6368,"
4004        *   "2.5.4.42=#5765726E6572,CN=Werner Koch,OU=For testing"
4005        *   " purposes only!,O=Testorganisation,C=DE"
4006        */
4007       char *dn = ksba_cert_get_subject (cert, 0);
4008       if (dn)
4009         {
4010           char *p, *pend, *buf;
4011
4012           p = strstr (dn, "CN=");
4013           if (p && (p==dn || p[-1] == ','))
4014             {
4015               p += 3;
4016               if (!(pend = strchr (p, ',')))
4017                 pend = p + strlen (p);
4018               if (pend && pend > p
4019                   && (prkdf->common_name = xtrymalloc ((pend - p) + 1)))
4020                 {
4021                   memcpy (prkdf->common_name, p, pend-p);
4022                   prkdf->common_name[pend-p] = 0;
4023                 }
4024             }
4025           p = strstr (dn, "2.5.4.5=#"); /* OID of the SerialNumber */
4026           if (p && (p==dn || p[-1] == ','))
4027             {
4028               p += 9;
4029               if (!(pend = strchr (p, ',')))
4030                 pend = p + strlen (p);
4031               if (pend && pend > p
4032                   && (buf = xtrymalloc ((pend - p) + 1)))
4033                 {
4034                   memcpy (buf, p, pend-p);
4035                   buf[pend-p] = 0;
4036                   if (!hex2str (buf, buf, strlen (buf)+1, NULL))
4037                     xfree (buf);  /* Invalid hex encoding.  */
4038                   else
4039                     prkdf->serial_number = buf;
4040                 }
4041             }
4042           ksba_free (dn);
4043         }
4044     }
4045
4046   if (!err && !prkdf->keytime)
4047     {
4048       ksba_isotime_t isot;
4049       time_t t;
4050
4051       ksba_cert_get_validity (cert, 0, isot);
4052       t = isotime2epoch (isot);
4053       prkdf->keytime = (t == (time_t)(-1))? 0 : (u32)t;
4054       prkdf->have_keytime = 1;
4055     }
4056
4057   if (!err && !prkdf->keyalgostr)
4058     prkdf->keyalgostr = pubkey_algo_string (s_pkey, NULL);
4059
4060   ksba_cert_release (cert);
4061   if (err)
4062     goto leave;
4063
4064   prkdf->keyalgo = get_pk_algo_from_key (s_pkey);
4065   if (!prkdf->keyalgo)
4066     {
4067       err = gpg_error (GPG_ERR_PUBKEY_ALGO);
4068       goto leave;
4069     }
4070
4071   prkdf->keynbits = gcry_pk_get_nbits (s_pkey);
4072   if (!prkdf->keynbits)
4073     {
4074       err = gpg_error (GPG_ERR_PUBKEY_ALGO);
4075       goto leave;
4076     }
4077
4078   prkdf->keygrip_valid = 1;  /* Yeah, got everything.  */
4079
4080  leave:
4081   gcry_sexp_release (s_pkey);
4082   return err;
4083 }
4084
4085
4086 /* Return a malloced keyref string for PRKDF.  Returns NULL on
4087  * malloc failure.  */
4088 static char *
4089 keyref_from_prkdf (app_t app, prkdf_object_t prkdf)
4090 {
4091   char *buf, *p;
4092
4093   buf = xtrymalloc (4 + 5 + prkdf->objidlen*2 + 1);
4094   if (!buf)
4095     return NULL;
4096   p = stpcpy (buf, "P15");
4097   if (app->app_local->home_df != DEFAULT_HOME_DF)
4098     {
4099       snprintf (p, 6, "-%04X",
4100                 (unsigned int)(app->app_local->home_df & 0xffff));
4101       p += 5;
4102     }
4103   p = stpcpy (p, ".");
4104   bin2hex (prkdf->objid, prkdf->objidlen, p);
4105   return buf;
4106 }
4107
4108
4109 /* Helper to do_learn_status: Send information about all known
4110    keypairs back.  FIXME: much code duplication from
4111    send_certinfo(). */
4112 static gpg_error_t
4113 send_keypairinfo (app_t app, ctrl_t ctrl, prkdf_object_t prkdf)
4114 {
4115   gpg_error_t err;
4116
4117   for (; prkdf; prkdf = prkdf->next)
4118     {
4119       char *buf;
4120       int j;
4121
4122       buf = keyref_from_prkdf (app, prkdf);
4123       if (!buf)
4124         return gpg_error_from_syserror ();
4125
4126       err = keygrip_from_prkdf (app, prkdf);
4127       if (err)
4128         {
4129           log_error ("p15: error getting keygrip from ");
4130           for (j=0; j < prkdf->pathlen; j++)
4131             log_printf ("%s%04hX", j?"/":"", prkdf->path[j]);
4132           log_printf (": %s\n", gpg_strerror (err));
4133         }
4134       else
4135         {
4136           char usage[5];
4137           char keytime[20];
4138           const char *algostr;
4139           size_t usagelen = 0;
4140
4141           if (prkdf->gpgusage.any)
4142             {
4143               if (prkdf->gpgusage.sign)
4144                 usage[usagelen++] = 's';
4145               if (prkdf->gpgusage.cert)
4146                 usage[usagelen++] = 'c';
4147               if (prkdf->gpgusage.encr)
4148                 usage[usagelen++] = 'e';
4149               if (prkdf->gpgusage.auth)
4150                 usage[usagelen++] = 'a';
4151             }
4152           else
4153             {
4154               if ((prkdf->usageflags.sign
4155                    || prkdf->usageflags.sign_recover
4156                    || prkdf->usageflags.non_repudiation)
4157                   && (!prkdf->extusage.valid
4158                       || prkdf->extusage.sign))
4159                 usage[usagelen++] = 's';
4160               if ((prkdf->usageflags.sign
4161                    || prkdf->usageflags.sign_recover)
4162                   && (!prkdf->extusage.valid || prkdf->extusage.sign))
4163                 usage[usagelen++] = 'c';
4164               if ((prkdf->usageflags.decrypt
4165                    || prkdf->usageflags.unwrap)
4166                   && (!prkdf->extusage.valid || prkdf->extusage.encr))
4167                 usage[usagelen++] = 'e';
4168               if ((prkdf->usageflags.sign
4169                    || prkdf->usageflags.sign_recover)
4170                   && (!prkdf->extusage.valid || prkdf->extusage.auth))
4171                 usage[usagelen++] = 'a';
4172             }
4173
4174           log_assert (strlen (prkdf->keygrip) == 40);
4175           if (prkdf->keytime && prkdf->have_keytime)
4176             snprintf (keytime, sizeof keytime, "%lu",
4177                       (unsigned long)prkdf->keytime);
4178           else
4179             strcpy (keytime, "-");
4180
4181           algostr = prkdf->keyalgostr;
4182
4183           send_status_info (ctrl, "KEYPAIRINFO",
4184                             prkdf->keygrip, 2*KEYGRIP_LEN,
4185                             buf, strlen (buf),
4186                             usage, usagelen,
4187                             keytime, strlen (keytime),
4188                             algostr, strlen (algostr?algostr:""),
4189                             NULL, (size_t)0);
4190         }
4191       xfree (buf);
4192     }
4193   return 0;
4194 }
4195
4196
4197
4198 /* This is the handler for the LEARN command.  Note that if
4199  * APP_LEARN_FLAG_REREAD is set and this function returns an error,
4200  * the caller must deinitialize this application.  */
4201 static gpg_error_t
4202 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
4203 {
4204   gpg_error_t err;
4205
4206   if (flags & APP_LEARN_FLAG_REREAD)
4207     {
4208       err = read_p15_info (app);
4209       if (err)
4210         return err;
4211     }
4212
4213   if ((flags & APP_LEARN_FLAG_KEYPAIRINFO))
4214     err = 0;
4215   else
4216     {
4217       err = do_getattr (app, ctrl, "MANUFACTURER");
4218       if (!err)
4219         err = send_certinfo (app, ctrl, "100",
4220                              app->app_local->certificate_info);
4221       if (!err)
4222         err = send_certinfo (app, ctrl, "101",
4223                              app->app_local->trusted_certificate_info);
4224       if (!err)
4225         err = send_certinfo (app, ctrl, "102",
4226                              app->app_local->useful_certificate_info);
4227     }
4228
4229   if (!err)
4230     err = send_keypairinfo (app, ctrl, app->app_local->private_key_info);
4231
4232   if (!err)
4233     err = do_getattr (app, ctrl, "CHV-STATUS");
4234   if (!err)
4235     err = do_getattr (app, ctrl, "CHV-LABEL");
4236
4237
4238   return err;
4239 }
4240
4241
4242 /* Read a certificate using the information in CDF and return the
4243  * certificate in a newly malloced buffer R_CERT and its length
4244  * R_CERTLEN.  Also parses the certificate.  R_CERT and R_CERTLEN may
4245  * be NULL to do just the caching.  */
4246 static gpg_error_t
4247 readcert_by_cdf (app_t app, cdf_object_t cdf,
4248                  unsigned char **r_cert, size_t *r_certlen)
4249 {
4250   gpg_error_t err;
4251   unsigned char *buffer = NULL;
4252   const unsigned char *p, *save_p;
4253   size_t buflen, n;
4254   int class, tag, constructed, ndef;
4255   size_t totobjlen, objlen, hdrlen;
4256   int rootca;
4257   int i;
4258
4259   if (r_cert)
4260     *r_cert = NULL;
4261   if (r_certlen)
4262     *r_certlen = 0;
4263
4264   /* First check whether it has been cached. */
4265   if (cdf->cert)
4266     {
4267       const unsigned char *image;
4268       size_t imagelen;
4269
4270       if (!r_cert || !r_certlen)
4271         return 0; /* Caller does not actually want the result. */
4272
4273       image = ksba_cert_get_image (cdf->cert, &imagelen);
4274       if (!image)
4275         {
4276           log_error ("p15: ksba_cert_get_image failed\n");
4277           return gpg_error (GPG_ERR_INTERNAL);
4278         }
4279       *r_cert = xtrymalloc (imagelen);
4280       if (!*r_cert)
4281         return gpg_error_from_syserror ();
4282       memcpy (*r_cert, image, imagelen);
4283       *r_certlen = imagelen;
4284       return 0;
4285     }
4286
4287   if (DBG_CARD)
4288     {
4289       log_info ("p15: Reading CDF: id=");
4290       for (i=0; i < cdf->objidlen; i++)
4291         log_printf ("%02X", cdf->objid[i]);
4292       if (cdf->label)
4293         log_printf (" (%s)", cdf->label);
4294       log_info ("p15:             path=");
4295       for (i=0; i < cdf->pathlen; i++)
4296         log_printf ("%s%04hX", i?"/":"", cdf->path[i]);
4297       if (cdf->have_off)
4298         log_printf ("[%lu/%lu]", cdf->off, cdf->len);
4299       if (cdf->authid)
4300         {
4301           log_printf (" authid=");
4302           for (i=0; i < cdf->authidlen; i++)
4303             log_printf ("%02X", cdf->authid[i]);
4304         }
4305       log_printf ("\n");
4306     }
4307
4308   /* Read the entire file.  fixme: This could be optimized by first
4309      reading the header to figure out how long the certificate
4310      actually is. */
4311   err = select_ef_by_path (app, cdf->path, cdf->pathlen);
4312   if (err)
4313     goto leave;
4314
4315   if (app->app_local->no_extended_mode || !cdf->len)
4316     err = iso7816_read_binary_ext (app_get_slot (app), 0, cdf->off, 0,
4317                                    &buffer, &buflen, NULL);
4318   else
4319     err = iso7816_read_binary_ext (app_get_slot (app), 1, cdf->off, cdf->len,
4320                                    &buffer, &buflen, NULL);
4321   if (!err && (!buflen || *buffer == 0xff))
4322     err = gpg_error (GPG_ERR_NOT_FOUND);
4323   if (err)
4324     {
4325       log_error ("p15: error reading certificate id=");
4326       for (i=0; i < cdf->objidlen; i++)
4327         log_printf ("%02X", cdf->objid[i]);
4328       log_printf (" at ");
4329       for (i=0; i < cdf->pathlen; i++)
4330         log_printf ("%s%04hX", i? "/":"", cdf->path[i]);
4331       log_printf (": %s\n", gpg_strerror (err));
4332       goto leave;
4333     }
4334
4335   /* Check whether this is really a certificate.  */
4336   p = buffer;
4337   n = buflen;
4338   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
4339                           &ndef, &objlen, &hdrlen);
4340   if (err)
4341     goto leave;
4342
4343   if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed)
4344     rootca = 0;
4345   else if ( class == CLASS_UNIVERSAL && tag == TAG_SET && constructed )
4346     rootca = 1;
4347   else
4348     {
4349       err = gpg_error (GPG_ERR_INV_OBJ);
4350       goto leave;
4351     }
4352   totobjlen = objlen + hdrlen;
4353   log_assert (totobjlen <= buflen);
4354
4355   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
4356                           &ndef, &objlen, &hdrlen);
4357   if (err)
4358     goto leave;
4359
4360   if (!rootca
4361       && class == CLASS_UNIVERSAL && tag == TAG_OBJECT_ID && !constructed)
4362     {
4363       /* The certificate seems to be contained in a userCertificate
4364          container.  Skip this and assume the following sequence is
4365          the certificate. */
4366       if (n < objlen)
4367         {
4368           err = gpg_error (GPG_ERR_INV_OBJ);
4369           goto leave;
4370         }
4371       p += objlen;
4372       n -= objlen;
4373       save_p = p;
4374       err = parse_ber_header (&p, &n, &class, &tag, &constructed,
4375                               &ndef, &objlen, &hdrlen);
4376       if (err)
4377         goto leave;
4378       if ( !(class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed) )
4379         {
4380           err = gpg_error (GPG_ERR_INV_OBJ);
4381           goto leave;
4382         }
4383       totobjlen = objlen + hdrlen;
4384       log_assert (save_p + totobjlen <= buffer + buflen);
4385       memmove (buffer, save_p, totobjlen);
4386     }
4387
4388
4389   /* Try to parse and cache the certificate. */
4390   err = ksba_cert_new (&cdf->cert);
4391   if (!err)
4392     {
4393       err = ksba_cert_init_from_mem (cdf->cert, buffer, totobjlen);
4394       if (!err) /* Call us to use the just cached cert object.  */
4395         err = readcert_by_cdf (app, cdf, r_cert, r_certlen);
4396       if (err)
4397         {
4398           ksba_cert_release (cdf->cert);
4399           cdf->cert = NULL;
4400         }
4401
4402     }
4403   if (err)
4404     {
4405       log_error ("p15: caching certificate failed: %s\n",
4406                  gpg_strerror (err));
4407       /* We return the certificate anyway so that the caller has a
4408        * chance to get an even unsupported or broken certificate.  */
4409       if (r_cert && r_certlen)
4410         {
4411           *r_cert = buffer;
4412           buffer = NULL;
4413           *r_certlen = totobjlen;
4414         }
4415     }
4416
4417  leave:
4418   xfree (buffer);
4419   return err;
4420 }
4421
4422
4423 /* Handler for the READCERT command.
4424
4425    Read the certificate with id CERTID (as returned by learn_status in
4426    the CERTINFO status lines) and return it in the freshly allocated
4427    buffer to be stored at R_CERT and its length at R_CERTLEN.  A error
4428    code will be returned on failure and R_CERT and R_CERTLEN will be
4429    set to (NULL,0). */
4430 static gpg_error_t
4431 do_readcert (app_t app, const char *certid,
4432              unsigned char **r_cert, size_t *r_certlen)
4433 {
4434   gpg_error_t err;
4435   cdf_object_t cdf;
4436
4437   *r_cert = NULL;
4438   *r_certlen = 0;
4439   err = cdf_object_from_certid (app, certid, &cdf);
4440   if (!err)
4441     err = readcert_by_cdf (app, cdf, r_cert, r_certlen);
4442   return err;
4443 }
4444
4445
4446 /* Sort helper for an array of authentication objects.  */
4447 static int
4448 compare_aodf_objid (const void *arg_a, const void *arg_b)
4449 {
4450   const aodf_object_t a = *(const aodf_object_t *)arg_a;
4451   const aodf_object_t b = *(const aodf_object_t *)arg_b;
4452   int rc;
4453
4454   rc = memcmp (a->objid, b->objid,
4455                a->objidlen < b->objidlen? a->objidlen : b->objidlen);
4456   if (!rc)
4457     {
4458       if (a->objidlen < b->objidlen)
4459         rc = -1;
4460       else if (a->objidlen > b->objidlen)
4461         rc = 1;
4462     }
4463   return rc;
4464 }
4465
4466
4467 static void
4468 send_key_fpr_line (ctrl_t ctrl, int number, const unsigned char *fpr)
4469 {
4470   char buf[41];
4471   char numbuf[25];
4472
4473   bin2hex (fpr, 20, buf);
4474   if (number == -1)
4475     *numbuf = 0; /* Don't print the key number */
4476   else
4477     snprintf (numbuf, sizeof numbuf, "%d", number);
4478   send_status_info (ctrl, "KEY-FPR",
4479                     numbuf, (size_t)strlen(numbuf),
4480                     buf, (size_t)strlen (buf),
4481                     NULL, 0);
4482 }
4483
4484
4485 /* If possible Emit a FPR-KEY status line for the private key object
4486  * PRKDF using NUMBER as index.  */
4487 static void
4488 send_key_fpr (app_t app, ctrl_t ctrl, prkdf_object_t prkdf, int number)
4489 {
4490   gpg_error_t err;
4491   cdf_object_t cdf;
4492   unsigned char *pk, *fixed_pk;
4493   size_t pklen, fixed_pklen;
4494   const unsigned char *m, *e, *q;
4495   size_t mlen, elen, qlen;
4496   unsigned char fpr20[20];
4497
4498   if (cdf_object_from_objid (app, prkdf->objidlen, prkdf->objid, &cdf)
4499       && cdf_object_from_label (app, prkdf->label, &cdf))
4500     return;
4501   if (!cdf->cert)
4502     readcert_by_cdf (app, cdf, NULL, NULL);
4503   if (!cdf->cert)
4504     return;
4505   if (!prkdf->have_keytime)
4506     return;
4507   pk = ksba_cert_get_public_key (cdf->cert);
4508   if (!pk)
4509     return;
4510   pklen = gcry_sexp_canon_len (pk, 0, NULL, &err);
4511
4512   if (uncompress_ecc_q_in_canon_sexp (pk, pklen, &fixed_pk, &fixed_pklen))
4513     {
4514       xfree (pk);
4515       return;
4516     }
4517   if (fixed_pk)
4518     {
4519       xfree (pk); pk = NULL;
4520       pk = fixed_pk;
4521       pklen = fixed_pklen;
4522     }
4523
4524   switch (prkdf->keyalgo)
4525     {
4526     case GCRY_PK_RSA:
4527       if (!get_rsa_pk_from_canon_sexp (pk, pklen,
4528                                        &m, &mlen, &e, &elen)
4529           && !compute_openpgp_fpr_rsa (4,
4530                                        prkdf->keytime,
4531                                        m, mlen, e, elen,
4532                                        fpr20, NULL))
4533         send_key_fpr_line (ctrl, number, fpr20);
4534       break;
4535
4536     case GCRY_PK_ECC:
4537     case GCRY_PK_ECDSA:
4538     case GCRY_PK_ECDH:
4539     case GCRY_PK_EDDSA:
4540       /* Note that NUMBER 2 indicates the encryption key.  */
4541       if (!get_ecc_q_from_canon_sexp (pk, pklen, &q, &qlen)
4542           && !compute_openpgp_fpr_ecc (4,
4543                                        prkdf->keytime,
4544                                        prkdf->keyalgostr,
4545                                        number == 2,
4546                                        q, qlen,
4547                                        prkdf->ecdh_kdf, 4,
4548                                        fpr20, NULL))
4549         send_key_fpr_line (ctrl, number, fpr20);
4550       break;
4551
4552     default: /* No Fingerprint for an unknown algo.  */
4553       break;
4554
4555     }
4556   xfree (pk);
4557 }
4558
4559
4560 /* Implement the GETATTR command.  This is similar to the LEARN
4561    command but returns just one value via the status interface. */
4562 static gpg_error_t
4563 do_getattr (app_t app, ctrl_t ctrl, const char *name)
4564 {
4565   gpg_error_t err;
4566   prkdf_object_t prkdf;
4567
4568   if (!strcmp (name, "$AUTHKEYID")
4569       || !strcmp (name, "$ENCRKEYID")
4570       || !strcmp (name, "$SIGNKEYID"))
4571     {
4572       char *buf;
4573
4574       /* We return the ID of the first private key capable of the
4575        * requested action.  If any gpgusage flag has been set for the
4576        * card we consult the gpgusage flags and not the regualr usage
4577        * flags.
4578        */
4579       /* FIXME: This changed: Note that we do not yet return
4580        * non_repudiation keys for $SIGNKEYID because our D-Trust
4581        * testcard uses rsaPSS, which is not supported by gpgsm and not
4582        * covered by the VS-NfD approval.  */
4583       for (prkdf = app->app_local->private_key_info; prkdf;
4584            prkdf = prkdf->next)
4585         {
4586           if (app->app_local->any_gpgusage)
4587             {
4588               if ((name[1] == 'A' && prkdf->gpgusage.auth)
4589                   || (name[1] == 'E' && prkdf->gpgusage.encr)
4590                   || (name[1] == 'S' && prkdf->gpgusage.sign))
4591                 break;
4592             }
4593           else
4594             {
4595               if ((name[1] == 'A' && (prkdf->usageflags.sign
4596                                       || prkdf->usageflags.sign_recover))
4597                   || (name[1] == 'E' && (prkdf->usageflags.decrypt
4598                                          || prkdf->usageflags.unwrap))
4599                   || (name[1] == 'S' && (prkdf->usageflags.sign
4600                                          || prkdf->usageflags.sign_recover)))
4601                 break;
4602             }
4603         }
4604       if (prkdf)
4605         {
4606           buf = keyref_from_prkdf (app, prkdf);
4607           if (!buf)
4608             return gpg_error_from_syserror ();
4609
4610           send_status_info (ctrl, name, buf, strlen (buf), NULL, 0);
4611           xfree (buf);
4612         }
4613       return 0;
4614     }
4615   else if (!strcmp (name, "$DISPSERIALNO"))
4616     {
4617       /* For certain cards we return special IDs.  There is no
4618          general rule for it so we need to decide case by case. */
4619       if (app->app_local->card_type == CARD_TYPE_BELPIC)
4620         {
4621           /* The eID card has a card number printed on the front matter
4622              which seems to be a good indication. */
4623           unsigned char *buffer;
4624           const unsigned char *p;
4625           size_t buflen, n;
4626           unsigned short path[] = { 0x3F00, 0xDF01, 0x4031 };
4627
4628           err = select_ef_by_path (app, path, DIM(path) );
4629           if (!err)
4630             err = iso7816_read_binary (app_get_slot (app), 0, 0,
4631                                        &buffer, &buflen);
4632           if (err)
4633             {
4634               log_error ("p15: error accessing EF(ID): %s\n",
4635                          gpg_strerror (err));
4636               return err;
4637             }
4638
4639           p = find_tlv (buffer, buflen, 1, &n);
4640           if (p && n == 12)
4641             {
4642               char tmp[12+2+1];
4643               memcpy (tmp, p, 3);
4644               tmp[3] = '-';
4645               memcpy (tmp+4, p+3, 7);
4646               tmp[11] = '-';
4647               memcpy (tmp+12, p+10, 2);
4648               tmp[14] = 0;
4649               send_status_info (ctrl, name, tmp, strlen (tmp), NULL, 0);
4650               xfree (buffer);
4651               return 0;
4652             }
4653           xfree (buffer);
4654         }
4655       else
4656         {
4657           char *sn;
4658
4659           /* We use the first private key object which has a serial
4660            * number set.  If none was found, we parse the first
4661            * object and see whether this has then a serial number.  */
4662           for (prkdf = app->app_local->private_key_info; prkdf;
4663                prkdf = prkdf->next)
4664             if (prkdf->serial_number)
4665               break;
4666           if (!prkdf && app->app_local->private_key_info)
4667             {
4668               prkdf = app->app_local->private_key_info;
4669               keygrip_from_prkdf (app, prkdf);
4670               if (!prkdf->serial_number)
4671                 prkdf = NULL;
4672             }
4673           sn = get_dispserialno (app, prkdf);
4674           /* Unless there is a bogus S/N in the cert, or the product
4675            * has a different strategy for the display-s/n, we should
4676            * have a suitable one from the cert now.  */
4677           if (sn)
4678             {
4679               err = send_status_printf (ctrl, name, "%s", sn);
4680               xfree (sn);
4681               return err;
4682             }
4683         }
4684       /* No abbreviated serial number. */
4685     }
4686   else if (!strcmp (name, "MANUFACTURER"))
4687     {
4688       if (app->app_local->manufacturer_id
4689           && !strchr (app->app_local->manufacturer_id, '[')
4690           && app->app_local->card_product)
4691         return send_status_printf (ctrl, "MANUFACTURER", "0 %s [%s]",
4692                               app->app_local->manufacturer_id,
4693                               cardproduct2str (app->app_local->card_product));
4694       else if (app->app_local->manufacturer_id)
4695         return send_status_printf (ctrl, "MANUFACTURER", "0 %s",
4696                                    app->app_local->manufacturer_id);
4697       else
4698         return 0;
4699     }
4700   else if (!strcmp (name, "CHV-STATUS") || !strcmp (name, "CHV-LABEL"))
4701     {
4702       int is_label = (name[4] == 'L');
4703       aodf_object_t aodf;
4704       aodf_object_t aodfarray[16];
4705       int naodf = 0;
4706       membuf_t mb;
4707       char *p;
4708       int i;
4709
4710       /* Put the AODFs into an array for easier sorting.  Note that we
4711        * handle onl the first 16 encountrer which should be more than
4712        * enough.  */
4713       for (aodf = app->app_local->auth_object_info;
4714            aodf && naodf < DIM(aodfarray); aodf = aodf->next)
4715         if (aodf->objidlen && aodf->pin_reference_valid)
4716           aodfarray[naodf++] = aodf;
4717       qsort (aodfarray, naodf, sizeof *aodfarray, compare_aodf_objid);
4718
4719       init_membuf (&mb, 256);
4720       for (i = 0; i < naodf; i++)
4721         {
4722           /* int j; */
4723           /* log_debug ("p15: AODF[%d] pinref=%lu id=", */
4724           /*            i, aodfarray[i]->pin_reference); */
4725           /* for (j=0; j < aodfarray[i]->objidlen; j++) */
4726           /*   log_printf ("%02X", aodfarray[i]->objid[j]); */
4727           /* Note that there is no need to percent escape the label
4728            * because all white space have been replaced by '_'.  */
4729           if (is_label)
4730             put_membuf_printf (&mb, "%s%s", i? " ":"",
4731                                (aodfarray[i]->label
4732                                 && *aodfarray[i]->label)?
4733                                aodfarray[i]->label:"X");
4734           else
4735             put_membuf_printf
4736               (&mb, "%s%d", i? " ":"",
4737                iso7816_verify_status (app_get_slot (app),
4738                                       aodfarray[i]->pin_reference));
4739         }
4740       put_membuf( &mb, "", 1);
4741       p = get_membuf (&mb, NULL);
4742       if (!p)
4743         return gpg_error_from_syserror ();
4744       err = send_status_direct (ctrl, is_label? "CHV-LABEL":"CHV-STATUS", p);
4745       xfree (p);
4746       return err;
4747     }
4748   else if (!strcmp (name, "KEY-LABEL"))
4749     {
4750       /* Send KEY-LABEL lines for all private key objects.  */
4751       const char *label;
4752       char *idbuf, *labelbuf;
4753
4754       for (prkdf = app->app_local->private_key_info; prkdf;
4755            prkdf = prkdf->next)
4756         {
4757           idbuf = keyref_from_prkdf (app, prkdf);
4758           if (!idbuf)
4759             return gpg_error_from_syserror ();
4760
4761           label = (prkdf->label && *prkdf->label)? prkdf->label : "-";
4762           labelbuf = percent_data_escape (0, NULL, label, strlen (label));
4763           if (!labelbuf)
4764             {
4765               xfree (idbuf);
4766               return gpg_error_from_syserror ();
4767             }
4768
4769           send_status_info (ctrl, name,
4770                             idbuf, strlen (idbuf),
4771                             labelbuf, strlen(labelbuf),
4772                             NULL, 0);
4773           xfree (idbuf);
4774           xfree (labelbuf);
4775         }
4776       return 0;
4777     }
4778   else if (!strcmp (name, "KEY-FPR"))
4779     {
4780       /* Send KEY-FPR for the two openpgp keys. */
4781       for (prkdf = app->app_local->private_key_info; prkdf;
4782            prkdf = prkdf->next)
4783         {
4784           if (app->app_local->any_gpgusage)
4785             {
4786               if (prkdf->gpgusage.sign)
4787                 break;
4788             }
4789           else
4790             {
4791               if (prkdf->usageflags.sign || prkdf->usageflags.sign_recover)
4792                 break;
4793             }
4794         }
4795       if (prkdf)
4796         send_key_fpr (app, ctrl, prkdf, 1);
4797       for (prkdf = app->app_local->private_key_info; prkdf;
4798            prkdf = prkdf->next)
4799         {
4800           if (app->app_local->any_gpgusage)
4801             {
4802               if (prkdf->gpgusage.encr)
4803                 break;
4804             }
4805           else
4806             {
4807               if (prkdf->usageflags.decrypt || prkdf->usageflags.unwrap)
4808                 break;
4809             }
4810         }
4811       if (prkdf)
4812         send_key_fpr (app, ctrl, prkdf, 2);
4813       return 0;
4814     }
4815
4816   return gpg_error (GPG_ERR_INV_NAME);
4817 }
4818
4819
4820
4821
4822 /* Micardo cards require special treatment. This is a helper for the
4823    crypto functions to manage the security environment.  We expect that
4824    the key file has already been selected. FID is the one of the
4825    selected key. */
4826 static gpg_error_t
4827 micardo_mse (app_t app, unsigned short fid)
4828 {
4829   gpg_error_t err;
4830   int recno;
4831   unsigned short refdata = 0;
4832   int se_num;
4833   unsigned char msebuf[10];
4834
4835   /* Read the KeyD file containing extra information on keys. */
4836   err = iso7816_select_file (app_get_slot (app), 0x0013, 0);
4837   if (err)
4838     {
4839       log_error ("p15: error reading EF_keyD: %s\n", gpg_strerror (err));
4840       return err;
4841     }
4842
4843   for (recno = 1, se_num = -1; ; recno++)
4844     {
4845       unsigned char *buffer;
4846       size_t buflen;
4847       size_t n, nn;
4848       const unsigned char *p, *pp;
4849
4850       err = iso7816_read_record (app_get_slot (app), recno, 1, 0,
4851                                  &buffer, &buflen);
4852       if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
4853         break; /* ready */
4854       if (err)
4855         {
4856           log_error ("p15: error reading EF_keyD record: %s\n",
4857                      gpg_strerror (err));
4858           return err;
4859         }
4860       if (opt.verbose)
4861         {
4862           log_info (buffer, buflen, "p15: keyD record: ");
4863           log_printhex (buffer, buflen, "");
4864         }
4865       p = find_tlv (buffer, buflen, 0x83, &n);
4866       if (p && n == 4 && ((p[2]<<8)|p[3]) == fid)
4867         {
4868           refdata = ((p[0]<<8)|p[1]);
4869           /* Locate the SE DO and the there included sec env number. */
4870           p = find_tlv (buffer, buflen, 0x7b, &n);
4871           if (p && n)
4872             {
4873               pp = find_tlv (p, n, 0x80, &nn);
4874               if (pp && nn == 1)
4875                 {
4876                   se_num = *pp;
4877                   xfree (buffer);
4878                   break; /* found. */
4879                 }
4880             }
4881         }
4882       xfree (buffer);
4883     }
4884   if (se_num == -1)
4885     {
4886       log_error ("p15: CRT for keyfile %04hX not found\n", fid);
4887       return gpg_error (GPG_ERR_NOT_FOUND);
4888     }
4889
4890
4891   /* Restore the security environment to SE_NUM if needed */
4892   if (se_num)
4893     {
4894       err = iso7816_manage_security_env (app_get_slot (app),
4895                                          0xf3, se_num, NULL, 0);
4896       if (err)
4897         {
4898           log_error ("p15: restoring SE to %d failed: %s\n",
4899                      se_num, gpg_strerror (err));
4900           return err;
4901         }
4902     }
4903
4904   /* Set the DST reference data. */
4905   msebuf[0] = 0x83;
4906   msebuf[1] = 0x03;
4907   msebuf[2] = 0x80;
4908   msebuf[3] = (refdata >> 8);
4909   msebuf[4] = refdata;
4910   err = iso7816_manage_security_env (app_get_slot (app), 0x41, 0xb6, msebuf, 5);
4911   if (err)
4912     {
4913       log_error ("p15: setting SE to reference file %04hX failed: %s\n",
4914                  refdata, gpg_strerror (err));
4915       return err;
4916     }
4917   return 0;
4918 }
4919
4920
4921
4922 /* Prepare the verification of the PIN for the key PRKDF by checking
4923  * the AODF and selecting the key file.  KEYREF is used for error
4924  * messages.  AODF may be NULL if no verification needs to be done. */
4925 static gpg_error_t
4926 prepare_verify_pin (app_t app, const char *keyref,
4927                     prkdf_object_t prkdf, aodf_object_t aodf)
4928 {
4929   gpg_error_t err;
4930   int i;
4931
4932   if (aodf)
4933     {
4934       if (opt.verbose)
4935         {
4936           log_info ("p15: using AODF %04hX id=", aodf->fid);
4937           for (i=0; i < aodf->objidlen; i++)
4938             log_printf ("%02X", aodf->objid[i]);
4939           log_printf ("\n");
4940         }
4941
4942       if (aodf->authid && opt.verbose)
4943         log_info ("p15: PIN is controlled by another authentication token\n");
4944
4945       if (aodf->pinflags.integrity_protected
4946           || aodf->pinflags.confidentiality_protected)
4947         {
4948           log_error ("p15: PIN verification requires"
4949                      " unsupported protection method\n");
4950           return gpg_error (GPG_ERR_BAD_PIN_METHOD);
4951         }
4952       if (!aodf->stored_length && aodf->pinflags.needs_padding)
4953         {
4954           log_error ("p15: PIN verification requires"
4955                      " padding but no length known\n");
4956           return gpg_error (GPG_ERR_INV_CARD);
4957         }
4958     }
4959
4960
4961   if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
4962     {
4963       /* According to our protocol analysis we need to select a
4964        * special AID here.  Before that the master file needs to be
4965        * selected.  (RID A000000167 is assigned to IBM) */
4966       static char const dtrust_aid[] =
4967         { 0xA0, 0x00, 0x00, 0x01, 0x67, 0x45, 0x53, 0x49, 0x47, 0x4E };
4968
4969       err = iso7816_select_mf (app_get_slot (app));
4970       if (!err)
4971         err = iso7816_select_application (app_get_slot (app),
4972                                           dtrust_aid, sizeof dtrust_aid, 0);
4973       if (err)
4974         log_error ("p15: error selecting D-TRUST's AID for key %s: %s\n",
4975                    keyref, gpg_strerror (err));
4976     }
4977   else if (prkdf)
4978     {
4979       /* Standard case: Select the key file.  Note that this may
4980        * change the security environment thus we need to do it before
4981        * PIN verification. */
4982       err = select_ef_by_path (app, prkdf->path, prkdf->pathlen);
4983       if (err)
4984         log_error ("p15: error selecting file for key %s: %s\n",
4985                    keyref, gpg_strerror (err));
4986     }
4987   else
4988     {
4989       log_info ("p15: skipping EF selection for auth object '%s'\n", keyref);
4990       err = 0;
4991     }
4992
4993   return err;
4994 }
4995
4996
4997 static int
4998 any_control_or_space (const char *string)
4999 {
5000   const unsigned char *s;
5001
5002   for (s = string; *s; s++)
5003     if (*s <= 0x20 || *s >= 0x7f)
5004       return 1;
5005   return 0;
5006 }
5007
5008 static int
5009 any_control_or_space_mem (const void *buffer, size_t buflen)
5010 {
5011   const unsigned char *s;
5012
5013   for (s = buffer; buflen; s++, buflen--)
5014     if (*s <= 0x20 || *s >= 0x7f)
5015       return 1;
5016   return 0;
5017 }
5018
5019
5020 /* Return a malloced serial number to be shown to the user.  PRKDF is
5021  * used to get it from a certificate; PRKDF may be NULL.  */
5022 static char *
5023 get_dispserialno (app_t app, prkdf_object_t prkdf)
5024 {
5025   char *serial;
5026   const unsigned char *s;
5027   int i;
5028   size_t n;
5029
5030   /* We prefer the SerialNumber RDN from the Subject-DN but we don't
5031    * use it if it features a percent sign (special character in pin
5032    * prompts) or has any control character.  For some cards we use a
5033    * different strategy.  */
5034   if (app->app_local->card_product == CARD_PRODUCT_RSCS)
5035     {
5036       /* We use only the right 8 hex digits.  */
5037       serial = app_get_serialno (app);
5038       if (serial && (n=strlen (serial)) > 8)
5039         memmove (serial, serial + n - 8, 9);
5040     }
5041   else if (IS_CARDOS_5 (app) && app->app_local->manufacturer_id
5042            && !ascii_strcasecmp (app->app_local->manufacturer_id,
5043                                  "Technology Nexus")
5044            && app->serialno && app->serialnolen == 4+9
5045            && !memcmp (app->serialno, "\xff\x00\x00\xff", 4)
5046            && !any_control_or_space_mem (app->serialno + 4, 9))
5047     {
5048       /* Sample: ff0000ff354830313232363537 -> "5H01 2265 7" */
5049       serial = xtrymalloc (9+2+1);
5050       if (serial)
5051         {
5052           s = app->serialno + 4;
5053           for (i=0; i < 4; i++)
5054             serial[i] = *s++;
5055           serial[i++] = ' ';
5056           for (; i < 9; i++)
5057             serial[i] = *s++;
5058           serial[i++] = ' ';
5059           serial[i++] = *s;
5060           serial[i] = 0;
5061         }
5062     }
5063   else if (prkdf && prkdf->serial_number && *prkdf->serial_number
5064       && !strchr (prkdf->serial_number, '%')
5065       && !any_control_or_space (prkdf->serial_number))
5066     {
5067       serial = xtrystrdup (prkdf->serial_number);
5068     }
5069   else
5070     {
5071       serial = app_get_serialno (app);
5072     }
5073
5074   return serial;
5075 }
5076
5077
5078 /* Return an allocated string to be used as prompt.  PRKDF may be
5079  * NULL.  Returns NULL on malloc error.  */
5080 static char *
5081 make_pin_prompt (app_t app, int remaining, const char *firstline,
5082                  prkdf_object_t prkdf)
5083 {
5084   char *serial, *tmpbuf, *result;
5085   const char *holder = NULL;
5086
5087   serial = get_dispserialno (app, prkdf);
5088
5089   if (app->app_local->card_product == CARD_PRODUCT_GENUA)
5090     {
5091       /* The label of the first non SO-PIN is used for the holder.  */
5092       aodf_object_t aodf;
5093
5094       for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5095         if (aodf->auth_type == AUTH_TYPE_PIN
5096             && !aodf->pinflags.so_pin
5097             && aodf->label)
5098           {
5099             holder = aodf->label;
5100             break;
5101           }
5102     }
5103
5104   if (holder)
5105     ;
5106   else if (prkdf && prkdf->common_name)
5107     holder = prkdf->common_name;
5108   else if (app->app_local->token_label)
5109     holder = app->app_local->token_label;
5110   else
5111     holder = "";
5112
5113   /* TRANSLATORS: Put a \x1f right before a colon.  This can be
5114    * used by pinentry to nicely align the names and values.  Keep
5115    * the %s at the start and end of the string.  */
5116   result = xtryasprintf (_("%s"
5117                            "Number\x1f: %s%%0A"
5118                            "Holder\x1f: %s"
5119                            "%s"),
5120                          "\x1e",
5121                          serial,
5122                          holder,
5123                          "");
5124   xfree (serial);
5125   if (!result)
5126     return NULL; /* Out of core.  */
5127
5128   /* Append a "remaining attempts" info if needed.  */
5129   if (remaining != -1 && remaining < 3)
5130     {
5131       char *rembuf;
5132
5133       /* TRANSLATORS: This is the number of remaining attempts to
5134        * enter a PIN.  Use %%0A (double-percent,0A) for a linefeed. */
5135       rembuf = xtryasprintf (_("Remaining attempts: %d"), remaining);
5136       if (rembuf)
5137         {
5138           tmpbuf = strconcat (firstline, "%0A%0A", result,
5139                               "%0A%0A", rembuf, NULL);
5140           xfree (rembuf);
5141         }
5142       else
5143         tmpbuf = NULL;
5144       xfree (result);
5145       result = tmpbuf;
5146     }
5147   else
5148     {
5149       tmpbuf = strconcat (firstline, "%0A%0A", result, NULL);
5150       xfree (result);
5151       result = tmpbuf;
5152     }
5153
5154   return result;
5155 }
5156
5157
5158 /* Given the private key object PRKDF and its authentication object
5159  * AODF ask for the PIN and verify that PIN.  If AODF is NULL, no
5160  * authentication is done.  */
5161 static gpg_error_t
5162 verify_pin (app_t app,
5163             gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg,
5164             prkdf_object_t prkdf, aodf_object_t aodf)
5165 {
5166   gpg_error_t err;
5167   char *pinvalue;
5168   size_t pinvaluelen;
5169   const char *label;
5170   const char *errstr;
5171   const char *s;
5172   int remaining;
5173   int pin_reference;
5174   int verified = 0;
5175   int i;
5176
5177   if (!aodf)
5178     return 0;
5179
5180   pin_reference = aodf->pin_reference_valid? aodf->pin_reference : 0;
5181
5182   if (IS_CARDOS_5 (app))
5183     {
5184       /* We know that this card supports a verify status check.  Note
5185        * that in contrast to PIV cards ISO7816_VERIFY_NOT_NEEDED is
5186        * not supported.  We also don't use the pin_verified cache
5187        * status because that is not as reliable as to ask the card
5188        * about its state.  */
5189       if (prkdf)  /* Clear the cache which we don't use.  */
5190         prkdf->pin_verified = 0;
5191
5192       remaining = iso7816_verify_status (app_get_slot (app), pin_reference);
5193       if (remaining == ISO7816_VERIFY_NOT_NEEDED)
5194         {
5195           verified = 1;
5196           remaining = -1;
5197         }
5198       else if (remaining < 0)
5199         remaining = -1; /* We don't care about the concrete error.  */
5200       else if (remaining < 3)
5201         log_info ("p15: PIN has %d attempts left\n", remaining);
5202     }
5203   else
5204     remaining = -1;  /* Unknown.  */
5205
5206   /* Check whether we already verified it.  */
5207   if (prkdf && (prkdf->pin_verified || verified))
5208     return 0;  /* Already done.  */
5209
5210   if (prkdf
5211       && prkdf->usageflags.non_repudiation
5212       && (app->app_local->card_type == CARD_TYPE_BELPIC
5213           || app->app_local->card_product == CARD_PRODUCT_DTRUST))
5214     label = _("||Please enter the PIN for the key to create "
5215               "qualified signatures.");
5216   else if (aodf->pinflags.so_pin)
5217     label = _("|A|Please enter the Admin PIN");
5218   else if (aodf->pinflags.unblocking_pin)
5219     label = _("|P|Please enter the PIN Unblocking Code (PUK) "
5220               "for the standard keys.");
5221   else
5222     label = _("||Please enter the PIN for the standard keys.");
5223
5224   {
5225     char *prompt = make_pin_prompt (app, remaining, label, prkdf);
5226     if (!prompt)
5227       err = gpg_error_from_syserror ();
5228     else
5229       err = pincb (pincb_arg, prompt, &pinvalue);
5230     xfree (prompt);
5231   }
5232   if (err)
5233     {
5234       log_info ("p15: PIN callback returned error: %s\n", gpg_strerror (err));
5235       return err;
5236     }
5237
5238   /* We might need to cope with UTF8 things here.  Not sure how
5239      min_length etc. are exactly defined, for now we take them as
5240      a plain octet count. */
5241   if (strlen (pinvalue) < aodf->min_length)
5242     {
5243       log_error ("p15: PIN is too short; minimum length is %lu\n",
5244                  aodf->min_length);
5245       err = gpg_error (GPG_ERR_BAD_PIN);
5246     }
5247   else if (aodf->stored_length && strlen (pinvalue) > aodf->stored_length)
5248     {
5249       /* This would otherwise truncate the PIN silently. */
5250       log_error ("p15: PIN is too large; maximum length is %lu\n",
5251                  aodf->stored_length);
5252       err = gpg_error (GPG_ERR_BAD_PIN);
5253     }
5254   else if (aodf->max_length_valid && strlen (pinvalue) > aodf->max_length)
5255     {
5256       log_error ("p15: PIN is too large; maximum length is %lu\n",
5257                  aodf->max_length);
5258       err = gpg_error (GPG_ERR_BAD_PIN);
5259     }
5260
5261   if (err)
5262     {
5263       xfree (pinvalue);
5264       return err;
5265     }
5266
5267   errstr = NULL;
5268   err = 0;
5269   switch (aodf->pintype)
5270     {
5271     case PIN_TYPE_BCD:
5272     case PIN_TYPE_ASCII_NUMERIC:
5273       for (s=pinvalue; digitp (s); s++)
5274         ;
5275       if (*s)
5276         {
5277           errstr = "Non-numeric digits found in PIN";
5278           err = gpg_error (GPG_ERR_BAD_PIN);
5279         }
5280       break;
5281     case PIN_TYPE_UTF8:
5282       break;
5283     case PIN_TYPE_HALF_NIBBLE_BCD:
5284       errstr = "PIN type Half-Nibble-BCD is not supported";
5285       break;
5286     case PIN_TYPE_ISO9564_1:
5287       errstr = "PIN type ISO9564-1 is not supported";
5288       break;
5289     default:
5290       errstr = "Unknown PIN type";
5291       break;
5292     }
5293   if (errstr)
5294     {
5295       log_error ("p15: can't verify PIN: %s\n", errstr);
5296       xfree (pinvalue);
5297       return err? err : gpg_error (GPG_ERR_BAD_PIN_METHOD);
5298     }
5299
5300
5301   if (aodf->pintype == PIN_TYPE_BCD )
5302     {
5303       char *paddedpin;
5304       int ndigits;
5305
5306       for (ndigits=0, s=pinvalue; *s; ndigits++, s++)
5307         ;
5308       paddedpin = xtrymalloc (aodf->stored_length+1);
5309       if (!paddedpin)
5310         {
5311           err = gpg_error_from_syserror ();
5312           xfree (pinvalue);
5313           return err;
5314         }
5315
5316       i = 0;
5317       paddedpin[i++] = 0x20 | (ndigits & 0x0f);
5318       for (s=pinvalue; i < aodf->stored_length && *s && s[1]; s = s+2 )
5319         paddedpin[i++] = (((*s - '0') << 4) | ((s[1] - '0') & 0x0f));
5320       if (i < aodf->stored_length && *s)
5321         paddedpin[i++] = (((*s - '0') << 4)
5322                           |((aodf->pad_char_valid?aodf->pad_char:0)&0x0f));
5323
5324       if (aodf->pinflags.needs_padding)
5325         {
5326           while (i < aodf->stored_length)
5327             paddedpin[i++] = aodf->pad_char_valid? aodf->pad_char : 0;
5328         }
5329
5330       xfree (pinvalue);
5331       pinvalue = paddedpin;
5332       pinvaluelen = i;
5333     }
5334   else if (aodf->pinflags.needs_padding)
5335     {
5336       char *paddedpin;
5337
5338       paddedpin = xtrymalloc (aodf->stored_length+1);
5339       if (!paddedpin)
5340         {
5341           err = gpg_error_from_syserror ();
5342           xfree (pinvalue);
5343           return err;
5344         }
5345       for (i=0, s=pinvalue; i < aodf->stored_length && *s; i++, s++)
5346         paddedpin[i] = *s;
5347       /* Not sure what padding char to use if none has been set.
5348          For now we use 0x00; maybe a space would be better. */
5349       for (; i < aodf->stored_length; i++)
5350         paddedpin[i] = aodf->pad_char_valid? aodf->pad_char : 0;
5351       paddedpin[i] = 0;
5352       pinvaluelen = i;
5353       xfree (pinvalue);
5354       pinvalue = paddedpin;
5355     }
5356   else
5357     pinvaluelen = strlen (pinvalue);
5358
5359   /* log_printhex (pinvalue, pinvaluelen, */
5360   /*               "about to verify with ref %lu pin:", pin_reference); */
5361   err = iso7816_verify (app_get_slot (app), pin_reference,
5362                         pinvalue, pinvaluelen);
5363   xfree (pinvalue);
5364   if (err)
5365     {
5366       log_error ("p15: PIN verification failed: %s\n", gpg_strerror (err));
5367       return err;
5368     }
5369   if (opt.verbose)
5370     log_info ("p15: PIN verification succeeded\n");
5371   if (prkdf)
5372     prkdf->pin_verified = 1;
5373
5374   return 0;
5375 }
5376
5377
5378
5379
5380 /* Handler for the PKSIGN command.
5381
5382    Create the signature and return the allocated result in OUTDATA.
5383    If a PIN is required, the PINCB will be used to ask for the PIN;
5384    that callback should return the PIN in an allocated buffer and
5385    store that as the 3rd argument.  */
5386 static gpg_error_t
5387 do_sign (app_t app, ctrl_t ctrl, const char *keyidstr, int hashalgo,
5388          gpg_error_t (*pincb)(void*, const char *, char **),
5389          void *pincb_arg,
5390          const void *indata, size_t indatalen,
5391          unsigned char **outdata, size_t *outdatalen )
5392 {
5393   gpg_error_t err;
5394   prkdf_object_t prkdf;    /* The private key object. */
5395   aodf_object_t aodf;      /* The associated authentication object. */
5396   int mse_done = 0;        /* Set to true if the MSE has been done. */
5397   unsigned int digestlen;  /* Length of the hash.  */
5398   int exmode, le_value;
5399   unsigned char oidbuf[64];
5400   size_t oidbuflen;
5401   size_t n;
5402   unsigned char *indata_buffer = NULL; /* Malloced helper.  */
5403
5404   (void)ctrl;
5405
5406   if (!keyidstr || !*keyidstr || !indatalen)
5407     return gpg_error (GPG_ERR_INV_VALUE);
5408
5409   err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5410   if (err)
5411     return err;
5412   if (!(prkdf->usageflags.sign
5413         || prkdf->usageflags.sign_recover
5414         || prkdf->usageflags.non_repudiation
5415         || prkdf->gpgusage.cert
5416         || prkdf->gpgusage.sign
5417         || prkdf->gpgusage.auth ))
5418     {
5419       log_error ("p15: key %s may not be used for signing\n", keyidstr);
5420       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
5421     }
5422
5423   if (!prkdf->authid)
5424     {
5425       log_error ("p15: no authentication object defined for %s\n", keyidstr);
5426       /* fixme: we might want to go ahead and do without PIN
5427          verification. */
5428       return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
5429     }
5430
5431   /* Find the authentication object to this private key object. */
5432   for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5433     if (aodf->objidlen == prkdf->authidlen
5434         && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
5435       break;
5436   if (!aodf)
5437     log_info ("p15: no authentication for %s needed\n", keyidstr);
5438
5439   /* We need some more info about the key - get the keygrip to
5440    * populate these fields.  */
5441   err = keygrip_from_prkdf (app, prkdf);
5442   if (err)
5443     {
5444       log_error ("p15: keygrip_from_prkdf failed: %s\n", gpg_strerror (err));
5445       return err;
5446     }
5447
5448
5449   digestlen = gcry_md_get_algo_dlen (hashalgo);
5450
5451   /* We handle ECC separately from RSA so that we do not need to touch
5452    * working code.  In particular we prepare the input data before the
5453    * verify and a possible MSE.  */
5454   if (prkdf->is_ecc)
5455     {
5456       if (digestlen != 32 && digestlen != 48 && digestlen != 64)
5457         {
5458           log_error ("p15: ECC signing not possible: dlen=%u\n", digestlen);
5459           err = gpg_error (GPG_ERR_DIGEST_ALGO);
5460           goto leave;
5461         }
5462
5463       if (indatalen == digestlen)
5464         ; /* Already prepared.  */
5465       else if (indatalen > digestlen)
5466         {
5467           /* Assume a PKCS#1 prefix and remove it.  */
5468           oidbuflen = sizeof oidbuf;
5469           err = gcry_md_get_asnoid (hashalgo, &oidbuf, &oidbuflen);
5470           if (err)
5471             {
5472               log_error ("p15: no OID for hash algo %d\n", hashalgo);
5473               err = gpg_error (GPG_ERR_INTERNAL);
5474               goto leave;
5475             }
5476           if (indatalen != oidbuflen + digestlen
5477               || memcmp (indata, oidbuf, oidbuflen))
5478             {
5479               log_error ("p15: input data too long for ECC: len=%zu\n",
5480                          indatalen);
5481               err = gpg_error (GPG_ERR_INV_VALUE);
5482               goto leave;
5483             }
5484           indata = (const char*)indata + oidbuflen;
5485           indatalen -= oidbuflen;
5486         }
5487       else
5488         {
5489           log_error ("p15: input data too short for ECC: len=%zu\n",
5490                      indatalen);
5491           err = gpg_error (GPG_ERR_INV_VALUE);
5492           goto leave;
5493         }
5494     }
5495   else /* Prepare RSA input.  */
5496     {
5497       unsigned int framelen;
5498       unsigned char *frame;
5499       int i;
5500
5501       framelen = (prkdf->keynbits+7) / 8;
5502       if (!framelen)
5503         {
5504           log_error ("p15: key length unknown"
5505                      " - can't prepare PKCS#v1.5 frame\n");
5506           err = gpg_error (GPG_ERR_INV_VALUE);
5507           goto leave;
5508         }
5509
5510       oidbuflen = sizeof oidbuf;
5511       if (!hashalgo)
5512         {
5513           /* We assume that indata already has the required
5514            * digestinfo; thus merely prepend the padding below.  */
5515         }
5516       else if ((err = gcry_md_get_asnoid (hashalgo, &oidbuf, &oidbuflen)))
5517         {
5518           log_debug ("p15: no OID for hash algo %d\n", hashalgo);
5519           goto leave;
5520         }
5521       else
5522         {
5523           if (indatalen == digestlen)
5524             {
5525               /* Plain hash in INDATA; prepend the digestinfo.  */
5526               indata_buffer = xtrymalloc (oidbuflen + indatalen);
5527               if (!indata_buffer)
5528                 {
5529                   err = gpg_error_from_syserror ();
5530                   goto leave;
5531                 }
5532               memcpy (indata_buffer, oidbuf, oidbuflen);
5533               memcpy (indata_buffer+oidbuflen, indata, indatalen);
5534               indata = indata_buffer;
5535               indatalen = oidbuflen + indatalen;
5536             }
5537           else if (indatalen == oidbuflen + digestlen
5538                    && !memcmp (indata, oidbuf, oidbuflen))
5539             ; /* We already got the correct prefix.  */
5540           else
5541             {
5542               err = gpg_error (GPG_ERR_INV_VALUE);
5543               log_error ("p15: bad input for signing with RSA and hash %d\n",
5544                          hashalgo);
5545               goto leave;
5546             }
5547         }
5548       /* Now prepend the pkcs#v1.5 padding.  We require at least 8
5549        * byte of padding and 3 extra bytes for the prefix and the
5550        * delimiting nul.  */
5551       if (!indatalen || indatalen + 8 + 4 > framelen)
5552         {
5553           err = gpg_error (GPG_ERR_INV_VALUE);
5554           log_error ("p15: input does not fit into a %u bit PKCS#v1.5 frame\n",
5555                      8*framelen);
5556           goto leave;
5557         }
5558       frame = xtrymalloc (framelen);
5559       if (!frame)
5560         {
5561           err = gpg_error_from_syserror ();
5562           goto leave;
5563         }
5564       if (app->app_local->card_type == CARD_TYPE_BELPIC)
5565         {
5566           /* This card wants only the plain hash w/o any prefix.  */
5567           /* FIXME: We may want to remove this code because it is unlikely
5568            * that such cards are still in use.  */
5569           memcpy (frame, indata, indatalen);
5570           framelen = indatalen;
5571         }
5572       else
5573         {
5574           n = 0;
5575           frame[n++] = 0;
5576           frame[n++] = 1; /* Block type. */
5577           i = framelen - indatalen - 3 ;
5578           memset (frame+n, 0xff, i);
5579           n += i;
5580           frame[n++] = 0; /* Delimiter.  */
5581           memcpy (frame+n, indata, indatalen);
5582           n += indatalen;
5583           log_assert (n == framelen);
5584         }
5585       /* And now put it into the indata_buffer.  */
5586       xfree (indata_buffer);
5587       indata_buffer = frame;
5588       indata = indata_buffer;
5589       indatalen = framelen;
5590     }
5591
5592   /* Prepare PIN verification.  This is split so that we can do
5593    * MSE operation for some task after having selected the key file but
5594    * before sending the verify APDU.  */
5595   err = prepare_verify_pin (app, keyidstr, prkdf, aodf);
5596   if (err)
5597     return err;
5598
5599   /* Due to the fact that the non-repudiation signature on a BELPIC
5600      card requires a verify immediately before the DSO we set the
5601      MSE before we do the verification.  Other cards might also allow
5602      this but I don't want to break anything, thus we do it only
5603      for the BELPIC card here.
5604      FIXME: see comment above about these cards.   */
5605   if (app->app_local->card_type == CARD_TYPE_BELPIC)
5606     {
5607       unsigned char mse[5];
5608
5609       mse[0] = 4;    /* Length of the template. */
5610       mse[1] = 0x80; /* Algorithm reference tag. */
5611       if (hashalgo == MD_USER_TLS_MD5SHA1)
5612         mse[2] = 0x01; /* Let card do pkcs#1 0xFF padding. */
5613       else
5614         mse[2] = 0x02; /* RSASSA-PKCS1-v1.5 using SHA1. */
5615       mse[3] = 0x84; /* Private key reference tag. */
5616       mse[4] = prkdf->key_reference_valid? prkdf->key_reference : 0x82;
5617
5618       err = iso7816_manage_security_env (app_get_slot (app),
5619                                          0x41, 0xB6,
5620                                          mse, sizeof mse);
5621       mse_done = 1;
5622     }
5623   if (err)
5624     {
5625       log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5626       goto leave;
5627     }
5628
5629   /* Now that we have all the information available run the actual PIN
5630    * verification.*/
5631   err = verify_pin (app, pincb, pincb_arg, prkdf, aodf);
5632   if (err)
5633     return err;
5634
5635   /* Manage security environment needs to be tweaked for certain cards. */
5636   if (mse_done)
5637     err = 0;
5638   else if (app->app_local->card_type == CARD_TYPE_TCOS)
5639     {
5640       /* TCOS creates signatures always using the local key 0.  MSE
5641          may not be used. */
5642     }
5643   else if (app->app_local->card_type == CARD_TYPE_MICARDO)
5644     {
5645       if (!prkdf->pathlen)
5646         err = gpg_error (GPG_ERR_BUG);
5647       else
5648         err = micardo_mse (app, prkdf->path[prkdf->pathlen-1]);
5649     }
5650   else if (prkdf->key_reference_valid)
5651     {
5652       unsigned char mse[3];
5653
5654       mse[0] = 0x84; /* Select asym. key. */
5655       mse[1] = 1;
5656       mse[2] = prkdf->key_reference;
5657
5658       err = iso7816_manage_security_env (app_get_slot (app),
5659                                          0x41, 0xB6,
5660                                          mse, sizeof mse);
5661     }
5662   if (err)
5663     {
5664       log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5665       goto leave;
5666     }
5667
5668   if (prkdf->keyalgo == GCRY_PK_RSA && prkdf->keynbits >= 2048)
5669     {
5670       exmode = 1;
5671       le_value = prkdf->keynbits / 8;
5672     }
5673   else
5674     {
5675       exmode = 0;
5676       le_value = 0;
5677     }
5678
5679   err = iso7816_compute_ds (app_get_slot (app),
5680                             exmode, indata, indatalen,
5681                             le_value, outdata, outdatalen);
5682
5683  leave:
5684   xfree (indata_buffer);
5685   return err;
5686 }
5687
5688
5689 /* Handler for the PKAUTH command.
5690
5691    This is basically the same as the PKSIGN command but we first check
5692    that the requested key is suitable for authentication; that is, it
5693    must match the criteria used for the attribute $AUTHKEYID.  See
5694    do_sign for calling conventions; there is no HASHALGO, though. */
5695 static gpg_error_t
5696 do_auth (app_t app, ctrl_t ctrl, const char *keyidstr,
5697          gpg_error_t (*pincb)(void*, const char *, char **),
5698          void *pincb_arg,
5699          const void *indata, size_t indatalen,
5700          unsigned char **outdata, size_t *outdatalen )
5701 {
5702   gpg_error_t err;
5703   prkdf_object_t prkdf;
5704   int algo;
5705
5706   if (!keyidstr || !*keyidstr)
5707     return gpg_error (GPG_ERR_INV_VALUE);
5708
5709   err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5710   if (err)
5711     return err;
5712   if (!(prkdf->usageflags.sign || prkdf->gpgusage.auth))
5713     {
5714       log_error ("p15: key %s may not be used for authentication\n", keyidstr);
5715       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
5716     }
5717
5718   algo = indatalen == 36? MD_USER_TLS_MD5SHA1 : GCRY_MD_SHA1;
5719   return do_sign (app, ctrl, keyidstr, algo, pincb, pincb_arg,
5720                   indata, indatalen, outdata, outdatalen);
5721 }
5722
5723
5724 /* Handler for the PKDECRYPT command.  Decrypt the data in INDATA and
5725  * return the allocated result in OUTDATA.  If a PIN is required the
5726  * PINCB will be used to ask for the PIN; it should return the PIN in
5727  * an allocated buffer and put it into PIN.  */
5728 static gpg_error_t
5729 do_decipher (app_t app, ctrl_t ctrl, const char *keyidstr,
5730              gpg_error_t (*pincb)(void*, const char *, char **),
5731              void *pincb_arg,
5732              const void *indata, size_t indatalen,
5733              unsigned char **outdata, size_t *outdatalen,
5734              unsigned int *r_info)
5735 {
5736   gpg_error_t err;
5737   prkdf_object_t prkdf;    /* The private key object. */
5738   aodf_object_t aodf;      /* The associated authentication object. */
5739   int exmode, le_value, padind;
5740
5741   (void)ctrl;
5742   (void)r_info;
5743
5744   if (!keyidstr || !*keyidstr)
5745     return gpg_error (GPG_ERR_INV_VALUE);
5746   if (!indatalen || !indata || !outdatalen || !outdata)
5747     return gpg_error (GPG_ERR_INV_ARG);
5748
5749   err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5750   if (err)
5751     return err;
5752   if (!(prkdf->usageflags.decrypt
5753         || prkdf->usageflags.unwrap
5754         || prkdf->gpgusage.encr     ))
5755     {
5756       log_error ("p15: key %s may not be used for decryption\n", keyidstr);
5757       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
5758     }
5759
5760   /* Find the authentication object to this private key object. */
5761   if (!prkdf->authid)
5762     {
5763       log_error ("p15: no authentication object defined for %s\n", keyidstr);
5764       /* fixme: we might want to go ahead and do without PIN
5765          verification. */
5766       return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
5767     }
5768   for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5769     if (aodf->objidlen == prkdf->authidlen
5770         && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
5771       break;
5772   if (!aodf)
5773     log_info ("p15: no authentication for %s needed\n", keyidstr);
5774
5775   /* We need some more info about the key - get the keygrip to
5776    * populate these fields.  */
5777   err = keygrip_from_prkdf (app, prkdf);
5778   if (err)
5779     {
5780       log_error ("p15: keygrip_from_prkdf failed: %s\n", gpg_strerror (err));
5781       return err;
5782     }
5783
5784   /* Verify the PIN.  */
5785   err = prepare_verify_pin (app, keyidstr, prkdf, aodf);
5786   if (!err)
5787     err = verify_pin (app, pincb, pincb_arg, prkdf, aodf);
5788   if (err)
5789     return err;
5790
5791   if (prkdf->is_ecc && IS_CARDOS_5(app))
5792     {
5793
5794       err = iso7816_manage_security_env (app_get_slot (app), 0xF3, 0x01,
5795                                          NULL, 0);
5796       if (err)
5797         {
5798           log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5799           return err;
5800         }
5801     }
5802
5803
5804   /* The next is guess work for CardOS.  */
5805   if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
5806     {
5807       /* From analyzing an USB trace of a Windows signing application
5808        * we see that the SE is simply reset to 0x14.  It seems to be
5809        * sufficient to do this for decryption; signing still works
5810        * with the standard code despite that our trace showed that
5811        * there the SE is restored to 0x09.  Note that the special
5812        * D-Trust AID is in any case select by prepare_verify_pin.
5813        *
5814        * Hey, D-Trust please hand over the specs so that you can
5815        * actually sell your cards and we can properly implement it;
5816        * other vendors understand this and do not demand ridiculous
5817        * paper work or complicated procedures to get samples.  */
5818       err = iso7816_manage_security_env (app_get_slot (app),
5819                                          0xF3, 0x14, NULL, 0);
5820
5821     }
5822   else if (prkdf->key_reference_valid)
5823     {
5824       unsigned char mse[9];
5825       int i;
5826
5827       /* Note: This works with CardOS but the D-Trust card has the
5828        * problem that the next created signature would be broken.  */
5829
5830       i = 0;
5831       if (!prkdf->is_ecc)
5832         {
5833           mse[i++] = 0x80; /* Algorithm reference.  */
5834           mse[i++] = 1;
5835           mse[i++] = 0x0a; /* RSA, no padding.  */
5836         }
5837       mse[i++] = 0x84; /* Key reference.  */
5838       mse[i++] = 1;
5839       mse[i++] = prkdf->key_reference;
5840       if (prkdf->is_ecc && IS_CARDOS_5(app))
5841         {
5842           mse[i++] = 0x95; /* ???.  */
5843           mse[i++] = 1;
5844           mse[i++] = 0x40;
5845         }
5846       log_assert (i <= DIM(mse));
5847       err = iso7816_manage_security_env (app_get_slot (app), 0x41, 0xB8,
5848                                          mse, i);
5849     }
5850   /* Check for MSE error.  */
5851   if (err)
5852     {
5853       log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5854       return err;
5855     }
5856
5857   exmode = le_value = 0;
5858   padind = 0;
5859   if (prkdf->keyalgo == GCRY_PK_RSA && prkdf->keynbits >= 2048)
5860     {
5861       exmode = 1;   /* Extended length w/o a limit.  */
5862       le_value = prkdf->keynbits / 8;
5863     }
5864
5865   if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
5866     padind = 0x81;
5867
5868   if (prkdf->is_ecc && IS_CARDOS_5(app))
5869     {
5870       if ((indatalen & 1) && *(const char *)indata == 0x04)
5871         {
5872           /* Strip indicator byte.  */
5873           indatalen--;
5874           indata = (const char *)indata + 1;
5875         }
5876       err = iso7816_pso_csv (app_get_slot (app), exmode,
5877                              indata, indatalen,
5878                              le_value,
5879                              outdata, outdatalen);
5880     }
5881   else
5882     {
5883       err = iso7816_decipher (app_get_slot (app), exmode,
5884                               indata, indatalen,
5885                               le_value, padind,
5886                               outdata, outdatalen);
5887     }
5888
5889   return err;
5890 }
5891
5892
5893 /* Perform a simple verify operation for the PIN specified by
5894  * KEYIDSTR.  Note that we require a key reference which is then used
5895  * to select the authentication object.  Return GPG_ERR_NO_PIN if a
5896  * PIN is not required for using the private key KEYIDSTR.  */
5897 static gpg_error_t
5898 do_check_pin (app_t app, ctrl_t ctrl, const char *keyidstr,
5899               gpg_error_t (*pincb)(void*, const char *, char **),
5900               void *pincb_arg)
5901 {
5902   gpg_error_t err;
5903   prkdf_object_t prkdf;    /* The private key object. */
5904   aodf_object_t aodf;      /* The associated authentication object. */
5905
5906   (void)ctrl;
5907
5908   if (!keyidstr || !*keyidstr)
5909     return gpg_error (GPG_ERR_INV_VALUE);
5910
5911   err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5912   if (err
5913       && gpg_err_code (err) != GPG_ERR_INV_ID
5914       && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
5915     return err;
5916
5917   if (err) /* Not found or invalid - assume it is the label.  */
5918     {
5919       prkdf = NULL;
5920       for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5921         if (aodf->label && !ascii_strcasecmp (aodf->label, keyidstr))
5922           break;
5923       if (!aodf)
5924         return err;  /* Re-use the original error code.  */
5925     }
5926   else /* Find the authentication object to this private key object. */
5927     {
5928       if (!prkdf->authid)
5929         {
5930           log_error ("p15: no authentication object defined for %s\n",
5931                      keyidstr);
5932           return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
5933         }
5934       for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5935         if (aodf->objidlen == prkdf->authidlen
5936             && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
5937           break;
5938       if (!aodf) /* None found.  */
5939         return gpg_error (GPG_ERR_NO_PIN);
5940     }
5941
5942   err = prepare_verify_pin (app, keyidstr, prkdf, aodf);
5943   if (!err)
5944     err = verify_pin (app, pincb, pincb_arg, prkdf, aodf);
5945
5946   return err;
5947 }
5948
5949
5950 /* Process the various keygrip based info requests.  */
5951 static gpg_error_t
5952 do_with_keygrip (app_t app, ctrl_t ctrl, int action,
5953                  const char *want_keygripstr, int capability)
5954 {
5955   gpg_error_t err;
5956   char *serialno = NULL;
5957   int as_data = 0;
5958   prkdf_object_t prkdf;
5959
5960   /* First a quick check for valid parameters.  */
5961   switch (action)
5962     {
5963     case KEYGRIP_ACTION_LOOKUP:
5964       if (!want_keygripstr)
5965         {
5966           err = gpg_error (GPG_ERR_NOT_FOUND);
5967           goto leave;
5968         }
5969       break;
5970     case KEYGRIP_ACTION_SEND_DATA:
5971       as_data = 1;
5972       break;
5973     case KEYGRIP_ACTION_WRITE_STATUS:
5974       break;
5975     default:
5976       err = gpg_error (GPG_ERR_INV_ARG);
5977       goto leave;
5978     }
5979
5980   /* Allocate the s/n string if needed.  */
5981   if (action != KEYGRIP_ACTION_LOOKUP)
5982     {
5983       serialno = app_get_serialno (app);
5984       if (!serialno)
5985         {
5986           err = gpg_error_from_syserror ();
5987           goto leave;
5988         }
5989     }
5990
5991   for (prkdf = app->app_local->private_key_info;
5992        prkdf; prkdf = prkdf->next)
5993     {
5994       if (keygrip_from_prkdf (app, prkdf))
5995         continue;
5996
5997       if (action == KEYGRIP_ACTION_LOOKUP)
5998         {
5999           if (!strcmp (prkdf->keygrip, want_keygripstr))
6000             {
6001               err = 0; /* Found */
6002               goto leave;
6003             }
6004         }
6005       else if (!want_keygripstr || !strcmp (prkdf->keygrip, want_keygripstr))
6006         {
6007           char *keyref;
6008
6009           if (capability == GCRY_PK_USAGE_SIGN)
6010             {
6011               if (!(prkdf->usageflags.sign || prkdf->usageflags.sign_recover
6012                     || prkdf->usageflags.non_repudiation))
6013                 continue;
6014             }
6015           else if (capability == GCRY_PK_USAGE_ENCR)
6016             {
6017               if (!(prkdf->usageflags.decrypt || prkdf->usageflags.unwrap))
6018                 continue;
6019             }
6020           else if (capability == GCRY_PK_USAGE_AUTH)
6021             {
6022               if (!(prkdf->usageflags.sign || prkdf->usageflags.sign_recover))
6023                 continue;
6024             }
6025
6026           keyref = keyref_from_prkdf (app, prkdf);
6027           if (!keyref)
6028             {
6029               err = gpg_error_from_syserror ();
6030               goto leave;
6031             }
6032
6033           send_keyinfo (ctrl, as_data, prkdf->keygrip, serialno, keyref);
6034           xfree (keyref);
6035           if (want_keygripstr)
6036             {
6037               err = 0; /* Found */
6038               goto leave;
6039             }
6040         }
6041     }
6042
6043   /* Return an error so that the dispatcher keeps on looping over the
6044    * other applications.  For clarity we use a different error code
6045    * when listing all keys.  Note that in lookup mode WANT_KEYGRIPSTR
6046    * is not NULL.  */
6047   if (!want_keygripstr)
6048     err = gpg_error (GPG_ERR_TRUE);
6049   else
6050     err = gpg_error (GPG_ERR_NOT_FOUND);
6051
6052  leave:
6053   xfree (serialno);
6054   return err;
6055 }
6056
6057
6058 \f
6059 /* Assume that EF(DIR) has been selected.  Read its content and figure
6060    out the home EF of pkcs#15.  Return that home DF or 0 if not found
6061    and the value at the address of BELPIC indicates whether it was
6062    found by the belpic aid. */
6063 static unsigned short
6064 read_home_df (int slot, int *r_belpic)
6065 {
6066   gpg_error_t err;
6067   unsigned char *buffer;
6068   const unsigned char *p, *pp;
6069   size_t buflen, n, nn;
6070   unsigned short result = 0;
6071
6072   *r_belpic = 0;
6073
6074   err = iso7816_read_binary (slot, 0, 0, &buffer, &buflen);
6075   if (err)
6076     {
6077       log_error ("p15: error reading EF(DIR): %s\n", gpg_strerror (err));
6078       return 0;
6079     }
6080
6081   /* FIXME: We need to scan all records. */
6082   p = find_tlv (buffer, buflen, 0x61, &n);
6083   if (p && n)
6084     {
6085       pp = find_tlv (p, n, 0x4f, &nn);
6086       if (pp && ((nn == sizeof pkcs15_aid && !memcmp (pp, pkcs15_aid, nn))
6087                  || (*r_belpic = (nn == sizeof pkcs15be_aid
6088                                   && !memcmp (pp, pkcs15be_aid, nn)))))
6089         {
6090           pp = find_tlv (p, n, 0x50, &nn);
6091           if (pp && opt.verbose)
6092             log_info ("p15: application label from EF(DIR) is '%.*s'\n",
6093                       (int)nn, pp);
6094           pp = find_tlv (p, n, 0x51, &nn);
6095           if (pp && nn == 4 && *pp == 0x3f && !pp[1])
6096             {
6097               result = ((pp[2] << 8) | pp[3]);
6098               if (opt.verbose)
6099                 log_info ("p15: application directory is 0x%04hX\n", result);
6100             }
6101         }
6102     }
6103   xfree (buffer);
6104   return result;
6105 }
6106
6107
6108 /*
6109    Select the PKCS#15 application on the card in SLOT.
6110  */
6111 gpg_error_t
6112 app_select_p15 (app_t app)
6113 {
6114   int slot = app_get_slot (app);
6115   int rc;
6116   unsigned short def_home_df = 0;
6117   card_type_t card_type = CARD_TYPE_UNKNOWN;
6118   int direct = 0;
6119   int is_belpic = 0;
6120   unsigned char *fci = NULL;
6121   size_t fcilen;
6122
6123   rc = iso7816_select_application_ext (slot, pkcs15_aid, sizeof pkcs15_aid, 1,
6124                                        &fci, &fcilen);
6125   if (rc)
6126     { /* Not found: Try to locate it from 2F00.  We use direct path
6127          selection here because it seems that the Belgian eID card
6128          does only allow for that.  Many other cards supports this
6129          selection method too.  Note, that we don't use
6130          select_application above for the Belgian card - the call
6131          works but it seems that it does not switch to the correct DF.
6132          Using the 2f02 just works. */
6133       unsigned short path[1] = { 0x2f00 };
6134
6135       rc = iso7816_select_path (slot, path, 1, 0);
6136       if (!rc)
6137         {
6138           direct = 1;
6139           def_home_df = read_home_df (slot, &is_belpic);
6140           if (def_home_df)
6141             {
6142               path[0] = def_home_df;
6143               rc = iso7816_select_path (slot, path, 1, 0);
6144             }
6145         }
6146     }
6147   if (rc)
6148     { /* Still not found:  Try the default DF. */
6149       def_home_df = DEFAULT_HOME_DF;
6150       rc = iso7816_select_file (slot, def_home_df, 1);
6151     }
6152   if (!rc)
6153     {
6154       /* Determine the type of the card.  The general case is to look
6155          it up from the ATR table.  For the Belgian eID card we know
6156          it instantly from the AID. */
6157       if (is_belpic)
6158         {
6159           card_type = CARD_TYPE_BELPIC;
6160         }
6161       else
6162         {
6163           unsigned char *atr;
6164           size_t atrlen;
6165           int i;
6166
6167           atr = apdu_get_atr (app_get_slot (app), &atrlen);
6168           if (!atr)
6169             rc = gpg_error (GPG_ERR_INV_CARD);
6170           else
6171             {
6172               for (i=0; card_atr_list[i].atrlen; i++)
6173                 if (card_atr_list[i].atrlen == atrlen
6174                     && !memcmp (card_atr_list[i].atr, atr, atrlen))
6175                   {
6176                     card_type = card_atr_list[i].type;
6177                     break;
6178                   }
6179               xfree (atr);
6180             }
6181         }
6182     }
6183   if (!rc)
6184     {
6185       app->apptype = APPTYPE_P15;
6186
6187       app->app_local = xtrycalloc (1, sizeof *app->app_local);
6188       if (!app->app_local)
6189         {
6190           rc = gpg_error_from_syserror ();
6191           goto leave;
6192         }
6193
6194       /* Set the home DF from the FCI returned by the select.  */
6195       if (!def_home_df && fci)
6196         {
6197           const unsigned char *s;
6198           size_t n;
6199
6200           s = find_tlv (fci, fcilen, 0x83, &n);
6201           if (s && n == 2)
6202             def_home_df = buf16_to_ushort (s);
6203           else
6204             {
6205               if (fcilen)
6206                 log_printhex (fci, fcilen, "fci:");
6207               log_info ("p15: select did not return the DF - using default\n");
6208               def_home_df = DEFAULT_HOME_DF;
6209             }
6210         }
6211       app->app_local->home_df = def_home_df;
6212
6213       /* Store the card type.  FIXME: We might want to put this into
6214          the common APP structure. */
6215       app->app_local->card_type = card_type;
6216
6217       app->app_local->card_product = CARD_PRODUCT_UNKNOWN;
6218
6219       /* Store whether we may and should use direct path selection. */
6220       switch (card_type)
6221         {
6222         case CARD_TYPE_CARDOS_50:
6223         case CARD_TYPE_CARDOS_53:
6224           direct = 1;
6225           break;
6226         case CARD_TYPE_AET:
6227           app->app_local->no_extended_mode = 1;
6228           break;
6229         default:
6230           /* Use whatever has been determined above.  */
6231           break;
6232         }
6233       app->app_local->direct_path_selection = direct;
6234
6235       /* Read basic information and thus check whether this is a real
6236          card.  */
6237       rc = read_p15_info (app);
6238       if (rc)
6239         goto leave;
6240
6241       /* Special serial number munging.  We need to check for a German
6242          prototype card right here because we need to access to
6243          EF(TokenInfo).  We mark such a serial number by the using a
6244          prefix of FF0100. */
6245       if (APP_CARD(app)->serialnolen == 12
6246           && !memcmp (APP_CARD(app)->serialno,
6247                       "\xD2\x76\0\0\0\0\0\0\0\0\0\0", 12))
6248         {
6249           /* This is a German card with a silly serial number.  Try to get
6250              the serial number from the EF(TokenInfo). . */
6251           unsigned char *p;
6252
6253           /* FIXME: actually get it from EF(TokenInfo). */
6254
6255           p = xtrymalloc (3 + APP_CARD(app)->serialnolen);
6256           if (!p)
6257             rc = gpg_error (gpg_err_code_from_errno (errno));
6258           else
6259             {
6260               memcpy (p, "\xff\x01", 3);
6261               memcpy (p+3, APP_CARD(app)->serialno, APP_CARD(app)->serialnolen);
6262               APP_CARD(app)->serialnolen += 3;
6263               xfree (APP_CARD(app)->serialno);
6264               APP_CARD(app)->serialno = p;
6265             }
6266         }
6267
6268       app->fnc.deinit = do_deinit;
6269       app->fnc.prep_reselect = NULL;
6270       app->fnc.reselect = NULL;
6271       app->fnc.learn_status = do_learn_status;
6272       app->fnc.readcert = do_readcert;
6273       app->fnc.getattr = do_getattr;
6274       app->fnc.setattr = NULL;
6275       app->fnc.genkey = NULL;
6276       app->fnc.sign = do_sign;
6277       app->fnc.auth = do_auth;
6278       app->fnc.decipher = do_decipher;
6279       app->fnc.change_pin = NULL;
6280       app->fnc.check_pin = do_check_pin;
6281       app->fnc.with_keygrip = do_with_keygrip;
6282
6283     leave:
6284       if (rc)
6285         do_deinit (app);
6286    }
6287
6288   xfree (fci);
6289   return rc;
6290 }