Imported Upstream version 2.2.28
[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 "R&S";
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       && !strncmp (app->app_local->token_label, "D-TRUST Card V3", 15)
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       xfree (labelbuf);
3855     }
3856   return 0;
3857 }
3858
3859
3860 /* Get the keygrip of the private key object PRKDF.  On success the
3861  * keygrip, the algo and the length are stored in the KEYGRIP,
3862  * KEYALGO, and KEYNBITS fields of the PRKDF object.  */
3863 static gpg_error_t
3864 keygrip_from_prkdf (app_t app, prkdf_object_t prkdf)
3865 {
3866   gpg_error_t err;
3867   cdf_object_t cdf;
3868   unsigned char *der;
3869   size_t derlen;
3870   ksba_cert_t cert;
3871   gcry_sexp_t s_pkey = NULL;
3872
3873   /* Easy if we got a cached version.  */
3874   if (prkdf->keygrip_valid)
3875     return 0;
3876
3877   xfree (prkdf->common_name);
3878   prkdf->common_name = NULL;
3879   xfree (prkdf->serial_number);
3880   prkdf->serial_number = NULL;
3881
3882   /* We could have also checked whether a public key directory file
3883    * and a matching public key for PRKDF is available.  This would
3884    * make extraction of the key faster.  However, this way we don't
3885    * have a way to look at extended key attributes to check gpgusage.
3886    * FIXME: Add public key lookup if no certificate was found. */
3887
3888   /* Look for a matching certificate. A certificate matches if the id
3889    * matches the one of the private key info.  If none was found we
3890    * also try to match on the label.  */
3891   err = cdf_object_from_objid (app, prkdf->objidlen, prkdf->objid, &cdf);
3892   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
3893     err = cdf_object_from_label (app, prkdf->label, &cdf);
3894   if (!err && !cdf)
3895     err = gpg_error (GPG_ERR_NOT_FOUND);
3896   if (err)
3897     goto leave;
3898
3899   err = readcert_by_cdf (app, cdf, &der, &derlen);
3900   if (err)
3901     goto leave;
3902
3903   err = ksba_cert_new (&cert);
3904   if (!err)
3905     err = ksba_cert_init_from_mem (cert, der, derlen);
3906   xfree (der);
3907   if (!err)
3908     err = app_help_get_keygrip_string (cert, prkdf->keygrip, &s_pkey, NULL);
3909   if (!err && !prkdf->gpgusage.any)
3910     {
3911       /* Try to get the CN and the SerialNumber from the certificate;
3912        * we use a very simple approach here which should work in many
3913        * cases.  Eventually we should add a rfc-2253 parser into
3914        * libksba to make it easier to parse such a string.
3915        * We don't do this if this is marked as gpg key and thus
3916        * has only a dummy certificate.
3917        *
3918        * First example string:
3919        *   "CN=Otto Schily,O=Miniluv,C=DE"
3920        * Second example string:
3921        *   "2.5.4.5=#445452323030303236333531,2.5.4.4=#4B6F6368,"
3922        *   "2.5.4.42=#5765726E6572,CN=Werner Koch,OU=For testing"
3923        *   " purposes only!,O=Testorganisation,C=DE"
3924        */
3925       char *dn = ksba_cert_get_subject (cert, 0);
3926       if (dn)
3927         {
3928           char *p, *pend, *buf;
3929
3930           p = strstr (dn, "CN=");
3931           if (p && (p==dn || p[-1] == ','))
3932             {
3933               p += 3;
3934               if (!(pend = strchr (p, ',')))
3935                 pend = p + strlen (p);
3936               if (pend && pend > p
3937                   && (prkdf->common_name = xtrymalloc ((pend - p) + 1)))
3938                 {
3939                   memcpy (prkdf->common_name, p, pend-p);
3940                   prkdf->common_name[pend-p] = 0;
3941                 }
3942             }
3943           p = strstr (dn, "2.5.4.5=#"); /* OID of the SerialNumber */
3944           if (p && (p==dn || p[-1] == ','))
3945             {
3946               p += 9;
3947               if (!(pend = strchr (p, ',')))
3948                 pend = p + strlen (p);
3949               if (pend && pend > p
3950                   && (buf = xtrymalloc ((pend - p) + 1)))
3951                 {
3952                   memcpy (buf, p, pend-p);
3953                   buf[pend-p] = 0;
3954                   if (!hex2str (buf, buf, strlen (buf)+1, NULL))
3955                     xfree (buf);  /* Invalid hex encoding.  */
3956                   else
3957                     prkdf->serial_number = buf;
3958                 }
3959             }
3960           ksba_free (dn);
3961         }
3962     }
3963
3964   if (!err && !prkdf->keytime)
3965     {
3966       ksba_isotime_t isot;
3967       time_t t;
3968
3969       ksba_cert_get_validity (cert, 0, isot);
3970       t = isotime2epoch (isot);
3971       prkdf->keytime = (t == (time_t)(-1))? 0 : (u32)t;
3972       prkdf->have_keytime = 1;
3973     }
3974
3975   if (!err && !prkdf->keyalgostr)
3976     prkdf->keyalgostr = pubkey_algo_string (s_pkey, NULL);
3977
3978   ksba_cert_release (cert);
3979   if (err)
3980     goto leave;
3981
3982   prkdf->keyalgo = get_pk_algo_from_key (s_pkey);
3983   if (!prkdf->keyalgo)
3984     {
3985       err = gpg_error (GPG_ERR_PUBKEY_ALGO);
3986       goto leave;
3987     }
3988
3989   prkdf->keynbits = gcry_pk_get_nbits (s_pkey);
3990   if (!prkdf->keynbits)
3991     {
3992       err = gpg_error (GPG_ERR_PUBKEY_ALGO);
3993       goto leave;
3994     }
3995
3996   prkdf->keygrip_valid = 1;  /* Yeah, got everything.  */
3997
3998  leave:
3999   gcry_sexp_release (s_pkey);
4000   return err;
4001 }
4002
4003
4004 /* Return a malloced keyref string for PRKDF.  Returns NULL on
4005  * malloc failure.  */
4006 static char *
4007 keyref_from_prkdf (app_t app, prkdf_object_t prkdf)
4008 {
4009   char *buf, *p;
4010
4011   buf = xtrymalloc (4 + 5 + prkdf->objidlen*2 + 1);
4012   if (!buf)
4013     return NULL;
4014   p = stpcpy (buf, "P15");
4015   if (app->app_local->home_df != DEFAULT_HOME_DF)
4016     {
4017       snprintf (p, 6, "-%04X",
4018                 (unsigned int)(app->app_local->home_df & 0xffff));
4019       p += 5;
4020     }
4021   p = stpcpy (p, ".");
4022   bin2hex (prkdf->objid, prkdf->objidlen, p);
4023   return buf;
4024 }
4025
4026
4027 /* Helper to do_learn_status: Send information about all known
4028    keypairs back.  FIXME: much code duplication from
4029    send_certinfo(). */
4030 static gpg_error_t
4031 send_keypairinfo (app_t app, ctrl_t ctrl, prkdf_object_t prkdf)
4032 {
4033   gpg_error_t err;
4034
4035   for (; prkdf; prkdf = prkdf->next)
4036     {
4037       char *buf;
4038       int j;
4039
4040       buf = keyref_from_prkdf (app, prkdf);
4041       if (!buf)
4042         return gpg_error_from_syserror ();
4043
4044       err = keygrip_from_prkdf (app, prkdf);
4045       if (err)
4046         {
4047           log_error ("p15: error getting keygrip from ");
4048           for (j=0; j < prkdf->pathlen; j++)
4049             log_printf ("%s%04hX", j?"/":"", prkdf->path[j]);
4050           log_printf (": %s\n", gpg_strerror (err));
4051         }
4052       else
4053         {
4054           char usage[5];
4055           char keytime[20];
4056           const char *algostr;
4057           size_t usagelen = 0;
4058
4059           if (prkdf->gpgusage.any)
4060             {
4061               if (prkdf->gpgusage.sign)
4062                 usage[usagelen++] = 's';
4063               if (prkdf->gpgusage.cert)
4064                 usage[usagelen++] = 'c';
4065               if (prkdf->gpgusage.encr)
4066                 usage[usagelen++] = 'e';
4067               if (prkdf->gpgusage.auth)
4068                 usage[usagelen++] = 'a';
4069             }
4070           else
4071             {
4072               if ((prkdf->usageflags.sign
4073                    || prkdf->usageflags.sign_recover
4074                    || prkdf->usageflags.non_repudiation)
4075                   && (!prkdf->extusage.valid
4076                       || prkdf->extusage.sign))
4077                 usage[usagelen++] = 's';
4078               if ((prkdf->usageflags.sign
4079                    || prkdf->usageflags.sign_recover)
4080                   && (!prkdf->extusage.valid || prkdf->extusage.sign))
4081                 usage[usagelen++] = 'c';
4082               if ((prkdf->usageflags.decrypt
4083                    || prkdf->usageflags.unwrap)
4084                   && (!prkdf->extusage.valid || prkdf->extusage.encr))
4085                 usage[usagelen++] = 'e';
4086               if ((prkdf->usageflags.sign
4087                    || prkdf->usageflags.sign_recover)
4088                   && (!prkdf->extusage.valid || prkdf->extusage.auth))
4089                 usage[usagelen++] = 'a';
4090             }
4091
4092           log_assert (strlen (prkdf->keygrip) == 40);
4093           if (prkdf->keytime && prkdf->have_keytime)
4094             snprintf (keytime, sizeof keytime, "%lu",
4095                       (unsigned long)prkdf->keytime);
4096           else
4097             strcpy (keytime, "-");
4098
4099           algostr = prkdf->keyalgostr;
4100
4101           send_status_info (ctrl, "KEYPAIRINFO",
4102                             prkdf->keygrip, 2*KEYGRIP_LEN,
4103                             buf, strlen (buf),
4104                             usage, usagelen,
4105                             keytime, strlen (keytime),
4106                             algostr, strlen (algostr?algostr:""),
4107                             NULL, (size_t)0);
4108         }
4109       xfree (buf);
4110     }
4111   return 0;
4112 }
4113
4114
4115
4116 /* This is the handler for the LEARN command.  Note that if
4117  * APP_LEARN_FLAG_REREAD is set and this function returns an error,
4118  * the caller must deinitialize this application.  */
4119 static gpg_error_t
4120 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
4121 {
4122   gpg_error_t err;
4123
4124   if (flags & APP_LEARN_FLAG_REREAD)
4125     {
4126       err = read_p15_info (app);
4127       if (err)
4128         return err;
4129     }
4130
4131   if ((flags & APP_LEARN_FLAG_KEYPAIRINFO))
4132     err = 0;
4133   else
4134     {
4135       err = do_getattr (app, ctrl, "MANUFACTURER");
4136       if (!err)
4137         err = send_certinfo (app, ctrl, "100",
4138                              app->app_local->certificate_info);
4139       if (!err)
4140         err = send_certinfo (app, ctrl, "101",
4141                              app->app_local->trusted_certificate_info);
4142       if (!err)
4143         err = send_certinfo (app, ctrl, "102",
4144                              app->app_local->useful_certificate_info);
4145     }
4146
4147   if (!err)
4148     err = send_keypairinfo (app, ctrl, app->app_local->private_key_info);
4149
4150   if (!err)
4151     err = do_getattr (app, ctrl, "CHV-STATUS");
4152   if (!err)
4153     err = do_getattr (app, ctrl, "CHV-LABEL");
4154
4155
4156   return err;
4157 }
4158
4159
4160 /* Read a certificate using the information in CDF and return the
4161  * certificate in a newly malloced buffer R_CERT and its length
4162  * R_CERTLEN.  Also parses the certificate.  R_CERT and R_CERTLEN may
4163  * be NULL to do just the caching.  */
4164 static gpg_error_t
4165 readcert_by_cdf (app_t app, cdf_object_t cdf,
4166                  unsigned char **r_cert, size_t *r_certlen)
4167 {
4168   gpg_error_t err;
4169   unsigned char *buffer = NULL;
4170   const unsigned char *p, *save_p;
4171   size_t buflen, n;
4172   int class, tag, constructed, ndef;
4173   size_t totobjlen, objlen, hdrlen;
4174   int rootca;
4175   int i;
4176
4177   if (r_cert)
4178     *r_cert = NULL;
4179   if (r_certlen)
4180     *r_certlen = 0;
4181
4182   /* First check whether it has been cached. */
4183   if (cdf->cert)
4184     {
4185       const unsigned char *image;
4186       size_t imagelen;
4187
4188       if (!r_cert || !r_certlen)
4189         return 0; /* Caller does not actually want the result. */
4190
4191       image = ksba_cert_get_image (cdf->cert, &imagelen);
4192       if (!image)
4193         {
4194           log_error ("p15: ksba_cert_get_image failed\n");
4195           return gpg_error (GPG_ERR_INTERNAL);
4196         }
4197       *r_cert = xtrymalloc (imagelen);
4198       if (!*r_cert)
4199         return gpg_error_from_syserror ();
4200       memcpy (*r_cert, image, imagelen);
4201       *r_certlen = imagelen;
4202       return 0;
4203     }
4204
4205   /* Read the entire file.  fixme: This could be optimized by first
4206      reading the header to figure out how long the certificate
4207      actually is. */
4208   err = select_ef_by_path (app, cdf->path, cdf->pathlen);
4209   if (err)
4210     goto leave;
4211
4212   err = iso7816_read_binary_ext (app_get_slot (app), 1, cdf->off, cdf->len,
4213                                  &buffer, &buflen, NULL);
4214   if (!err && (!buflen || *buffer == 0xff))
4215     err = gpg_error (GPG_ERR_NOT_FOUND);
4216   if (err)
4217     {
4218       log_error ("p15: error reading certificate id=");
4219       for (i=0; i < cdf->objidlen; i++)
4220         log_printf ("%02X", cdf->objid[i]);
4221       log_printf (" at ");
4222       for (i=0; i < cdf->pathlen; i++)
4223         log_printf ("%s%04hX", i? "/":"", cdf->path[i]);
4224       log_printf (": %s\n", gpg_strerror (err));
4225       goto leave;
4226     }
4227
4228   /* Check whether this is really a certificate.  */
4229   p = buffer;
4230   n = buflen;
4231   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
4232                           &ndef, &objlen, &hdrlen);
4233   if (err)
4234     goto leave;
4235
4236   if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed)
4237     rootca = 0;
4238   else if ( class == CLASS_UNIVERSAL && tag == TAG_SET && constructed )
4239     rootca = 1;
4240   else
4241     {
4242       err = gpg_error (GPG_ERR_INV_OBJ);
4243       goto leave;
4244     }
4245   totobjlen = objlen + hdrlen;
4246   log_assert (totobjlen <= buflen);
4247
4248   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
4249                           &ndef, &objlen, &hdrlen);
4250   if (err)
4251     goto leave;
4252
4253   if (!rootca
4254       && class == CLASS_UNIVERSAL && tag == TAG_OBJECT_ID && !constructed)
4255     {
4256       /* The certificate seems to be contained in a userCertificate
4257          container.  Skip this and assume the following sequence is
4258          the certificate. */
4259       if (n < objlen)
4260         {
4261           err = gpg_error (GPG_ERR_INV_OBJ);
4262           goto leave;
4263         }
4264       p += objlen;
4265       n -= objlen;
4266       save_p = p;
4267       err = parse_ber_header (&p, &n, &class, &tag, &constructed,
4268                               &ndef, &objlen, &hdrlen);
4269       if (err)
4270         goto leave;
4271       if ( !(class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed) )
4272         {
4273           err = gpg_error (GPG_ERR_INV_OBJ);
4274           goto leave;
4275         }
4276       totobjlen = objlen + hdrlen;
4277       log_assert (save_p + totobjlen <= buffer + buflen);
4278       memmove (buffer, save_p, totobjlen);
4279     }
4280
4281
4282   /* Try to parse and cache the certificate. */
4283   err = ksba_cert_new (&cdf->cert);
4284   if (!err)
4285     {
4286       err = ksba_cert_init_from_mem (cdf->cert, buffer, totobjlen);
4287       if (!err) /* Call us to use the just cached cert object.  */
4288         err = readcert_by_cdf (app, cdf, r_cert, r_certlen);
4289       if (err)
4290         {
4291           ksba_cert_release (cdf->cert);
4292           cdf->cert = NULL;
4293         }
4294
4295     }
4296   if (err)
4297     {
4298       log_error ("p15: caching certificate failed: %s\n",
4299                  gpg_strerror (err));
4300       /* We return the certificate anyway so that the caller has a
4301        * chance to get an even unsupported or broken certificate.  */
4302       if (r_cert && r_certlen)
4303         {
4304           *r_cert = buffer;
4305           buffer = NULL;
4306           *r_certlen = totobjlen;
4307         }
4308     }
4309
4310  leave:
4311   xfree (buffer);
4312   return err;
4313 }
4314
4315
4316 /* Handler for the READCERT command.
4317
4318    Read the certificate with id CERTID (as returned by learn_status in
4319    the CERTINFO status lines) and return it in the freshly allocated
4320    buffer to be stored at R_CERT and its length at R_CERTLEN.  A error
4321    code will be returned on failure and R_CERT and R_CERTLEN will be
4322    set to (NULL,0). */
4323 static gpg_error_t
4324 do_readcert (app_t app, const char *certid,
4325              unsigned char **r_cert, size_t *r_certlen)
4326 {
4327   gpg_error_t err;
4328   cdf_object_t cdf;
4329
4330   *r_cert = NULL;
4331   *r_certlen = 0;
4332   err = cdf_object_from_certid (app, certid, &cdf);
4333   if (!err)
4334     err = readcert_by_cdf (app, cdf, r_cert, r_certlen);
4335   return err;
4336 }
4337
4338
4339 /* Sort helper for an array of authentication objects.  */
4340 static int
4341 compare_aodf_objid (const void *arg_a, const void *arg_b)
4342 {
4343   const aodf_object_t a = *(const aodf_object_t *)arg_a;
4344   const aodf_object_t b = *(const aodf_object_t *)arg_b;
4345   int rc;
4346
4347   rc = memcmp (a->objid, b->objid,
4348                a->objidlen < b->objidlen? a->objidlen : b->objidlen);
4349   if (!rc)
4350     {
4351       if (a->objidlen < b->objidlen)
4352         rc = -1;
4353       else if (a->objidlen > b->objidlen)
4354         rc = 1;
4355     }
4356   return rc;
4357 }
4358
4359
4360 static void
4361 send_key_fpr_line (ctrl_t ctrl, int number, const unsigned char *fpr)
4362 {
4363   char buf[41];
4364   char numbuf[25];
4365
4366   bin2hex (fpr, 20, buf);
4367   if (number == -1)
4368     *numbuf = 0; /* Don't print the key number */
4369   else
4370     snprintf (numbuf, sizeof numbuf, "%d", number);
4371   send_status_info (ctrl, "KEY-FPR",
4372                     numbuf, (size_t)strlen(numbuf),
4373                     buf, (size_t)strlen (buf),
4374                     NULL, 0);
4375 }
4376
4377
4378 /* If possible Emit a FPR-KEY status line for the private key object
4379  * PRKDF using NUMBER as index.  */
4380 static void
4381 send_key_fpr (app_t app, ctrl_t ctrl, prkdf_object_t prkdf, int number)
4382 {
4383   gpg_error_t err;
4384   cdf_object_t cdf;
4385   unsigned char *pk, *fixed_pk;
4386   size_t pklen, fixed_pklen;
4387   const unsigned char *m, *e, *q;
4388   size_t mlen, elen, qlen;
4389   unsigned char fpr20[20];
4390
4391   if (cdf_object_from_objid (app, prkdf->objidlen, prkdf->objid, &cdf)
4392       && cdf_object_from_label (app, prkdf->label, &cdf))
4393     return;
4394   if (!cdf->cert)
4395     readcert_by_cdf (app, cdf, NULL, NULL);
4396   if (!cdf->cert)
4397     return;
4398   if (!prkdf->have_keytime)
4399     return;
4400   pk = ksba_cert_get_public_key (cdf->cert);
4401   if (!pk)
4402     return;
4403   pklen = gcry_sexp_canon_len (pk, 0, NULL, &err);
4404
4405   if (uncompress_ecc_q_in_canon_sexp (pk, pklen, &fixed_pk, &fixed_pklen))
4406     {
4407       xfree (pk);
4408       return;
4409     }
4410   if (fixed_pk)
4411     {
4412       xfree (pk); pk = NULL;
4413       pk = fixed_pk;
4414       pklen = fixed_pklen;
4415     }
4416
4417   switch (prkdf->keyalgo)
4418     {
4419     case GCRY_PK_RSA:
4420       if (!get_rsa_pk_from_canon_sexp (pk, pklen,
4421                                        &m, &mlen, &e, &elen)
4422           && !compute_openpgp_fpr_rsa (4,
4423                                        prkdf->keytime,
4424                                        m, mlen, e, elen,
4425                                        fpr20, NULL))
4426         send_key_fpr_line (ctrl, number, fpr20);
4427       break;
4428
4429     case GCRY_PK_ECC:
4430     case GCRY_PK_ECDSA:
4431     case GCRY_PK_ECDH:
4432     case GCRY_PK_EDDSA:
4433       /* Note that NUMBER 2 indicates the encryption key.  */
4434       if (!get_ecc_q_from_canon_sexp (pk, pklen, &q, &qlen)
4435           && !compute_openpgp_fpr_ecc (4,
4436                                        prkdf->keytime,
4437                                        prkdf->keyalgostr,
4438                                        number == 2,
4439                                        q, qlen,
4440                                        prkdf->ecdh_kdf, 4,
4441                                        fpr20, NULL))
4442         send_key_fpr_line (ctrl, number, fpr20);
4443       break;
4444
4445     default: /* No Fingerprint for an unknown algo.  */
4446       break;
4447
4448     }
4449   xfree (pk);
4450 }
4451
4452
4453 /* Implement the GETATTR command.  This is similar to the LEARN
4454    command but returns just one value via the status interface. */
4455 static gpg_error_t
4456 do_getattr (app_t app, ctrl_t ctrl, const char *name)
4457 {
4458   gpg_error_t err;
4459   prkdf_object_t prkdf;
4460
4461   if (!strcmp (name, "$AUTHKEYID")
4462       || !strcmp (name, "$ENCRKEYID")
4463       || !strcmp (name, "$SIGNKEYID"))
4464     {
4465       char *buf;
4466
4467       /* We return the ID of the first private key capable of the
4468        * requested action.  If any gpgusage flag has been set for the
4469        * card we consult the gpgusage flags and not the regualr usage
4470        * flags.
4471        */
4472       /* FIXME: This changed: Note that we do not yet return
4473        * non_repudiation keys for $SIGNKEYID because our D-Trust
4474        * testcard uses rsaPSS, which is not supported by gpgsm and not
4475        * covered by the VS-NfD approval.  */
4476       for (prkdf = app->app_local->private_key_info; prkdf;
4477            prkdf = prkdf->next)
4478         {
4479           if (app->app_local->any_gpgusage)
4480             {
4481               if ((name[1] == 'A' && prkdf->gpgusage.auth)
4482                   || (name[1] == 'E' && prkdf->gpgusage.encr)
4483                   || (name[1] == 'S' && prkdf->gpgusage.sign))
4484                 break;
4485             }
4486           else
4487             {
4488               if ((name[1] == 'A' && (prkdf->usageflags.sign
4489                                       || prkdf->usageflags.sign_recover))
4490                   || (name[1] == 'E' && (prkdf->usageflags.decrypt
4491                                          || prkdf->usageflags.unwrap))
4492                   || (name[1] == 'S' && (prkdf->usageflags.sign
4493                                          || prkdf->usageflags.sign_recover)))
4494                 break;
4495             }
4496         }
4497       if (prkdf)
4498         {
4499           buf = keyref_from_prkdf (app, prkdf);
4500           if (!buf)
4501             return gpg_error_from_syserror ();
4502
4503           send_status_info (ctrl, name, buf, strlen (buf), NULL, 0);
4504           xfree (buf);
4505         }
4506       return 0;
4507     }
4508   else if (!strcmp (name, "$DISPSERIALNO"))
4509     {
4510       /* For certain cards we return special IDs.  There is no
4511          general rule for it so we need to decide case by case. */
4512       if (app->app_local->card_type == CARD_TYPE_BELPIC)
4513         {
4514           /* The eID card has a card number printed on the front matter
4515              which seems to be a good indication. */
4516           unsigned char *buffer;
4517           const unsigned char *p;
4518           size_t buflen, n;
4519           unsigned short path[] = { 0x3F00, 0xDF01, 0x4031 };
4520
4521           err = select_ef_by_path (app, path, DIM(path) );
4522           if (!err)
4523             err = iso7816_read_binary (app_get_slot (app), 0, 0,
4524                                        &buffer, &buflen);
4525           if (err)
4526             {
4527               log_error ("p15: error accessing EF(ID): %s\n",
4528                          gpg_strerror (err));
4529               return err;
4530             }
4531
4532           p = find_tlv (buffer, buflen, 1, &n);
4533           if (p && n == 12)
4534             {
4535               char tmp[12+2+1];
4536               memcpy (tmp, p, 3);
4537               tmp[3] = '-';
4538               memcpy (tmp+4, p+3, 7);
4539               tmp[11] = '-';
4540               memcpy (tmp+12, p+10, 2);
4541               tmp[14] = 0;
4542               send_status_info (ctrl, name, tmp, strlen (tmp), NULL, 0);
4543               xfree (buffer);
4544               return 0;
4545             }
4546           xfree (buffer);
4547         }
4548       else
4549         {
4550           char *sn;
4551
4552           /* We use the first private key object which has a serial
4553            * number set.  If none was found, we parse the first
4554            * object and see whether this has then a serial number.  */
4555           for (prkdf = app->app_local->private_key_info; prkdf;
4556                prkdf = prkdf->next)
4557             if (prkdf->serial_number)
4558               break;
4559           if (!prkdf && app->app_local->private_key_info)
4560             {
4561               prkdf = app->app_local->private_key_info;
4562               keygrip_from_prkdf (app, prkdf);
4563               if (!prkdf->serial_number)
4564                 prkdf = NULL;
4565             }
4566           sn = get_dispserialno (app, prkdf);
4567           /* Unless there is a bogus S/N in the cert, or the product
4568            * has a different strategy for the display-s/n, we should
4569            * have a suitable one from the cert now.  */
4570           if (sn)
4571             {
4572               err = send_status_printf (ctrl, name, "%s", sn);
4573               xfree (sn);
4574               return err;
4575             }
4576         }
4577       /* No abbreviated serial number. */
4578     }
4579   else if (!strcmp (name, "MANUFACTURER"))
4580     {
4581       if (app->app_local->manufacturer_id
4582           && !strchr (app->app_local->manufacturer_id, '[')
4583           && app->app_local->card_product)
4584         return send_status_printf (ctrl, "MANUFACTURER", "0 %s [%s]",
4585                               app->app_local->manufacturer_id,
4586                               cardproduct2str (app->app_local->card_product));
4587       else if (app->app_local->manufacturer_id)
4588         return send_status_printf (ctrl, "MANUFACTURER", "0 %s",
4589                                    app->app_local->manufacturer_id);
4590       else
4591         return 0;
4592     }
4593   else if (!strcmp (name, "CHV-STATUS") || !strcmp (name, "CHV-LABEL"))
4594     {
4595       int is_label = (name[4] == 'L');
4596       aodf_object_t aodf;
4597       aodf_object_t aodfarray[16];
4598       int naodf = 0;
4599       membuf_t mb;
4600       char *p;
4601       int i;
4602
4603       /* Put the AODFs into an array for easier sorting.  Note that we
4604        * handle onl the first 16 encountrer which should be more than
4605        * enough.  */
4606       for (aodf = app->app_local->auth_object_info;
4607            aodf && naodf < DIM(aodfarray); aodf = aodf->next)
4608         if (aodf->objidlen && aodf->pin_reference_valid)
4609           aodfarray[naodf++] = aodf;
4610       qsort (aodfarray, naodf, sizeof *aodfarray, compare_aodf_objid);
4611
4612       init_membuf (&mb, 256);
4613       for (i = 0; i < naodf; i++)
4614         {
4615           /* int j; */
4616           /* log_debug ("p15: AODF[%d] pinref=%lu id=", */
4617           /*            i, aodfarray[i]->pin_reference); */
4618           /* for (j=0; j < aodfarray[i]->objidlen; j++) */
4619           /*   log_printf ("%02X", aodfarray[i]->objid[j]); */
4620           /* Note that there is no need to percent escape the label
4621            * because all white space have been replaced by '_'.  */
4622           if (is_label)
4623             put_membuf_printf (&mb, "%s%s", i? " ":"",
4624                                (aodfarray[i]->label
4625                                 && *aodfarray[i]->label)?
4626                                aodfarray[i]->label:"X");
4627           else
4628             put_membuf_printf
4629               (&mb, "%s%d", i? " ":"",
4630                iso7816_verify_status (app_get_slot (app),
4631                                       aodfarray[i]->pin_reference));
4632         }
4633       put_membuf( &mb, "", 1);
4634       p = get_membuf (&mb, NULL);
4635       if (!p)
4636         return gpg_error_from_syserror ();
4637       err = send_status_direct (ctrl, is_label? "CHV-LABEL":"CHV-STATUS", p);
4638       xfree (p);
4639       return err;
4640     }
4641   else if (!strcmp (name, "KEY-LABEL"))
4642     {
4643       /* Send KEY-LABEL lines for all private key objects.  */
4644       const char *label;
4645       char *idbuf, *labelbuf;
4646
4647       for (prkdf = app->app_local->private_key_info; prkdf;
4648            prkdf = prkdf->next)
4649         {
4650           idbuf = keyref_from_prkdf (app, prkdf);
4651           if (!idbuf)
4652             return gpg_error_from_syserror ();
4653
4654           label = (prkdf->label && *prkdf->label)? prkdf->label : "-";
4655           labelbuf = percent_data_escape (0, NULL, label, strlen (label));
4656           if (!labelbuf)
4657             {
4658               xfree (idbuf);
4659               return gpg_error_from_syserror ();
4660             }
4661
4662           send_status_info (ctrl, name,
4663                             idbuf, strlen (idbuf),
4664                             labelbuf, strlen(labelbuf),
4665                             NULL, 0);
4666           xfree (idbuf);
4667           xfree (labelbuf);
4668         }
4669       return 0;
4670     }
4671   else if (!strcmp (name, "KEY-FPR"))
4672     {
4673       /* Send KEY-FPR for the two openpgp keys. */
4674       for (prkdf = app->app_local->private_key_info; prkdf;
4675            prkdf = prkdf->next)
4676         {
4677           if (app->app_local->any_gpgusage)
4678             {
4679               if (prkdf->gpgusage.sign)
4680                 break;
4681             }
4682           else
4683             {
4684               if (prkdf->usageflags.sign || prkdf->usageflags.sign_recover)
4685                 break;
4686             }
4687         }
4688       if (prkdf)
4689         send_key_fpr (app, ctrl, prkdf, 1);
4690       for (prkdf = app->app_local->private_key_info; prkdf;
4691            prkdf = prkdf->next)
4692         {
4693           if (app->app_local->any_gpgusage)
4694             {
4695               if (prkdf->gpgusage.encr)
4696                 break;
4697             }
4698           else
4699             {
4700               if (prkdf->usageflags.decrypt || prkdf->usageflags.unwrap)
4701                 break;
4702             }
4703         }
4704       if (prkdf)
4705         send_key_fpr (app, ctrl, prkdf, 2);
4706       return 0;
4707     }
4708
4709   return gpg_error (GPG_ERR_INV_NAME);
4710 }
4711
4712
4713
4714
4715 /* Micardo cards require special treatment. This is a helper for the
4716    crypto functions to manage the security environment.  We expect that
4717    the key file has already been selected. FID is the one of the
4718    selected key. */
4719 static gpg_error_t
4720 micardo_mse (app_t app, unsigned short fid)
4721 {
4722   gpg_error_t err;
4723   int recno;
4724   unsigned short refdata = 0;
4725   int se_num;
4726   unsigned char msebuf[10];
4727
4728   /* Read the KeyD file containing extra information on keys. */
4729   err = iso7816_select_file (app_get_slot (app), 0x0013, 0);
4730   if (err)
4731     {
4732       log_error ("p15: error reading EF_keyD: %s\n", gpg_strerror (err));
4733       return err;
4734     }
4735
4736   for (recno = 1, se_num = -1; ; recno++)
4737     {
4738       unsigned char *buffer;
4739       size_t buflen;
4740       size_t n, nn;
4741       const unsigned char *p, *pp;
4742
4743       err = iso7816_read_record (app_get_slot (app), recno, 1, 0,
4744                                  &buffer, &buflen);
4745       if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
4746         break; /* ready */
4747       if (err)
4748         {
4749           log_error ("p15: error reading EF_keyD record: %s\n",
4750                      gpg_strerror (err));
4751           return err;
4752         }
4753       if (opt.verbose)
4754         {
4755           log_info (buffer, buflen, "p15: keyD record: ");
4756           log_printhex (buffer, buflen, "");
4757         }
4758       p = find_tlv (buffer, buflen, 0x83, &n);
4759       if (p && n == 4 && ((p[2]<<8)|p[3]) == fid)
4760         {
4761           refdata = ((p[0]<<8)|p[1]);
4762           /* Locate the SE DO and the there included sec env number. */
4763           p = find_tlv (buffer, buflen, 0x7b, &n);
4764           if (p && n)
4765             {
4766               pp = find_tlv (p, n, 0x80, &nn);
4767               if (pp && nn == 1)
4768                 {
4769                   se_num = *pp;
4770                   xfree (buffer);
4771                   break; /* found. */
4772                 }
4773             }
4774         }
4775       xfree (buffer);
4776     }
4777   if (se_num == -1)
4778     {
4779       log_error ("p15: CRT for keyfile %04hX not found\n", fid);
4780       return gpg_error (GPG_ERR_NOT_FOUND);
4781     }
4782
4783
4784   /* Restore the security environment to SE_NUM if needed */
4785   if (se_num)
4786     {
4787       err = iso7816_manage_security_env (app_get_slot (app),
4788                                          0xf3, se_num, NULL, 0);
4789       if (err)
4790         {
4791           log_error ("p15: restoring SE to %d failed: %s\n",
4792                      se_num, gpg_strerror (err));
4793           return err;
4794         }
4795     }
4796
4797   /* Set the DST reference data. */
4798   msebuf[0] = 0x83;
4799   msebuf[1] = 0x03;
4800   msebuf[2] = 0x80;
4801   msebuf[3] = (refdata >> 8);
4802   msebuf[4] = refdata;
4803   err = iso7816_manage_security_env (app_get_slot (app), 0x41, 0xb6, msebuf, 5);
4804   if (err)
4805     {
4806       log_error ("p15: setting SE to reference file %04hX failed: %s\n",
4807                  refdata, gpg_strerror (err));
4808       return err;
4809     }
4810   return 0;
4811 }
4812
4813
4814
4815 /* Prepare the verification of the PIN for the key PRKDF by checking
4816  * the AODF and selecting the key file.  KEYREF is used for error
4817  * messages.  AODF may be NULL if no verification needs to be done. */
4818 static gpg_error_t
4819 prepare_verify_pin (app_t app, const char *keyref,
4820                     prkdf_object_t prkdf, aodf_object_t aodf)
4821 {
4822   gpg_error_t err;
4823   int i;
4824
4825   if (aodf)
4826     {
4827       if (opt.verbose)
4828         {
4829           log_info ("p15: using AODF %04hX id=", aodf->fid);
4830           for (i=0; i < aodf->objidlen; i++)
4831             log_printf ("%02X", aodf->objid[i]);
4832           log_printf ("\n");
4833         }
4834
4835       if (aodf->authid && opt.verbose)
4836         log_info ("p15: PIN is controlled by another authentication token\n");
4837
4838       if (aodf->pinflags.integrity_protected
4839           || aodf->pinflags.confidentiality_protected)
4840         {
4841           log_error ("p15: PIN verification requires"
4842                      " unsupported protection method\n");
4843           return gpg_error (GPG_ERR_BAD_PIN_METHOD);
4844         }
4845       if (!aodf->stored_length && aodf->pinflags.needs_padding)
4846         {
4847           log_error ("p15: PIN verification requires"
4848                      " padding but no length known\n");
4849           return gpg_error (GPG_ERR_INV_CARD);
4850         }
4851     }
4852
4853
4854   if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
4855     {
4856       /* According to our protocol analysis we need to select a
4857        * special AID here.  Before that the master file needs to be
4858        * selected.  (RID A000000167 is assigned to IBM) */
4859       static char const dtrust_aid[] =
4860         { 0xA0, 0x00, 0x00, 0x01, 0x67, 0x45, 0x53, 0x49, 0x47, 0x4E };
4861
4862       err = iso7816_select_mf (app_get_slot (app));
4863       if (!err)
4864         err = iso7816_select_application (app_get_slot (app),
4865                                           dtrust_aid, sizeof dtrust_aid, 0);
4866       if (err)
4867         log_error ("p15: error selecting D-TRUST's AID for key %s: %s\n",
4868                    keyref, gpg_strerror (err));
4869     }
4870   else if (prkdf)
4871     {
4872       /* Standard case: Select the key file.  Note that this may
4873        * change the security environment thus we need to do it before
4874        * PIN verification. */
4875       err = select_ef_by_path (app, prkdf->path, prkdf->pathlen);
4876       if (err)
4877         log_error ("p15: error selecting file for key %s: %s\n",
4878                    keyref, gpg_strerror (err));
4879     }
4880   else
4881     {
4882       log_info ("p15: skipping EF selection for auth object '%s'\n", keyref);
4883       err = 0;
4884     }
4885
4886   return err;
4887 }
4888
4889
4890 static int
4891 any_control_or_space (const char *string)
4892 {
4893   const unsigned char *s;
4894
4895   for (s = string; *string; string++)
4896     if (*s <= 0x20 || *s >= 0x7f)
4897       return 1;
4898   return 0;
4899 }
4900
4901
4902 /* Return a malloced serial number to be shown to the user.  PRKDF is
4903  * used to get it from a certificate; PRKDF may be NULL.  */
4904 static char *
4905 get_dispserialno (app_t app, prkdf_object_t prkdf)
4906 {
4907   char *serial;
4908   size_t n;
4909
4910   /* We prefer the SerialNumber RDN from the Subject-DN but we don't
4911    * use it if it features a percent sign (special character in pin
4912    * prompts) or has any control character.  */
4913   if (app->app_local->card_product == CARD_PRODUCT_RSCS)
4914     {
4915       /* We use only the right 8 hex digits.  */
4916       serial = app_get_serialno (app);
4917       if (serial && (n=strlen (serial)) > 8)
4918         memmove (serial, serial + n - 8, 9);
4919     }
4920   else if (prkdf && prkdf->serial_number && *prkdf->serial_number
4921       && !strchr (prkdf->serial_number, '%')
4922       && !any_control_or_space (prkdf->serial_number))
4923     {
4924       serial = xtrystrdup (prkdf->serial_number);
4925     }
4926   else
4927     {
4928       serial = app_get_serialno (app);
4929     }
4930   return serial;
4931 }
4932
4933
4934 /* Return an allocated string to be used as prompt.  PRKDF may be
4935  * NULL.  Returns NULL on malloc error.  */
4936 static char *
4937 make_pin_prompt (app_t app, int remaining, const char *firstline,
4938                  prkdf_object_t prkdf)
4939 {
4940   char *serial, *tmpbuf, *result;
4941   const char *holder;
4942
4943   serial = get_dispserialno (app, prkdf);
4944
4945   if (prkdf && prkdf->common_name)
4946     holder = prkdf->common_name;
4947   else if (app->app_local->token_label)
4948     holder = app->app_local->token_label;
4949   else
4950     holder = "";
4951
4952   /* TRANSLATORS: Put a \x1f right before a colon.  This can be
4953    * used by pinentry to nicely align the names and values.  Keep
4954    * the %s at the start and end of the string.  */
4955   result = xtryasprintf (_("%s"
4956                            "Number\x1f: %s%%0A"
4957                            "Holder\x1f: %s"
4958                            "%s"),
4959                          "\x1e",
4960                          serial,
4961                          holder,
4962                          "");
4963   xfree (serial);
4964   if (!result)
4965     return NULL; /* Out of core.  */
4966
4967   /* Append a "remaining attempts" info if needed.  */
4968   if (remaining != -1 && remaining < 3)
4969     {
4970       char *rembuf;
4971
4972       /* TRANSLATORS: This is the number of remaining attempts to
4973        * enter a PIN.  Use %%0A (double-percent,0A) for a linefeed. */
4974       rembuf = xtryasprintf (_("Remaining attempts: %d"), remaining);
4975       if (rembuf)
4976         {
4977           tmpbuf = strconcat (firstline, "%0A%0A", result,
4978                               "%0A%0A", rembuf, NULL);
4979           xfree (rembuf);
4980         }
4981       else
4982         tmpbuf = NULL;
4983       xfree (result);
4984       result = tmpbuf;
4985     }
4986   else
4987     {
4988       tmpbuf = strconcat (firstline, "%0A%0A", result, NULL);
4989       xfree (result);
4990       result = tmpbuf;
4991     }
4992
4993   return result;
4994 }
4995
4996
4997 /* Given the private key object PRKDF and its authentication object
4998  * AODF ask for the PIN and verify that PIN.  If AODF is NULL, no
4999  * authentication is done.  */
5000 static gpg_error_t
5001 verify_pin (app_t app,
5002             gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg,
5003             prkdf_object_t prkdf, aodf_object_t aodf)
5004 {
5005   gpg_error_t err;
5006   char *pinvalue;
5007   size_t pinvaluelen;
5008   const char *label;
5009   const char *errstr;
5010   const char *s;
5011   int remaining;
5012   int pin_reference;
5013   int verified = 0;
5014   int i;
5015
5016   if (!aodf)
5017     return 0;
5018
5019   pin_reference = aodf->pin_reference_valid? aodf->pin_reference : 0;
5020
5021   if (IS_CARDOS_5 (app))
5022     {
5023       /* We know that this card supports a verify status check.  Note
5024        * that in contrast to PIV cards ISO7816_VERIFY_NOT_NEEDED is
5025        * not supported.  Noet that we don't use the pin_verified cache
5026        * status because that is not as reliable than to ask the card
5027        * about its state.  */
5028       if (prkdf)  /* Clear the cache which we don't use.  */
5029         prkdf->pin_verified = 0;
5030
5031       remaining = iso7816_verify_status (app_get_slot (app), pin_reference);
5032       if (remaining == ISO7816_VERIFY_NOT_NEEDED)
5033         {
5034           verified = 1;
5035           remaining = -1;
5036         }
5037       else if (remaining < 0)
5038         remaining = -1; /* We don't care about the concrete error.  */
5039       else if (remaining < 3)
5040         log_info ("p15: PIN has %d attempts left\n", remaining);
5041     }
5042   else
5043     remaining = -1;  /* Unknown.  */
5044
5045   /* Check whether we already verified it.  */
5046   if (prkdf && (prkdf->pin_verified || verified))
5047     return 0;  /* Already done.  */
5048
5049   if (prkdf
5050       && prkdf->usageflags.non_repudiation
5051       && (app->app_local->card_type == CARD_TYPE_BELPIC
5052           || app->app_local->card_product == CARD_PRODUCT_DTRUST))
5053     label = _("||Please enter the PIN for the key to create "
5054               "qualified signatures.");
5055   else if (aodf->pinflags.so_pin)
5056     label = _("|A|Please enter the Admin PIN");
5057   else if (aodf->pinflags.unblocking_pin)
5058     label = _("|P|Please enter the PIN Unblocking Code (PUK) "
5059               "for the standard keys.");
5060   else
5061     label = _("||Please enter the PIN for the standard keys.");
5062
5063   {
5064     char *prompt = make_pin_prompt (app, remaining, label, prkdf);
5065     if (!prompt)
5066       err = gpg_error_from_syserror ();
5067     else
5068       err = pincb (pincb_arg, prompt, &pinvalue);
5069     xfree (prompt);
5070   }
5071   if (err)
5072     {
5073       log_info ("p15: PIN callback returned error: %s\n", gpg_strerror (err));
5074       return err;
5075     }
5076
5077   /* We might need to cope with UTF8 things here.  Not sure how
5078      min_length etc. are exactly defined, for now we take them as
5079      a plain octet count. */
5080   if (strlen (pinvalue) < aodf->min_length)
5081     {
5082       log_error ("p15: PIN is too short; minimum length is %lu\n",
5083                  aodf->min_length);
5084       err = gpg_error (GPG_ERR_BAD_PIN);
5085     }
5086   else if (aodf->stored_length && strlen (pinvalue) > aodf->stored_length)
5087     {
5088       /* This would otherwise truncate the PIN silently. */
5089       log_error ("p15: PIN is too large; maximum length is %lu\n",
5090                  aodf->stored_length);
5091       err = gpg_error (GPG_ERR_BAD_PIN);
5092     }
5093   else if (aodf->max_length_valid && strlen (pinvalue) > aodf->max_length)
5094     {
5095       log_error ("p15: PIN is too large; maximum length is %lu\n",
5096                  aodf->max_length);
5097       err = gpg_error (GPG_ERR_BAD_PIN);
5098     }
5099
5100   if (err)
5101     {
5102       xfree (pinvalue);
5103       return err;
5104     }
5105
5106   errstr = NULL;
5107   err = 0;
5108   switch (aodf->pintype)
5109     {
5110     case PIN_TYPE_BCD:
5111     case PIN_TYPE_ASCII_NUMERIC:
5112       for (s=pinvalue; digitp (s); s++)
5113         ;
5114       if (*s)
5115         {
5116           errstr = "Non-numeric digits found in PIN";
5117           err = gpg_error (GPG_ERR_BAD_PIN);
5118         }
5119       break;
5120     case PIN_TYPE_UTF8:
5121       break;
5122     case PIN_TYPE_HALF_NIBBLE_BCD:
5123       errstr = "PIN type Half-Nibble-BCD is not supported";
5124       break;
5125     case PIN_TYPE_ISO9564_1:
5126       errstr = "PIN type ISO9564-1 is not supported";
5127       break;
5128     default:
5129       errstr = "Unknown PIN type";
5130       break;
5131     }
5132   if (errstr)
5133     {
5134       log_error ("p15: can't verify PIN: %s\n", errstr);
5135       xfree (pinvalue);
5136       return err? err : gpg_error (GPG_ERR_BAD_PIN_METHOD);
5137     }
5138
5139
5140   if (aodf->pintype == PIN_TYPE_BCD )
5141     {
5142       char *paddedpin;
5143       int ndigits;
5144
5145       for (ndigits=0, s=pinvalue; *s; ndigits++, s++)
5146         ;
5147       paddedpin = xtrymalloc (aodf->stored_length+1);
5148       if (!paddedpin)
5149         {
5150           err = gpg_error_from_syserror ();
5151           xfree (pinvalue);
5152           return err;
5153         }
5154
5155       i = 0;
5156       paddedpin[i++] = 0x20 | (ndigits & 0x0f);
5157       for (s=pinvalue; i < aodf->stored_length && *s && s[1]; s = s+2 )
5158         paddedpin[i++] = (((*s - '0') << 4) | ((s[1] - '0') & 0x0f));
5159       if (i < aodf->stored_length && *s)
5160         paddedpin[i++] = (((*s - '0') << 4)
5161                           |((aodf->pad_char_valid?aodf->pad_char:0)&0x0f));
5162
5163       if (aodf->pinflags.needs_padding)
5164         {
5165           while (i < aodf->stored_length)
5166             paddedpin[i++] = aodf->pad_char_valid? aodf->pad_char : 0;
5167         }
5168
5169       xfree (pinvalue);
5170       pinvalue = paddedpin;
5171       pinvaluelen = i;
5172     }
5173   else if (aodf->pinflags.needs_padding)
5174     {
5175       char *paddedpin;
5176
5177       paddedpin = xtrymalloc (aodf->stored_length+1);
5178       if (!paddedpin)
5179         {
5180           err = gpg_error_from_syserror ();
5181           xfree (pinvalue);
5182           return err;
5183         }
5184       for (i=0, s=pinvalue; i < aodf->stored_length && *s; i++, s++)
5185         paddedpin[i] = *s;
5186       /* Not sure what padding char to use if none has been set.
5187          For now we use 0x00; maybe a space would be better. */
5188       for (; i < aodf->stored_length; i++)
5189         paddedpin[i] = aodf->pad_char_valid? aodf->pad_char : 0;
5190       paddedpin[i] = 0;
5191       pinvaluelen = i;
5192       xfree (pinvalue);
5193       pinvalue = paddedpin;
5194     }
5195   else
5196     pinvaluelen = strlen (pinvalue);
5197
5198   /* log_printhex (pinvalue, pinvaluelen, */
5199   /*               "about to verify with ref %lu pin:", pin_reference); */
5200   err = iso7816_verify (app_get_slot (app), pin_reference,
5201                         pinvalue, pinvaluelen);
5202   xfree (pinvalue);
5203   if (err)
5204     {
5205       log_error ("p15: PIN verification failed: %s\n", gpg_strerror (err));
5206       return err;
5207     }
5208   if (opt.verbose)
5209     log_info ("p15: PIN verification succeeded\n");
5210   if (prkdf)
5211     prkdf->pin_verified = 1;
5212
5213   return 0;
5214 }
5215
5216
5217
5218
5219 /* Handler for the PKSIGN command.
5220
5221    Create the signature and return the allocated result in OUTDATA.
5222    If a PIN is required, the PINCB will be used to ask for the PIN;
5223    that callback should return the PIN in an allocated buffer and
5224    store that as the 3rd argument.  */
5225 static gpg_error_t
5226 do_sign (app_t app, ctrl_t ctrl, const char *keyidstr, int hashalgo,
5227          gpg_error_t (*pincb)(void*, const char *, char **),
5228          void *pincb_arg,
5229          const void *indata, size_t indatalen,
5230          unsigned char **outdata, size_t *outdatalen )
5231 {
5232   gpg_error_t err;
5233   prkdf_object_t prkdf;    /* The private key object. */
5234   aodf_object_t aodf;      /* The associated authentication object. */
5235   int mse_done = 0;        /* Set to true if the MSE has been done. */
5236   unsigned int digestlen;  /* Length of the hash.  */
5237   int exmode, le_value;
5238   unsigned char oidbuf[64];
5239   size_t oidbuflen;
5240   size_t n;
5241   unsigned char *indata_buffer = NULL; /* Malloced helper.  */
5242
5243   (void)ctrl;
5244
5245   if (!keyidstr || !*keyidstr || !indatalen)
5246     return gpg_error (GPG_ERR_INV_VALUE);
5247
5248   err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5249   if (err)
5250     return err;
5251   if (!(prkdf->usageflags.sign
5252         || prkdf->usageflags.sign_recover
5253         || prkdf->usageflags.non_repudiation
5254         || prkdf->gpgusage.cert
5255         || prkdf->gpgusage.sign
5256         || prkdf->gpgusage.auth ))
5257     {
5258       log_error ("p15: key %s may not be used for signing\n", keyidstr);
5259       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
5260     }
5261
5262   if (!prkdf->authid)
5263     {
5264       log_error ("p15: no authentication object defined for %s\n", keyidstr);
5265       /* fixme: we might want to go ahead and do without PIN
5266          verification. */
5267       return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
5268     }
5269
5270   /* Find the authentication object to this private key object. */
5271   for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5272     if (aodf->objidlen == prkdf->authidlen
5273         && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
5274       break;
5275   if (!aodf)
5276     log_info ("p15: no authentication for %s needed\n", keyidstr);
5277
5278   /* We need some more info about the key - get the keygrip to
5279    * populate these fields.  */
5280   err = keygrip_from_prkdf (app, prkdf);
5281   if (err)
5282     {
5283       log_error ("p15: keygrip_from_prkdf failed: %s\n", gpg_strerror (err));
5284       return err;
5285     }
5286
5287
5288   digestlen = gcry_md_get_algo_dlen (hashalgo);
5289
5290   /* We handle ECC separately from RSA so that we do not need to touch
5291    * working code.  In particular we prepare the input data before the
5292    * verify and a possible MSE.  */
5293   if (prkdf->is_ecc)
5294     {
5295       if (digestlen != 32 && digestlen != 48 && digestlen != 64)
5296         {
5297           log_error ("p15: ECC signing not possible: dlen=%u\n", digestlen);
5298           err = gpg_error (GPG_ERR_DIGEST_ALGO);
5299           goto leave;
5300         }
5301
5302       if (indatalen == digestlen)
5303         ; /* Already prepared.  */
5304       else if (indatalen > digestlen)
5305         {
5306           /* Assume a PKCS#1 prefix and remove it.  */
5307           oidbuflen = sizeof oidbuf;
5308           err = gcry_md_get_asnoid (hashalgo, &oidbuf, &oidbuflen);
5309           if (err)
5310             {
5311               log_error ("p15: no OID for hash algo %d\n", hashalgo);
5312               err = gpg_error (GPG_ERR_INTERNAL);
5313               goto leave;
5314             }
5315           if (indatalen != oidbuflen + digestlen
5316               || memcmp (indata, oidbuf, oidbuflen))
5317             {
5318               log_error ("p15: input data too long for ECC: len=%zu\n",
5319                          indatalen);
5320               err = gpg_error (GPG_ERR_INV_VALUE);
5321               goto leave;
5322             }
5323           indata = (const char*)indata + oidbuflen;
5324           indatalen -= oidbuflen;
5325         }
5326       else
5327         {
5328           log_error ("p15: input data too short for ECC: len=%zu\n",
5329                      indatalen);
5330           err = gpg_error (GPG_ERR_INV_VALUE);
5331           goto leave;
5332         }
5333     }
5334   else /* Prepare RSA input.  */
5335     {
5336       unsigned int framelen;
5337       unsigned char *frame;
5338       int i;
5339
5340       framelen = (prkdf->keynbits+7) / 8;
5341       if (!framelen)
5342         {
5343           log_error ("p15: key length unknown"
5344                      " - can't prepare PKCS#v1.5 frame\n");
5345           err = gpg_error (GPG_ERR_INV_VALUE);
5346           goto leave;
5347         }
5348
5349       oidbuflen = sizeof oidbuf;
5350       if (!hashalgo)
5351         {
5352           /* We assume that indata already has the required
5353            * digestinfo; thus merely prepend the padding below.  */
5354         }
5355       else if ((err = gcry_md_get_asnoid (hashalgo, &oidbuf, &oidbuflen)))
5356         {
5357           log_debug ("p15: no OID for hash algo %d\n", hashalgo);
5358           goto leave;
5359         }
5360       else
5361         {
5362           if (indatalen == digestlen)
5363             {
5364               /* Plain hash in INDATA; prepend the digestinfo.  */
5365               indata_buffer = xtrymalloc (oidbuflen + indatalen);
5366               if (!indata_buffer)
5367                 {
5368                   err = gpg_error_from_syserror ();
5369                   goto leave;
5370                 }
5371               memcpy (indata_buffer, oidbuf, oidbuflen);
5372               memcpy (indata_buffer+oidbuflen, indata, indatalen);
5373               indata = indata_buffer;
5374               indatalen = oidbuflen + indatalen;
5375             }
5376           else if (indatalen == oidbuflen + digestlen
5377                    && !memcmp (indata, oidbuf, oidbuflen))
5378             ; /* We already got the correct prefix.  */
5379           else
5380             {
5381               err = gpg_error (GPG_ERR_INV_VALUE);
5382               log_error ("p15: bad input for signing with RSA and hash %d\n",
5383                          hashalgo);
5384               goto leave;
5385             }
5386         }
5387       /* Now prepend the pkcs#v1.5 padding.  We require at least 8
5388        * byte of padding and 3 extra bytes for the prefix and the
5389        * delimiting nul.  */
5390       if (!indatalen || indatalen + 8 + 4 > framelen)
5391         {
5392           err = gpg_error (GPG_ERR_INV_VALUE);
5393           log_error ("p15: input does not fit into a %u bit PKCS#v1.5 frame\n",
5394                      8*framelen);
5395           goto leave;
5396         }
5397       frame = xtrymalloc (framelen);
5398       if (!frame)
5399         {
5400           err = gpg_error_from_syserror ();
5401           goto leave;
5402         }
5403       if (app->app_local->card_type == CARD_TYPE_BELPIC)
5404         {
5405           /* This card wants only the plain hash w/o any prefix.  */
5406           /* FIXME: We may want to remove this code because it is unlikely
5407            * that such cards are still in use.  */
5408           memcpy (frame, indata, indatalen);
5409           framelen = indatalen;
5410         }
5411       else
5412         {
5413           n = 0;
5414           frame[n++] = 0;
5415           frame[n++] = 1; /* Block type. */
5416           i = framelen - indatalen - 3 ;
5417           memset (frame+n, 0xff, i);
5418           n += i;
5419           frame[n++] = 0; /* Delimiter.  */
5420           memcpy (frame+n, indata, indatalen);
5421           n += indatalen;
5422           log_assert (n == framelen);
5423         }
5424       /* And now put it into the indata_buffer.  */
5425       xfree (indata_buffer);
5426       indata_buffer = frame;
5427       indata = indata_buffer;
5428       indatalen = framelen;
5429     }
5430
5431   /* Prepare PIN verification.  This is split so that we can do
5432    * MSE operation for some task after having selected the key file but
5433    * before sending the verify APDU.  */
5434   err = prepare_verify_pin (app, keyidstr, prkdf, aodf);
5435   if (err)
5436     return err;
5437
5438   /* Due to the fact that the non-repudiation signature on a BELPIC
5439      card requires a verify immediately before the DSO we set the
5440      MSE before we do the verification.  Other cards might also allow
5441      this but I don't want to break anything, thus we do it only
5442      for the BELPIC card here.
5443      FIXME: see comment above about these cards.   */
5444   if (app->app_local->card_type == CARD_TYPE_BELPIC)
5445     {
5446       unsigned char mse[5];
5447
5448       mse[0] = 4;    /* Length of the template. */
5449       mse[1] = 0x80; /* Algorithm reference tag. */
5450       if (hashalgo == MD_USER_TLS_MD5SHA1)
5451         mse[2] = 0x01; /* Let card do pkcs#1 0xFF padding. */
5452       else
5453         mse[2] = 0x02; /* RSASSA-PKCS1-v1.5 using SHA1. */
5454       mse[3] = 0x84; /* Private key reference tag. */
5455       mse[4] = prkdf->key_reference_valid? prkdf->key_reference : 0x82;
5456
5457       err = iso7816_manage_security_env (app_get_slot (app),
5458                                          0x41, 0xB6,
5459                                          mse, sizeof mse);
5460       mse_done = 1;
5461     }
5462   if (err)
5463     {
5464       log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5465       goto leave;
5466     }
5467
5468   /* Now that we have all the information available run the actual PIN
5469    * verification.*/
5470   err = verify_pin (app, pincb, pincb_arg, prkdf, aodf);
5471   if (err)
5472     return err;
5473
5474   /* Manage security environment needs to be tweaked for certain cards. */
5475   if (mse_done)
5476     err = 0;
5477   else if (app->app_local->card_type == CARD_TYPE_TCOS)
5478     {
5479       /* TCOS creates signatures always using the local key 0.  MSE
5480          may not be used. */
5481     }
5482   else if (app->app_local->card_type == CARD_TYPE_MICARDO)
5483     {
5484       if (!prkdf->pathlen)
5485         err = gpg_error (GPG_ERR_BUG);
5486       else
5487         err = micardo_mse (app, prkdf->path[prkdf->pathlen-1]);
5488     }
5489   else if (prkdf->key_reference_valid)
5490     {
5491       unsigned char mse[3];
5492
5493       mse[0] = 0x84; /* Select asym. key. */
5494       mse[1] = 1;
5495       mse[2] = prkdf->key_reference;
5496
5497       err = iso7816_manage_security_env (app_get_slot (app),
5498                                          0x41, 0xB6,
5499                                          mse, sizeof mse);
5500     }
5501   if (err)
5502     {
5503       log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5504       goto leave;
5505     }
5506
5507   if (prkdf->keyalgo == GCRY_PK_RSA && prkdf->keynbits > 2048)
5508     {
5509       exmode = 1;
5510       le_value = prkdf->keynbits / 8;
5511     }
5512   else
5513     {
5514       exmode = 0;
5515       le_value = 0;
5516     }
5517
5518   err = iso7816_compute_ds (app_get_slot (app),
5519                             exmode, indata, indatalen,
5520                             le_value, outdata, outdatalen);
5521
5522  leave:
5523   xfree (indata_buffer);
5524   return err;
5525 }
5526
5527
5528 /* Handler for the PKAUTH command.
5529
5530    This is basically the same as the PKSIGN command but we first check
5531    that the requested key is suitable for authentication; that is, it
5532    must match the criteria used for the attribute $AUTHKEYID.  See
5533    do_sign for calling conventions; there is no HASHALGO, though. */
5534 static gpg_error_t
5535 do_auth (app_t app, ctrl_t ctrl, const char *keyidstr,
5536          gpg_error_t (*pincb)(void*, const char *, char **),
5537          void *pincb_arg,
5538          const void *indata, size_t indatalen,
5539          unsigned char **outdata, size_t *outdatalen )
5540 {
5541   gpg_error_t err;
5542   prkdf_object_t prkdf;
5543   int algo;
5544
5545   if (!keyidstr || !*keyidstr)
5546     return gpg_error (GPG_ERR_INV_VALUE);
5547
5548   err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5549   if (err)
5550     return err;
5551   if (!(prkdf->usageflags.sign || prkdf->gpgusage.auth))
5552     {
5553       log_error ("p15: key %s may not be used for authentication\n", keyidstr);
5554       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
5555     }
5556
5557   algo = indatalen == 36? MD_USER_TLS_MD5SHA1 : GCRY_MD_SHA1;
5558   return do_sign (app, ctrl, keyidstr, algo, pincb, pincb_arg,
5559                   indata, indatalen, outdata, outdatalen);
5560 }
5561
5562
5563 /* Handler for the PKDECRYPT command.  Decrypt the data in INDATA and
5564  * return the allocated result in OUTDATA.  If a PIN is required the
5565  * PINCB will be used to ask for the PIN; it should return the PIN in
5566  * an allocated buffer and put it into PIN.  */
5567 static gpg_error_t
5568 do_decipher (app_t app, ctrl_t ctrl, const char *keyidstr,
5569              gpg_error_t (*pincb)(void*, const char *, char **),
5570              void *pincb_arg,
5571              const void *indata, size_t indatalen,
5572              unsigned char **outdata, size_t *outdatalen,
5573              unsigned int *r_info)
5574 {
5575   gpg_error_t err;
5576   prkdf_object_t prkdf;    /* The private key object. */
5577   aodf_object_t aodf;      /* The associated authentication object. */
5578   int exmode, le_value, padind;
5579
5580   (void)ctrl;
5581   (void)r_info;
5582
5583   if (!keyidstr || !*keyidstr)
5584     return gpg_error (GPG_ERR_INV_VALUE);
5585   if (!indatalen || !indata || !outdatalen || !outdata)
5586     return gpg_error (GPG_ERR_INV_ARG);
5587
5588   err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5589   if (err)
5590     return err;
5591   if (!(prkdf->usageflags.decrypt
5592         || prkdf->usageflags.unwrap
5593         || prkdf->gpgusage.encr     ))
5594     {
5595       log_error ("p15: key %s may not be used for decryption\n", keyidstr);
5596       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
5597     }
5598
5599   /* Find the authentication object to this private key object. */
5600   if (!prkdf->authid)
5601     {
5602       log_error ("p15: no authentication object defined for %s\n", keyidstr);
5603       /* fixme: we might want to go ahead and do without PIN
5604          verification. */
5605       return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
5606     }
5607   for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5608     if (aodf->objidlen == prkdf->authidlen
5609         && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
5610       break;
5611   if (!aodf)
5612     log_info ("p15: no authentication for %s needed\n", keyidstr);
5613
5614   /* We need some more info about the key - get the keygrip to
5615    * populate these fields.  */
5616   err = keygrip_from_prkdf (app, prkdf);
5617   if (err)
5618     {
5619       log_error ("p15: keygrip_from_prkdf failed: %s\n", gpg_strerror (err));
5620       return err;
5621     }
5622
5623   /* Verify the PIN.  */
5624   err = prepare_verify_pin (app, keyidstr, prkdf, aodf);
5625   if (!err)
5626     err = verify_pin (app, pincb, pincb_arg, prkdf, aodf);
5627   if (err)
5628     return err;
5629
5630   if (prkdf->is_ecc && IS_CARDOS_5(app))
5631     {
5632
5633       err = iso7816_manage_security_env (app_get_slot (app), 0xF3, 0x01,
5634                                          NULL, 0);
5635       if (err)
5636         {
5637           log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5638           return err;
5639         }
5640     }
5641
5642
5643   /* The next is guess work for CardOS.  */
5644   if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
5645     {
5646       /* From analyzing an USB trace of a Windows signing application
5647        * we see that the SE is simply reset to 0x14.  It seems to be
5648        * sufficient to do this for decryption; signing still works
5649        * with the standard code despite that our trace showed that
5650        * there the SE is restored to 0x09.  Note that the special
5651        * D-Trust AID is in any case select by prepare_verify_pin.
5652        *
5653        * Hey, D-Trust please hand over the specs so that you can
5654        * actually sell your cards and we can properly implement it;
5655        * other vendors understand this and do not demand ridiculous
5656        * paper work or complicated procedures to get samples.  */
5657       err = iso7816_manage_security_env (app_get_slot (app),
5658                                          0xF3, 0x14, NULL, 0);
5659
5660     }
5661   else if (prkdf->key_reference_valid)
5662     {
5663       unsigned char mse[9];
5664       int i;
5665
5666       /* Note: This works with CardOS but the D-Trust card has the
5667        * problem that the next created signature would be broken.  */
5668
5669       i = 0;
5670       if (!prkdf->is_ecc)
5671         {
5672           mse[i++] = 0x80; /* Algorithm reference.  */
5673           mse[i++] = 1;
5674           mse[i++] = 0x0a; /* RSA, no padding.  */
5675         }
5676       mse[i++] = 0x84; /* Key reference.  */
5677       mse[i++] = 1;
5678       mse[i++] = prkdf->key_reference;
5679       if (prkdf->is_ecc && IS_CARDOS_5(app))
5680         {
5681           mse[i++] = 0x95; /* ???.  */
5682           mse[i++] = 1;
5683           mse[i++] = 0x40;
5684         }
5685       log_assert (i <= DIM(mse));
5686       err = iso7816_manage_security_env (app_get_slot (app), 0x41, 0xB8,
5687                                          mse, i);
5688     }
5689   /* Check for MSE error.  */
5690   if (err)
5691     {
5692       log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5693       return err;
5694     }
5695
5696   exmode = le_value = 0;
5697   padind = 0;
5698   if (prkdf->keyalgo == GCRY_PK_RSA && prkdf->keynbits > 2048)
5699     {
5700       exmode = 1;   /* Extended length w/o a limit.  */
5701       le_value = prkdf->keynbits / 8;
5702     }
5703
5704   if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
5705     padind = 0x81;
5706
5707   if (prkdf->is_ecc && IS_CARDOS_5(app))
5708     {
5709       if ((indatalen & 1) && *(const char *)indata == 0x04)
5710         {
5711           /* Strip indicator byte.  */
5712           indatalen--;
5713           indata = (const char *)indata + 1;
5714         }
5715       err = iso7816_pso_csv (app_get_slot (app), exmode,
5716                              indata, indatalen,
5717                              le_value,
5718                              outdata, outdatalen);
5719     }
5720   else
5721     {
5722       err = iso7816_decipher (app_get_slot (app), exmode,
5723                               indata, indatalen,
5724                               le_value, padind,
5725                               outdata, outdatalen);
5726     }
5727
5728   return err;
5729 }
5730
5731
5732 /* Perform a simple verify operation for the PIN specified by
5733  * KEYIDSTR.  Note that we require a key reference which is then used
5734  * to select the authentication object.  Return GPG_ERR_NO_PIN if a
5735  * PIN is not required for using the private key KEYIDSTR.  */
5736 static gpg_error_t
5737 do_check_pin (app_t app, ctrl_t ctrl, const char *keyidstr,
5738               gpg_error_t (*pincb)(void*, const char *, char **),
5739               void *pincb_arg)
5740 {
5741   gpg_error_t err;
5742   prkdf_object_t prkdf;    /* The private key object. */
5743   aodf_object_t aodf;      /* The associated authentication object. */
5744
5745   (void)ctrl;
5746
5747   if (!keyidstr || !*keyidstr)
5748     return gpg_error (GPG_ERR_INV_VALUE);
5749
5750   err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5751   if (err
5752       && gpg_err_code (err) != GPG_ERR_INV_ID
5753       && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
5754     return err;
5755
5756   if (err) /* Not found or invalid - assume it is the label.  */
5757     {
5758       prkdf = NULL;
5759       for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5760         if (aodf->label && !ascii_strcasecmp (aodf->label, keyidstr))
5761           break;
5762       if (!aodf)
5763         return err;  /* Re-use the original error code.  */
5764     }
5765   else /* Find the authentication object to this private key object. */
5766     {
5767       if (!prkdf->authid)
5768         {
5769           log_error ("p15: no authentication object defined for %s\n",
5770                      keyidstr);
5771           return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
5772         }
5773       for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5774         if (aodf->objidlen == prkdf->authidlen
5775             && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
5776           break;
5777       if (!aodf) /* None found.  */
5778         return gpg_error (GPG_ERR_NO_PIN);
5779     }
5780
5781   err = prepare_verify_pin (app, keyidstr, prkdf, aodf);
5782   if (!err)
5783     err = verify_pin (app, pincb, pincb_arg, prkdf, aodf);
5784
5785   return err;
5786 }
5787
5788
5789 /* Process the various keygrip based info requests.  */
5790 static gpg_error_t
5791 do_with_keygrip (app_t app, ctrl_t ctrl, int action,
5792                  const char *want_keygripstr, int capability)
5793 {
5794   gpg_error_t err;
5795   char *serialno = NULL;
5796   int as_data = 0;
5797   prkdf_object_t prkdf;
5798
5799   /* First a quick check for valid parameters.  */
5800   switch (action)
5801     {
5802     case KEYGRIP_ACTION_LOOKUP:
5803       if (!want_keygripstr)
5804         {
5805           err = gpg_error (GPG_ERR_NOT_FOUND);
5806           goto leave;
5807         }
5808       break;
5809     case KEYGRIP_ACTION_SEND_DATA:
5810       as_data = 1;
5811       break;
5812     case KEYGRIP_ACTION_WRITE_STATUS:
5813       break;
5814     default:
5815       err = gpg_error (GPG_ERR_INV_ARG);
5816       goto leave;
5817     }
5818
5819   /* Allocate the s/n string if needed.  */
5820   if (action != KEYGRIP_ACTION_LOOKUP)
5821     {
5822       serialno = app_get_serialno (app);
5823       if (!serialno)
5824         {
5825           err = gpg_error_from_syserror ();
5826           goto leave;
5827         }
5828     }
5829
5830   for (prkdf = app->app_local->private_key_info;
5831        prkdf; prkdf = prkdf->next)
5832     {
5833       if (keygrip_from_prkdf (app, prkdf))
5834         continue;
5835
5836       if (action == KEYGRIP_ACTION_LOOKUP)
5837         {
5838           if (!strcmp (prkdf->keygrip, want_keygripstr))
5839             {
5840               err = 0; /* Found */
5841               goto leave;
5842             }
5843         }
5844       else if (!want_keygripstr || !strcmp (prkdf->keygrip, want_keygripstr))
5845         {
5846           char *keyref;
5847
5848           if (capability == GCRY_PK_USAGE_SIGN)
5849             {
5850               if (!(prkdf->usageflags.sign || prkdf->usageflags.sign_recover
5851                     || prkdf->usageflags.non_repudiation))
5852                 continue;
5853             }
5854           else if (capability == GCRY_PK_USAGE_ENCR)
5855             {
5856               if (!(prkdf->usageflags.decrypt || prkdf->usageflags.unwrap))
5857                 continue;
5858             }
5859           else if (capability == GCRY_PK_USAGE_AUTH)
5860             {
5861               if (!(prkdf->usageflags.sign || prkdf->usageflags.sign_recover))
5862                 continue;
5863             }
5864
5865           keyref = keyref_from_prkdf (app, prkdf);
5866           if (!keyref)
5867             {
5868               err = gpg_error_from_syserror ();
5869               goto leave;
5870             }
5871
5872           send_keyinfo (ctrl, as_data, prkdf->keygrip, serialno, keyref);
5873           xfree (keyref);
5874           if (want_keygripstr)
5875             {
5876               err = 0; /* Found */
5877               goto leave;
5878             }
5879         }
5880     }
5881
5882   /* Return an error so that the dispatcher keeps on looping over the
5883    * other applications.  For clarity we use a different error code
5884    * when listing all keys.  Note that in lookup mode WANT_KEYGRIPSTR
5885    * is not NULL.  */
5886   if (!want_keygripstr)
5887     err = gpg_error (GPG_ERR_TRUE);
5888   else
5889     err = gpg_error (GPG_ERR_NOT_FOUND);
5890
5891  leave:
5892   xfree (serialno);
5893   return err;
5894 }
5895
5896
5897 \f
5898 /* Assume that EF(DIR) has been selected.  Read its content and figure
5899    out the home EF of pkcs#15.  Return that home DF or 0 if not found
5900    and the value at the address of BELPIC indicates whether it was
5901    found by the belpic aid. */
5902 static unsigned short
5903 read_home_df (int slot, int *r_belpic)
5904 {
5905   gpg_error_t err;
5906   unsigned char *buffer;
5907   const unsigned char *p, *pp;
5908   size_t buflen, n, nn;
5909   unsigned short result = 0;
5910
5911   *r_belpic = 0;
5912
5913   err = iso7816_read_binary (slot, 0, 0, &buffer, &buflen);
5914   if (err)
5915     {
5916       log_error ("p15: error reading EF(DIR): %s\n", gpg_strerror (err));
5917       return 0;
5918     }
5919
5920   /* FIXME: We need to scan all records. */
5921   p = find_tlv (buffer, buflen, 0x61, &n);
5922   if (p && n)
5923     {
5924       pp = find_tlv (p, n, 0x4f, &nn);
5925       if (pp && ((nn == sizeof pkcs15_aid && !memcmp (pp, pkcs15_aid, nn))
5926                  || (*r_belpic = (nn == sizeof pkcs15be_aid
5927                                   && !memcmp (pp, pkcs15be_aid, nn)))))
5928         {
5929           pp = find_tlv (p, n, 0x50, &nn);
5930           if (pp && opt.verbose)
5931             log_info ("p15: application label from EF(DIR) is '%.*s'\n",
5932                       (int)nn, pp);
5933           pp = find_tlv (p, n, 0x51, &nn);
5934           if (pp && nn == 4 && *pp == 0x3f && !pp[1])
5935             {
5936               result = ((pp[2] << 8) | pp[3]);
5937               if (opt.verbose)
5938                 log_info ("p15: application directory is 0x%04hX\n", result);
5939             }
5940         }
5941     }
5942   xfree (buffer);
5943   return result;
5944 }
5945
5946
5947 /*
5948    Select the PKCS#15 application on the card in SLOT.
5949  */
5950 gpg_error_t
5951 app_select_p15 (app_t app)
5952 {
5953   int slot = app_get_slot (app);
5954   int rc;
5955   unsigned short def_home_df = 0;
5956   card_type_t card_type = CARD_TYPE_UNKNOWN;
5957   int direct = 0;
5958   int is_belpic = 0;
5959   unsigned char *fci = NULL;
5960   size_t fcilen;
5961
5962   rc = iso7816_select_application_ext (slot, pkcs15_aid, sizeof pkcs15_aid, 1,
5963                                        &fci, &fcilen);
5964   if (rc)
5965     { /* Not found: Try to locate it from 2F00.  We use direct path
5966          selection here because it seems that the Belgian eID card
5967          does only allow for that.  Many other cards supports this
5968          selection method too.  Note, that we don't use
5969          select_application above for the Belgian card - the call
5970          works but it seems that it does not switch to the correct DF.
5971          Using the 2f02 just works. */
5972       unsigned short path[1] = { 0x2f00 };
5973
5974       rc = iso7816_select_path (slot, path, 1, 0);
5975       if (!rc)
5976         {
5977           direct = 1;
5978           def_home_df = read_home_df (slot, &is_belpic);
5979           if (def_home_df)
5980             {
5981               path[0] = def_home_df;
5982               rc = iso7816_select_path (slot, path, 1, 0);
5983             }
5984         }
5985     }
5986   if (rc)
5987     { /* Still not found:  Try the default DF. */
5988       def_home_df = DEFAULT_HOME_DF;
5989       rc = iso7816_select_file (slot, def_home_df, 1);
5990     }
5991   if (!rc)
5992     {
5993       /* Determine the type of the card.  The general case is to look
5994          it up from the ATR table.  For the Belgian eID card we know
5995          it instantly from the AID. */
5996       if (is_belpic)
5997         {
5998           card_type = CARD_TYPE_BELPIC;
5999         }
6000       else
6001         {
6002           unsigned char *atr;
6003           size_t atrlen;
6004           int i;
6005
6006           atr = apdu_get_atr (app_get_slot (app), &atrlen);
6007           if (!atr)
6008             rc = gpg_error (GPG_ERR_INV_CARD);
6009           else
6010             {
6011               for (i=0; card_atr_list[i].atrlen; i++)
6012                 if (card_atr_list[i].atrlen == atrlen
6013                     && !memcmp (card_atr_list[i].atr, atr, atrlen))
6014                   {
6015                     card_type = card_atr_list[i].type;
6016                     break;
6017                   }
6018               xfree (atr);
6019             }
6020         }
6021     }
6022   if (!rc)
6023     {
6024       app->apptype = APPTYPE_P15;
6025
6026       app->app_local = xtrycalloc (1, sizeof *app->app_local);
6027       if (!app->app_local)
6028         {
6029           rc = gpg_error_from_syserror ();
6030           goto leave;
6031         }
6032
6033       /* Set the home DF from the FCI returned by the select.  */
6034       if (!def_home_df && fci)
6035         {
6036           const unsigned char *s;
6037           size_t n;
6038
6039           s = find_tlv (fci, fcilen, 0x83, &n);
6040           if (s && n == 2)
6041             def_home_df = buf16_to_ushort (s);
6042           else
6043             log_error ("p15: select(AID) did not return the DF\n");
6044         }
6045       app->app_local->home_df = def_home_df;
6046
6047       /* Store the card type.  FIXME: We might want to put this into
6048          the common APP structure. */
6049       app->app_local->card_type = card_type;
6050
6051       app->app_local->card_product = CARD_PRODUCT_UNKNOWN;
6052
6053       /* Store whether we may and should use direct path selection. */
6054       switch (card_type)
6055         {
6056         case CARD_TYPE_CARDOS_50:
6057         case CARD_TYPE_CARDOS_53:
6058           direct = 1;
6059           break;
6060         default:
6061           /* Use whatever has been determined above.  */
6062           break;
6063         }
6064       app->app_local->direct_path_selection = direct;
6065
6066       /* Read basic information and thus check whether this is a real
6067          card.  */
6068       rc = read_p15_info (app);
6069       if (rc)
6070         goto leave;
6071
6072       /* Special serial number munging.  We need to check for a German
6073          prototype card right here because we need to access to
6074          EF(TokenInfo).  We mark such a serial number by the using a
6075          prefix of FF0100. */
6076       if (APP_CARD(app)->serialnolen == 12
6077           && !memcmp (APP_CARD(app)->serialno,
6078                       "\xD2\x76\0\0\0\0\0\0\0\0\0\0", 12))
6079         {
6080           /* This is a German card with a silly serial number.  Try to get
6081              the serial number from the EF(TokenInfo). . */
6082           unsigned char *p;
6083
6084           /* FIXME: actually get it from EF(TokenInfo). */
6085
6086           p = xtrymalloc (3 + APP_CARD(app)->serialnolen);
6087           if (!p)
6088             rc = gpg_error (gpg_err_code_from_errno (errno));
6089           else
6090             {
6091               memcpy (p, "\xff\x01", 3);
6092               memcpy (p+3, APP_CARD(app)->serialno, APP_CARD(app)->serialnolen);
6093               APP_CARD(app)->serialnolen += 3;
6094               xfree (APP_CARD(app)->serialno);
6095               APP_CARD(app)->serialno = p;
6096             }
6097         }
6098
6099       app->fnc.deinit = do_deinit;
6100       app->fnc.prep_reselect = NULL;
6101       app->fnc.reselect = NULL;
6102       app->fnc.learn_status = do_learn_status;
6103       app->fnc.readcert = do_readcert;
6104       app->fnc.getattr = do_getattr;
6105       app->fnc.setattr = NULL;
6106       app->fnc.genkey = NULL;
6107       app->fnc.sign = do_sign;
6108       app->fnc.auth = do_auth;
6109       app->fnc.decipher = do_decipher;
6110       app->fnc.change_pin = NULL;
6111       app->fnc.check_pin = do_check_pin;
6112       app->fnc.with_keygrip = do_with_keygrip;
6113
6114     leave:
6115       if (rc)
6116         do_deinit (app);
6117    }
6118
6119   xfree (fci);
6120   return rc;
6121 }