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