Imported Upstream version 2.1.21
[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  *
4  * This file is part of GnuPG.
5  *
6  * GnuPG is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * GnuPG is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see <https://www.gnu.org/licenses/>.
18  */
19
20 /* Information pertaining to the BELPIC developer card samples:
21
22        Unblock PUK: "222222111111"
23        Reset PIN:   "333333111111")
24
25    e.g. the APDUs 00:20:00:02:08:2C:33:33:33:11:11:11:FF
26               and 00:24:01:01:08:24:12:34:FF:FF:FF:FF:FF
27    should change the PIN into 1234.
28 */
29
30 #include <config.h>
31 #include <errno.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <assert.h>
36 #include <time.h>
37
38 #include "scdaemon.h"
39
40 #include "iso7816.h"
41 #include "app-common.h"
42 #include "../common/tlv.h"
43 #include "apdu.h" /* fixme: we should move the card detection to a
44                      separate file */
45
46 /* Types of cards we know and which needs special treatment. */
47 typedef enum
48   {
49     CARD_TYPE_UNKNOWN,
50     CARD_TYPE_TCOS,
51     CARD_TYPE_MICARDO,
52     CARD_TYPE_BELPIC   /* Belgian eID card specs. */
53   }
54 card_type_t;
55
56 /* A list card types with ATRs noticed with these cards. */
57 #define X(a) ((unsigned char const *)(a))
58 static struct
59 {
60   size_t atrlen;
61   unsigned char const *atr;
62   card_type_t type;
63 } card_atr_list[] = {
64   { 19, X("\x3B\xBA\x13\x00\x81\x31\x86\x5D\x00\x64\x05\x0A\x02\x01\x31\x80"
65           "\x90\x00\x8B"),
66     CARD_TYPE_TCOS },  /* SLE44 */
67   { 19, X("\x3B\xBA\x14\x00\x81\x31\x86\x5D\x00\x64\x05\x14\x02\x02\x31\x80"
68           "\x90\x00\x91"),
69     CARD_TYPE_TCOS }, /* SLE66S */
70   { 19, X("\x3B\xBA\x96\x00\x81\x31\x86\x5D\x00\x64\x05\x60\x02\x03\x31\x80"
71           "\x90\x00\x66"),
72     CARD_TYPE_TCOS }, /* SLE66P */
73   { 27, X("\x3B\xFF\x94\x00\xFF\x80\xB1\xFE\x45\x1F\x03\x00\x68\xD2\x76\x00"
74           "\x00\x28\xFF\x05\x1E\x31\x80\x00\x90\x00\x23"),
75     CARD_TYPE_MICARDO }, /* German BMI card */
76   { 19, X("\x3B\x6F\x00\xFF\x00\x68\xD2\x76\x00\x00\x28\xFF\x05\x1E\x31\x80"
77           "\x00\x90\x00"),
78     CARD_TYPE_MICARDO }, /* German BMI card (ATR due to reader problem) */
79   { 26, X("\x3B\xFE\x94\x00\xFF\x80\xB1\xFA\x45\x1F\x03\x45\x73\x74\x45\x49"
80           "\x44\x20\x76\x65\x72\x20\x31\x2E\x30\x43"),
81     CARD_TYPE_MICARDO }, /* EstEID (Estonian Big Brother card) */
82
83   { 0 }
84 };
85 #undef X
86
87
88 /* The AID of PKCS15. */
89 static char const pkcs15_aid[] = { 0xA0, 0, 0, 0, 0x63,
90                                    0x50, 0x4B, 0x43, 0x53, 0x2D, 0x31, 0x35 };
91
92 /* The Belgian eID variant - they didn't understood why a shared AID
93    is useful for a standard.  Oh well. */
94 static char const pkcs15be_aid[] = { 0xA0, 0, 0, 0x01, 0x77,
95                                    0x50, 0x4B, 0x43, 0x53, 0x2D, 0x31, 0x35 };
96
97
98 /* The PIN types as defined in pkcs#15 v1.1 */
99 typedef enum
100   {
101     PIN_TYPE_BCD = 0,
102     PIN_TYPE_ASCII_NUMERIC = 1,
103     PIN_TYPE_UTF8 = 2,
104     PIN_TYPE_HALF_NIBBLE_BCD = 3,
105     PIN_TYPE_ISO9564_1 = 4
106   } pin_type_t;
107
108
109 /* A bit array with for the key usage flags from the
110    commonKeyAttributes. */
111 struct keyusage_flags_s
112 {
113     unsigned int encrypt: 1;
114     unsigned int decrypt: 1;
115     unsigned int sign: 1;
116     unsigned int sign_recover: 1;
117     unsigned int wrap: 1;
118     unsigned int unwrap: 1;
119     unsigned int verify: 1;
120     unsigned int verify_recover: 1;
121     unsigned int derive: 1;
122     unsigned int non_repudiation: 1;
123 };
124 typedef struct keyusage_flags_s keyusage_flags_t;
125
126
127
128 /* This is an object to store information about a Certificate
129    Directory File (CDF) in a format suitable for further processing by
130    us. To keep memory management, simple we use a linked list of
131    items; i.e. one such object represents one certificate and the list
132    the entire CDF. */
133 struct cdf_object_s
134 {
135   /* Link to next item when used in a linked list. */
136   struct cdf_object_s *next;
137
138   /* Length and allocated buffer with the Id of this object. */
139   size_t objidlen;
140   unsigned char *objid;
141
142   /* To avoid reading a certificate more than once, we cache it in an
143      allocated memory IMAGE of IMAGELEN. */
144   size_t imagelen;
145   unsigned char *image;
146
147   /* Set to true if a length and offset is available. */
148   int have_off;
149   /* The offset and length of the object.  They are only valid if
150      HAVE_OFF is true and set to 0 if HAVE_OFF is false. */
151   unsigned long off, len;
152
153   /* The length of the path as given in the CDF and the path itself.
154      path[0] is the top DF (usually 0x3f00). The path will never be
155      empty. */
156   size_t pathlen;
157   unsigned short path[1];
158 };
159 typedef struct cdf_object_s *cdf_object_t;
160
161
162 /* This is an object to store information about a Private Key
163    Directory File (PrKDF) in a format suitable for further processing
164    by us. To keep memory management, simple we use a linked list of
165    items; i.e. one such object represents one certificate and the list
166    the entire PrKDF. */
167 struct prkdf_object_s
168 {
169   /* Link to next item when used in a linked list. */
170   struct prkdf_object_s *next;
171
172   /* Length and allocated buffer with the Id of this object. */
173   size_t objidlen;
174   unsigned char *objid;
175
176   /* Length and allocated buffer with the authId of this object or
177      NULL if no authID is known. */
178   size_t authidlen;
179   unsigned char *authid;
180
181   /* The key's usage flags. */
182   keyusage_flags_t usageflags;
183
184   /* The keyReference and a flag telling whether it is valid. */
185   unsigned long key_reference;
186   int key_reference_valid;
187
188   /* Set to true if a length and offset is available. */
189   int have_off;
190   /* The offset and length of the object.  They are only valid if
191      HAVE_OFF is true and set to 0 if HAVE_OFF is false. */
192   unsigned long off, len;
193
194   /* The length of the path as given in the PrKDF and the path itself.
195      path[0] is the top DF (usually 0x3f00). */
196   size_t pathlen;
197   unsigned short path[1];
198 };
199 typedef struct prkdf_object_s *prkdf_object_t;
200
201
202 /* This is an object to store information about a Authentication
203    Object Directory File (AODF) in a format suitable for further
204    processing by us. To keep memory management, simple we use a linked
205    list of items; i.e. one such object represents one authentication
206    object and the list the entire AOKDF. */
207 struct aodf_object_s
208 {
209   /* Link to next item when used in a linked list. */
210   struct aodf_object_s *next;
211
212   /* Length and allocated buffer with the Id of this object. */
213   size_t objidlen;
214   unsigned char *objid;
215
216   /* Length and allocated buffer with the authId of this object or
217      NULL if no authID is known. */
218   size_t authidlen;
219   unsigned char *authid;
220
221   /* The PIN Flags. */
222   struct
223   {
224     unsigned int case_sensitive: 1;
225     unsigned int local: 1;
226     unsigned int change_disabled: 1;
227     unsigned int unblock_disabled: 1;
228     unsigned int initialized: 1;
229     unsigned int needs_padding: 1;
230     unsigned int unblocking_pin: 1;
231     unsigned int so_pin: 1;
232     unsigned int disable_allowed: 1;
233     unsigned int integrity_protected: 1;
234     unsigned int confidentiality_protected: 1;
235     unsigned int exchange_ref_data: 1;
236   } pinflags;
237
238   /* The PIN Type. */
239   pin_type_t pintype;
240
241   /* The minimum length of a PIN. */
242   unsigned long min_length;
243
244   /* The stored length of a PIN. */
245   unsigned long stored_length;
246
247   /* The maximum length of a PIN and a flag telling whether it is valid. */
248   unsigned long max_length;
249   int max_length_valid;
250
251   /* The pinReference and a flag telling whether it is valid. */
252   unsigned long pin_reference;
253   int pin_reference_valid;
254
255   /* The padChar and a flag telling whether it is valid. */
256   char pad_char;
257   int pad_char_valid;
258
259
260   /* Set to true if a length and offset is available. */
261   int have_off;
262   /* The offset and length of the object.  They are only valid if
263      HAVE_OFF is true and set to 0 if HAVE_OFF is false. */
264   unsigned long off, len;
265
266   /* The length of the path as given in the Aodf and the path itself.
267      path[0] is the top DF (usually 0x3f00). PATH is optional and thus
268      may be NULL.  Malloced.*/
269   size_t pathlen;
270   unsigned short *path;
271 };
272 typedef struct aodf_object_s *aodf_object_t;
273
274
275 /* Context local to this application. */
276 struct app_local_s
277 {
278   /* The home DF. Note, that we don't yet support a multilevel
279      hierarchy.  Thus we assume this is directly below the MF.  */
280   unsigned short home_df;
281
282   /* The type of the card. */
283   card_type_t card_type;
284
285   /* Flag indicating whether we may use direct path selection. */
286   int direct_path_selection;
287
288   /* Structure with the EFIDs of the objects described in the ODF
289      file. */
290   struct
291   {
292     unsigned short private_keys;
293     unsigned short public_keys;
294     unsigned short trusted_public_keys;
295     unsigned short secret_keys;
296     unsigned short certificates;
297     unsigned short trusted_certificates;
298     unsigned short useful_certificates;
299     unsigned short data_objects;
300     unsigned short auth_objects;
301   } odf;
302
303   /* The PKCS#15 serialnumber from EF(TokeiNFo) or NULL.  Malloced. */
304   unsigned char *serialno;
305   size_t serialnolen;
306
307   /* Information on all certificates. */
308   cdf_object_t certificate_info;
309   /* Information on all trusted certificates. */
310   cdf_object_t trusted_certificate_info;
311   /* Information on all useful certificates. */
312   cdf_object_t useful_certificate_info;
313
314   /* Information on all private keys. */
315   prkdf_object_t private_key_info;
316
317   /* Information on all authentication objects. */
318   aodf_object_t auth_object_info;
319
320 };
321
322
323 /*** Local prototypes.  ***/
324 static gpg_error_t readcert_by_cdf (app_t app, cdf_object_t cdf,
325                                     unsigned char **r_cert, size_t *r_certlen);
326
327
328
329 /* Release the CDF object A  */
330 static void
331 release_cdflist (cdf_object_t a)
332 {
333   while (a)
334     {
335       cdf_object_t tmp = a->next;
336       xfree (a->image);
337       xfree (a->objid);
338       xfree (a);
339       a = tmp;
340     }
341 }
342
343 /* Release the PrKDF object A.  */
344 static void
345 release_prkdflist (prkdf_object_t a)
346 {
347   while (a)
348     {
349       prkdf_object_t tmp = a->next;
350       xfree (a->objid);
351       xfree (a->authid);
352       xfree (a);
353       a = tmp;
354     }
355 }
356
357 /* Release just one aodf object. */
358 void
359 release_aodf_object (aodf_object_t a)
360 {
361   if (a)
362     {
363       xfree (a->objid);
364       xfree (a->authid);
365       xfree (a->path);
366       xfree (a);
367     }
368 }
369
370 /* Release the AODF list A.  */
371 static void
372 release_aodflist (aodf_object_t a)
373 {
374   while (a)
375     {
376       aodf_object_t tmp = a->next;
377       release_aodf_object (a);
378       a = tmp;
379     }
380 }
381
382
383 /* Release all local resources.  */
384 static void
385 do_deinit (app_t app)
386 {
387   if (app && app->app_local)
388     {
389       release_cdflist (app->app_local->certificate_info);
390       release_cdflist (app->app_local->trusted_certificate_info);
391       release_cdflist (app->app_local->useful_certificate_info);
392       release_prkdflist (app->app_local->private_key_info);
393       release_aodflist (app->app_local->auth_object_info);
394       xfree (app->app_local->serialno);
395       xfree (app->app_local);
396       app->app_local = NULL;
397     }
398 }
399
400
401
402 /* Do a select and a read for the file with EFID.  EFID_DESC is a
403    desctription of the EF to be used with error messages.  On success
404    BUFFER and BUFLEN contain the entire content of the EF.  The caller
405    must free BUFFER only on success. */
406 static gpg_error_t
407 select_and_read_binary (int slot, unsigned short efid, const char *efid_desc,
408                         unsigned char **buffer, size_t *buflen)
409 {
410   gpg_error_t err;
411
412   err = iso7816_select_file (slot, efid, 0);
413   if (err)
414     {
415       log_error ("error selecting %s (0x%04X): %s\n",
416                  efid_desc, efid, gpg_strerror (err));
417       return err;
418     }
419   err = iso7816_read_binary (slot, 0, 0, buffer, buflen);
420   if (err)
421     {
422       log_error ("error reading %s (0x%04X): %s\n",
423                  efid_desc, efid, gpg_strerror (err));
424       return err;
425     }
426   return 0;
427 }
428
429
430 /* This function calls select file to read a file using a complete
431    path which may or may not start at the master file (MF). */
432 static gpg_error_t
433 select_ef_by_path (app_t app, const unsigned short *path, size_t pathlen)
434 {
435   gpg_error_t err;
436   int i, j;
437
438   if (!pathlen)
439     return gpg_error (GPG_ERR_INV_VALUE);
440
441   if (pathlen && *path != 0x3f00 )
442     log_debug ("WARNING: relative path selection not yet implemented\n");
443
444   if (app->app_local->direct_path_selection)
445     {
446       err = iso7816_select_path (app->slot, path+1, pathlen-1);
447       if (err)
448         {
449           log_error ("error selecting path ");
450           for (j=0; j < pathlen; j++)
451             log_printf ("%04hX", path[j]);
452           log_printf (": %s\n", gpg_strerror (err));
453           return err;
454         }
455     }
456   else
457     {
458       /* FIXME: Need code to remember the last PATH so that we can decide
459          what select commands to send in case the path does not start off
460          with 3F00.  We might also want to use direct path selection if
461          supported by the card. */
462       for (i=0; i < pathlen; i++)
463         {
464           err = iso7816_select_file (app->slot, path[i], !(i+1 == pathlen));
465           if (err)
466             {
467               log_error ("error selecting part %d from path ", i);
468               for (j=0; j < pathlen; j++)
469                 log_printf ("%04hX", path[j]);
470               log_printf (": %s\n", gpg_strerror (err));
471               return err;
472             }
473         }
474     }
475   return 0;
476 }
477
478 /* Parse a cert Id string (or a key Id string) and return the binary
479    object Id string in a newly allocated buffer stored at R_OBJID and
480    R_OBJIDLEN.  On Error NULL will be stored there and an error code
481    returned. On success caller needs to free the buffer at R_OBJID. */
482 static gpg_error_t
483 parse_certid (app_t app, const char *certid,
484               unsigned char **r_objid, size_t *r_objidlen)
485 {
486   char tmpbuf[10];
487   const char *s;
488   size_t objidlen;
489   unsigned char *objid;
490   int i;
491
492   *r_objid = NULL;
493   *r_objidlen = 0;
494
495   if (app->app_local->home_df)
496     snprintf (tmpbuf, sizeof tmpbuf,
497               "P15-%04X.", (unsigned int)(app->app_local->home_df & 0xffff));
498   else
499     strcpy (tmpbuf, "P15.");
500   if (strncmp (certid, tmpbuf, strlen (tmpbuf)) )
501     {
502       if (!strncmp (certid, "P15.", 4)
503           || (!strncmp (certid, "P15-", 4)
504               && hexdigitp (certid+4)
505               && hexdigitp (certid+5)
506               && hexdigitp (certid+6)
507               && hexdigitp (certid+7)
508               && certid[8] == '.'))
509         return gpg_error (GPG_ERR_NOT_FOUND);
510       return gpg_error (GPG_ERR_INV_ID);
511     }
512   certid += strlen (tmpbuf);
513
514   for (s=certid, objidlen=0; hexdigitp (s); s++, objidlen++)
515     ;
516   if (*s || !objidlen || (objidlen%2))
517     return gpg_error (GPG_ERR_INV_ID);
518   objidlen /= 2;
519   objid = xtrymalloc (objidlen);
520   if (!objid)
521     return gpg_error_from_syserror ();
522   for (s=certid, i=0; i < objidlen; i++, s+=2)
523     objid[i] = xtoi_2 (s);
524   *r_objid = objid;
525   *r_objidlen = objidlen;
526   return 0;
527 }
528
529
530 /* Find a certificate object by the certificate ID CERTID and store a
531    pointer to it at R_CDF. */
532 static gpg_error_t
533 cdf_object_from_certid (app_t app, const char *certid, cdf_object_t *r_cdf)
534 {
535   gpg_error_t err;
536   size_t objidlen;
537   unsigned char *objid;
538   cdf_object_t cdf;
539
540   err = parse_certid (app, certid, &objid, &objidlen);
541   if (err)
542     return err;
543
544   for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
545     if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
546       break;
547   if (!cdf)
548     for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
549       if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
550         break;
551   if (!cdf)
552     for (cdf = app->app_local->useful_certificate_info; cdf; cdf = cdf->next)
553       if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
554         break;
555   xfree (objid);
556   if (!cdf)
557     return gpg_error (GPG_ERR_NOT_FOUND);
558   *r_cdf = cdf;
559   return 0;
560 }
561
562
563 /* Find a private key object by the key Id string KEYIDSTR and store a
564    pointer to it at R_PRKDF. */
565 static gpg_error_t
566 prkdf_object_from_keyidstr (app_t app, const char *keyidstr,
567                             prkdf_object_t *r_prkdf)
568 {
569   gpg_error_t err;
570   size_t objidlen;
571   unsigned char *objid;
572   prkdf_object_t prkdf;
573
574   err = parse_certid (app, keyidstr, &objid, &objidlen);
575   if (err)
576     return err;
577
578   for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
579     if (prkdf->objidlen == objidlen && !memcmp (prkdf->objid, objid, objidlen))
580       break;
581   xfree (objid);
582   if (!prkdf)
583     return gpg_error (GPG_ERR_NOT_FOUND);
584   *r_prkdf = prkdf;
585   return 0;
586 }
587
588
589
590 \f
591 /* Read and parse the Object Directory File and store away the
592    pointers. ODF_FID shall contain the FID of the ODF.
593
594    Example of such a file:
595
596    A0 06 30 04 04 02 60 34  = Private Keys
597    A4 06 30 04 04 02 60 35  = Certificates
598    A5 06 30 04 04 02 60 36  = TrustedCertificates
599    A7 06 30 04 04 02 60 37  = DataObjects
600    A8 06 30 04 04 02 60 38  = AuthObjects
601
602    These are all PathOrObjects using the path CHOICE element.  The
603    paths are octet strings of length 2.  Using this Path CHOICE
604    element is recommended, so we only implement that for now.
605 */
606 static gpg_error_t
607 read_ef_odf (app_t app, unsigned short odf_fid)
608 {
609   gpg_error_t err;
610   unsigned char *buffer, *p;
611   size_t buflen;
612   unsigned short value;
613   size_t offset;
614
615   err = select_and_read_binary (app->slot, odf_fid, "ODF", &buffer, &buflen);
616   if (err)
617     return err;
618
619   if (buflen < 8)
620     {
621       log_error ("error: ODF too short\n");
622       xfree (buffer);
623       return gpg_error (GPG_ERR_INV_OBJ);
624     }
625   p = buffer;
626   while (buflen && *p && *p != 0xff)
627     {
628       if ( buflen >= 8
629            && (p[0] & 0xf0) == 0xA0
630            && !memcmp (p+1, "\x06\x30\x04\x04\x02", 5) )
631         {
632           offset = 6;
633         }
634       else if ( buflen >= 12
635                 && (p[0] & 0xf0) == 0xA0
636                 && !memcmp (p+1, "\x0a\x30\x08\x04\x06\x3F\x00", 7)
637                 && app->app_local->home_df == ((p[8]<<8)|p[9]) )
638         {
639           /* We only allow a full path if all files are at the same
640              level and below the home directory.  The extend this we
641              would need to make use of new data type capable of
642              keeping a full path. */
643           offset = 10;
644         }
645       else
646         {
647           log_error ("ODF format is not supported by us\n");
648           xfree (buffer);
649           return gpg_error (GPG_ERR_INV_OBJ);
650         }
651       switch ((p[0] & 0x0f))
652         {
653         case 0: value = app->app_local->odf.private_keys; break;
654         case 1: value = app->app_local->odf.public_keys; break;
655         case 2: value = app->app_local->odf.trusted_public_keys; break;
656         case 3: value = app->app_local->odf.secret_keys; break;
657         case 4: value = app->app_local->odf.certificates; break;
658         case 5: value = app->app_local->odf.trusted_certificates; break;
659         case 6: value = app->app_local->odf.useful_certificates; break;
660         case 7: value = app->app_local->odf.data_objects; break;
661         case 8: value = app->app_local->odf.auth_objects; break;
662         default: value = 0; break;
663         }
664       if (value)
665         {
666           log_error ("duplicate object type %d in ODF ignored\n",(p[0]&0x0f));
667           continue;
668         }
669       value = ((p[offset] << 8) | p[offset+1]);
670       switch ((p[0] & 0x0f))
671         {
672         case 0: app->app_local->odf.private_keys = value; break;
673         case 1: app->app_local->odf.public_keys = value; break;
674         case 2: app->app_local->odf.trusted_public_keys = value; break;
675         case 3: app->app_local->odf.secret_keys = value; break;
676         case 4: app->app_local->odf.certificates = value; break;
677         case 5: app->app_local->odf.trusted_certificates = value; break;
678         case 6: app->app_local->odf.useful_certificates = value; break;
679         case 7: app->app_local->odf.data_objects = value; break;
680         case 8: app->app_local->odf.auth_objects = value; break;
681         default:
682           log_error ("unknown object type %d in ODF ignored\n", (p[0]&0x0f));
683         }
684       offset += 2;
685
686       if (buflen < offset)
687         break;
688       p += offset;
689       buflen -= offset;
690     }
691
692   if (buflen)
693     log_info ("warning: %u bytes of garbage detected at end of ODF\n",
694               (unsigned int)buflen);
695
696   xfree (buffer);
697   return 0;
698 }
699
700
701 /* Parse the BIT STRING with the keyUsageFlags from the
702    CommonKeyAttributes. */
703 static gpg_error_t
704 parse_keyusage_flags (const unsigned char *der, size_t derlen,
705                       keyusage_flags_t *usageflags)
706 {
707   unsigned int bits, mask;
708   int i, unused, full;
709
710   memset (usageflags, 0, sizeof *usageflags);
711   if (!derlen)
712     return gpg_error (GPG_ERR_INV_OBJ);
713
714   unused = *der++; derlen--;
715   if ((!derlen && unused) || unused/8 > derlen)
716     return gpg_error (GPG_ERR_ENCODING_PROBLEM);
717   full = derlen - (unused+7)/8;
718   unused %= 8;
719   mask = 0;
720   for (i=1; unused; i <<= 1, unused--)
721     mask |= i;
722
723   /* First octet */
724   if (derlen)
725     {
726       bits = *der++; derlen--;
727       if (full)
728         full--;
729       else
730         {
731           bits &= ~mask;
732           mask = 0;
733         }
734     }
735   else
736     bits = 0;
737   if ((bits & 0x80)) usageflags->encrypt = 1;
738   if ((bits & 0x40)) usageflags->decrypt = 1;
739   if ((bits & 0x20)) usageflags->sign = 1;
740   if ((bits & 0x10)) usageflags->sign_recover = 1;
741   if ((bits & 0x08)) usageflags->wrap = 1;
742   if ((bits & 0x04)) usageflags->unwrap = 1;
743   if ((bits & 0x02)) usageflags->verify = 1;
744   if ((bits & 0x01)) usageflags->verify_recover = 1;
745
746   /* Second octet. */
747   if (derlen)
748     {
749       bits = *der++; derlen--;
750       if (full)
751         full--;
752       else
753         {
754           bits &= ~mask;
755         }
756     }
757   else
758     bits = 0;
759   if ((bits & 0x80)) usageflags->derive = 1;
760   if ((bits & 0x40)) usageflags->non_repudiation = 1;
761
762   return 0;
763 }
764
765 /* Read and  parse the Private Key Directory Files. */
766 /*
767   6034 (privatekeys)
768
769 30 33 30 11 0C 08 53 4B 2E  43 48 2E 44 53 03 02   030...SK.CH.DS..
770 06 80 04 01 07 30 0C 04 01  01 03 03 06 00 40 02   .....0........@.
771 02 00 50 A1 10 30 0E 30 08  04 06 3F 00 40 16 00   ..P..0.0...?.@..
772 50 02 02 04 00 30 33 30 11  0C 08 53 4B 2E 43 48   P....030...SK.CH
773 2E 4B 45 03 02 06 80 04 01  0A 30 0C 04 01 0C 03   .KE.......0.....
774 03 06 44 00 02 02 00 52 A1  10 30 0E 30 08 04 06   ..D....R..0.0...
775 3F 00 40 16 00 52 02 02 04  00 30 34 30 12 0C 09   ?.@..R....040...
776 53 4B 2E 43 48 2E 41 55 54  03 02 06 80 04 01 0A   SK.CH.AUT.......
777 30 0C 04 01 0D 03 03 06 20  00 02 02 00 51 A1 10   0....... ....Q..
778 30 0E 30 08 04 06 3F 00 40  16 00 51 02 02 04 00   0.0...?.@..Q....
779 30 37 30 15 0C 0C 53 4B 2E  43 48 2E 44 53 2D 53   070...SK.CH.DS-S
780 50 58 03 02 06 80 04 01 0A  30 0C 04 01 02 03 03   PX.......0......
781 06 20 00 02 02 00 53 A1 10  30 0E 30 08 04 06 3F   . ....S..0.0...?
782 00 40 16 00 53 02 02 04 00  00 00 00 00 00 00 00   .@..S...........
783 00 00 00 00 00 00 00 00 00  00 00 00 00 00 00 00   ................
784 00 00 00 00 00 00 00 00 00  00 00 00 00 00 00 00   ................
785
786    0 30   51: SEQUENCE {
787    2 30   17:   SEQUENCE { -- commonObjectAttributes
788    4 0C    8:     UTF8String 'SK.CH.DS'
789   14 03    2:     BIT STRING 6 unused bits
790             :       '01'B (bit 0)
791   18 04    1:     OCTET STRING --authid
792             :       07
793             :     }
794   21 30   12:   SEQUENCE { -- commonKeyAttributes
795   23 04    1:     OCTET STRING
796             :       01
797   26 03    3:     BIT STRING 6 unused bits
798             :       '1000000000'B (bit 9)
799   31 02    2:     INTEGER 80  -- keyReference (optional)
800             :     }
801   35 A1   16:   [1] {  -- keyAttributes
802   37 30   14:     SEQUENCE { -- privateRSAKeyAttributes
803   39 30    8:       SEQUENCE { -- objectValue
804   41 04    6:         OCTET STRING --path
805             :           3F 00 40 16 00 50
806             :         }
807   49 02    2:       INTEGER 1024 -- modulus
808             :       }
809             :     }
810             :   }
811
812
813 */
814 static gpg_error_t
815 read_ef_prkdf (app_t app, unsigned short fid, prkdf_object_t *result)
816 {
817   gpg_error_t err;
818   unsigned char *buffer = NULL;
819   size_t buflen;
820   const unsigned char *p;
821   size_t n, objlen, hdrlen;
822   int class, tag, constructed, ndef;
823   prkdf_object_t prkdflist = NULL;
824   int i;
825
826   if (!fid)
827     return gpg_error (GPG_ERR_NO_DATA); /* No private keys. */
828
829   err = select_and_read_binary (app->slot, fid, "PrKDF", &buffer, &buflen);
830   if (err)
831     return err;
832
833   p = buffer;
834   n = buflen;
835
836   /* FIXME: This shares a LOT of code with read_ef_cdf! */
837
838   /* Loop over the records.  We stop as soon as we detect a new record
839      starting with 0x00 or 0xff as these values are commonly used to
840      pad data blocks and are no valid ASN.1 encoding. */
841   while (n && *p && *p != 0xff)
842     {
843       const unsigned char *pp;
844       size_t nn;
845       int where;
846       const char *errstr = NULL;
847       prkdf_object_t prkdf = NULL;
848       unsigned long ul;
849       const unsigned char *objid;
850       size_t objidlen;
851       const unsigned char *authid = NULL;
852       size_t authidlen = 0;
853       keyusage_flags_t usageflags;
854       unsigned long key_reference = 0;
855       int key_reference_valid = 0;
856       const char *s;
857
858       err = parse_ber_header (&p, &n, &class, &tag, &constructed,
859                               &ndef, &objlen, &hdrlen);
860       if (!err && (objlen > n || tag != TAG_SEQUENCE))
861         err = gpg_error (GPG_ERR_INV_OBJ);
862       if (err)
863         {
864           log_error ("error parsing PrKDF record: %s\n", gpg_strerror (err));
865           goto leave;
866         }
867       pp = p;
868       nn = objlen;
869       p += objlen;
870       n -= objlen;
871
872       /* Parse the commonObjectAttributes.  */
873       where = __LINE__;
874       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
875                               &ndef, &objlen, &hdrlen);
876       if (!err && (objlen > nn || tag != TAG_SEQUENCE))
877         err = gpg_error (GPG_ERR_INV_OBJ);
878       if (err)
879         goto parse_error;
880       {
881         const unsigned char *ppp = pp;
882         size_t nnn = objlen;
883
884         pp += objlen;
885         nn -= objlen;
886
887         /* Search the optional AuthId.  We need to skip the optional
888            Label (UTF8STRING) and the optional CommonObjectFlags
889            (BITSTRING). */
890         where = __LINE__;
891         err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
892                                 &ndef, &objlen, &hdrlen);
893         if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
894           err = gpg_error (GPG_ERR_INV_OBJ);
895         if (gpg_err_code (err) == GPG_ERR_EOF)
896           goto no_authid;
897         if (err)
898           goto parse_error;
899         if (tag == TAG_UTF8_STRING)
900           {
901             ppp += objlen; /* Skip the Label. */
902             nnn -= objlen;
903
904             where = __LINE__;
905             err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
906                                     &ndef, &objlen, &hdrlen);
907             if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
908               err = gpg_error (GPG_ERR_INV_OBJ);
909             if (gpg_err_code (err) == GPG_ERR_EOF)
910               goto no_authid;
911             if (err)
912               goto parse_error;
913           }
914         if (tag == TAG_BIT_STRING)
915           {
916             ppp += objlen; /* Skip the CommonObjectFlags.  */
917             nnn -= objlen;
918
919             where = __LINE__;
920             err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
921                                     &ndef, &objlen, &hdrlen);
922             if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
923               err = gpg_error (GPG_ERR_INV_OBJ);
924             if (gpg_err_code (err) == GPG_ERR_EOF)
925               goto no_authid;
926             if (err)
927               goto parse_error;
928           }
929         if (tag == TAG_OCTET_STRING && objlen)
930           {
931             authid = ppp;
932             authidlen = objlen;
933           }
934       no_authid:
935         ;
936       }
937
938       /* Parse the commonKeyAttributes.  */
939       where = __LINE__;
940       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
941                               &ndef, &objlen, &hdrlen);
942       if (!err && (objlen > nn || tag != TAG_SEQUENCE))
943         err = gpg_error (GPG_ERR_INV_OBJ);
944       if (err)
945         goto parse_error;
946       {
947         const unsigned char *ppp = pp;
948         size_t nnn = objlen;
949
950         pp += objlen;
951         nn -= objlen;
952
953         /* Get the Id. */
954         where = __LINE__;
955         err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
956                               &ndef, &objlen, &hdrlen);
957         if (!err && (objlen > nnn
958                      || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
959           err = gpg_error (GPG_ERR_INV_OBJ);
960         if (err)
961           goto parse_error;
962         objid = ppp;
963         objidlen = objlen;
964         ppp += objlen;
965         nnn -= objlen;
966
967         /* Get the KeyUsageFlags. */
968         where = __LINE__;
969         err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
970                               &ndef, &objlen, &hdrlen);
971         if (!err && (objlen > nnn
972                      || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
973           err = gpg_error (GPG_ERR_INV_OBJ);
974         if (err)
975           goto parse_error;
976         err = parse_keyusage_flags (ppp, objlen, &usageflags);
977         if (err)
978           goto parse_error;
979         ppp += objlen;
980         nnn -= objlen;
981
982         /* Find the keyReference */
983         where = __LINE__;
984         err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
985                               &ndef, &objlen, &hdrlen);
986         if (gpg_err_code (err) == GPG_ERR_EOF)
987           goto leave_cki;
988         if (!err && objlen > nnn)
989           err = gpg_error (GPG_ERR_INV_OBJ);
990         if (err)
991           goto parse_error;
992         if (class == CLASS_UNIVERSAL && tag == TAG_BOOLEAN)
993           {
994             /* Skip the native element. */
995             ppp += objlen;
996             nnn -= objlen;
997
998             err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
999                                     &ndef, &objlen, &hdrlen);
1000             if (gpg_err_code (err) == GPG_ERR_EOF)
1001               goto leave_cki;
1002             if (!err && objlen > nnn)
1003               err = gpg_error (GPG_ERR_INV_OBJ);
1004             if (err)
1005               goto parse_error;
1006           }
1007         if (class == CLASS_UNIVERSAL && tag == TAG_BIT_STRING)
1008           {
1009             /* Skip the accessFlags. */
1010             ppp += objlen;
1011             nnn -= objlen;
1012
1013             err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1014                                     &ndef, &objlen, &hdrlen);
1015             if (gpg_err_code (err) == GPG_ERR_EOF)
1016               goto leave_cki;
1017             if (!err && objlen > nnn)
1018               err = gpg_error (GPG_ERR_INV_OBJ);
1019             if (err)
1020               goto parse_error;
1021           }
1022         if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
1023           {
1024             /* Yep, this is the keyReference.  */
1025             for (ul=0; objlen; objlen--)
1026               {
1027                 ul <<= 8;
1028                 ul |= (*ppp++) & 0xff;
1029                 nnn--;
1030             }
1031             key_reference = ul;
1032             key_reference_valid = 1;
1033           }
1034
1035       leave_cki:
1036         ;
1037       }
1038
1039
1040       /* Skip subClassAttributes.  */
1041       where = __LINE__;
1042       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1043                               &ndef, &objlen, &hdrlen);
1044       if (!err && objlen > nn)
1045         err = gpg_error (GPG_ERR_INV_OBJ);
1046       if (err)
1047         goto parse_error;
1048       if (class == CLASS_CONTEXT && tag == 0)
1049         {
1050           pp += objlen;
1051           nn -= objlen;
1052
1053           where = __LINE__;
1054           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1055                                   &ndef, &objlen, &hdrlen);
1056         }
1057       /* Parse the keyAttributes.  */
1058       if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1059         err = gpg_error (GPG_ERR_INV_OBJ);
1060       if (err)
1061         goto parse_error;
1062       nn = objlen;
1063
1064       where = __LINE__;
1065       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1066                               &ndef, &objlen, &hdrlen);
1067       if (!err && objlen > nn)
1068         err = gpg_error (GPG_ERR_INV_OBJ);
1069       if (err)
1070         goto parse_error;
1071       if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
1072         ; /* RSA */
1073       else if (class == CLASS_CONTEXT)
1074         {
1075           switch (tag)
1076             {
1077             case 0: errstr = "EC key objects are not supported"; break;
1078             case 1: errstr = "DH key objects are not supported"; break;
1079             case 2: errstr = "DSA key objects are not supported"; break;
1080             case 3: errstr = "KEA key objects are not supported"; break;
1081             default: errstr = "unknown privateKeyObject"; break;
1082             }
1083           goto parse_error;
1084         }
1085       else
1086         {
1087           err = gpg_error (GPG_ERR_INV_OBJ);
1088           goto parse_error;
1089         }
1090
1091       nn = objlen;
1092
1093       /* Check that the reference is a Path object.  */
1094       where = __LINE__;
1095       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1096                               &ndef, &objlen, &hdrlen);
1097       if (!err && objlen > nn)
1098         err = gpg_error (GPG_ERR_INV_OBJ);
1099       if (err)
1100         goto parse_error;
1101       if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
1102         {
1103           errstr = "unsupported reference type";
1104           goto parse_error;
1105         }
1106       nn = objlen;
1107
1108       /* Parse the Path object. */
1109       where = __LINE__;
1110       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1111                               &ndef, &objlen, &hdrlen);
1112       if (!err && objlen > nn)
1113         err = gpg_error (GPG_ERR_INV_OBJ);
1114       if (err)
1115         goto parse_error;
1116
1117       /* Make sure that the next element is a non zero path and of
1118          even length (FID are two bytes each). */
1119       if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
1120           ||  !objlen || (objlen & 1) )
1121         {
1122           errstr = "invalid path reference";
1123           goto parse_error;
1124         }
1125       /* Create a new PrKDF list item. */
1126       prkdf = xtrycalloc (1, (sizeof *prkdf
1127                               - sizeof(unsigned short)
1128                               + objlen/2 * sizeof(unsigned short)));
1129       if (!prkdf)
1130         {
1131           err = gpg_error_from_syserror ();
1132           goto leave;
1133         }
1134       prkdf->objidlen = objidlen;
1135       prkdf->objid = xtrymalloc (objidlen);
1136       if (!prkdf->objid)
1137         {
1138           err = gpg_error_from_syserror ();
1139           xfree (prkdf);
1140           goto leave;
1141         }
1142       memcpy (prkdf->objid, objid, objidlen);
1143       if (authid)
1144         {
1145           prkdf->authidlen = authidlen;
1146           prkdf->authid = xtrymalloc (authidlen);
1147           if (!prkdf->authid)
1148             {
1149               err = gpg_error_from_syserror ();
1150               xfree (prkdf->objid);
1151               xfree (prkdf);
1152               goto leave;
1153             }
1154           memcpy (prkdf->authid, authid, authidlen);
1155         }
1156
1157       prkdf->pathlen = objlen/2;
1158       for (i=0; i < prkdf->pathlen; i++, pp += 2, nn -= 2)
1159         prkdf->path[i] = ((pp[0] << 8) | pp[1]);
1160
1161       prkdf->usageflags = usageflags;
1162       prkdf->key_reference = key_reference;
1163       prkdf->key_reference_valid = key_reference_valid;
1164
1165       if (nn)
1166         {
1167           /* An index and length follows. */
1168           prkdf->have_off = 1;
1169           where = __LINE__;
1170           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1171                                   &ndef, &objlen, &hdrlen);
1172           if (!err && (objlen > nn
1173                        || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1174             err = gpg_error (GPG_ERR_INV_OBJ);
1175           if (err)
1176             goto parse_error;
1177
1178           for (ul=0; objlen; objlen--)
1179             {
1180               ul <<= 8;
1181               ul |= (*pp++) & 0xff;
1182               nn--;
1183             }
1184           prkdf->off = ul;
1185
1186           where = __LINE__;
1187           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1188                                   &ndef, &objlen, &hdrlen);
1189           if (!err && (objlen > nn
1190                        || class != CLASS_CONTEXT || tag != 0))
1191             err = gpg_error (GPG_ERR_INV_OBJ);
1192           if (err)
1193             goto parse_error;
1194
1195           for (ul=0; objlen; objlen--)
1196             {
1197               ul <<= 8;
1198               ul |= (*pp++) & 0xff;
1199               nn--;
1200             }
1201           prkdf->len = ul;
1202         }
1203
1204
1205       log_debug ("PrKDF %04hX: id=", fid);
1206       for (i=0; i < prkdf->objidlen; i++)
1207         log_printf ("%02X", prkdf->objid[i]);
1208       log_printf (" path=");
1209       for (i=0; i < prkdf->pathlen; i++)
1210         log_printf ("%04hX", prkdf->path[i]);
1211       if (prkdf->have_off)
1212         log_printf ("[%lu/%lu]", prkdf->off, prkdf->len);
1213       if (prkdf->authid)
1214         {
1215           log_printf (" authid=");
1216           for (i=0; i < prkdf->authidlen; i++)
1217             log_printf ("%02X", prkdf->authid[i]);
1218         }
1219       if (prkdf->key_reference_valid)
1220         log_printf (" keyref=0x%02lX", prkdf->key_reference);
1221       log_printf (" usage=");
1222       s = "";
1223       if (prkdf->usageflags.encrypt) log_printf ("%sencrypt", s), s = ",";
1224       if (prkdf->usageflags.decrypt) log_printf ("%sdecrypt", s), s = ",";
1225       if (prkdf->usageflags.sign   ) log_printf ("%ssign", s), s = ",";
1226       if (prkdf->usageflags.sign_recover)
1227         log_printf ("%ssign_recover", s), s = ",";
1228       if (prkdf->usageflags.wrap   ) log_printf ("%swrap", s), s = ",";
1229       if (prkdf->usageflags.unwrap ) log_printf ("%sunwrap", s), s = ",";
1230       if (prkdf->usageflags.verify ) log_printf ("%sverify", s), s = ",";
1231       if (prkdf->usageflags.verify_recover)
1232         log_printf ("%sverify_recover", s), s = ",";
1233       if (prkdf->usageflags.derive ) log_printf ("%sderive", s), s = ",";
1234       if (prkdf->usageflags.non_repudiation)
1235         log_printf ("%snon_repudiation", s), s = ",";
1236       log_printf ("\n");
1237
1238       /* Put it into the list. */
1239       prkdf->next = prkdflist;
1240       prkdflist = prkdf;
1241       prkdf = NULL;
1242       continue; /* Ready. */
1243
1244     parse_error:
1245       log_error ("error parsing PrKDF record (%d): %s - skipped\n",
1246                  where, errstr? errstr : gpg_strerror (err));
1247       if (prkdf)
1248         {
1249           xfree (prkdf->objid);
1250           xfree (prkdf->authid);
1251           xfree (prkdf);
1252         }
1253       err = 0;
1254     } /* End looping over all records. */
1255
1256  leave:
1257   xfree (buffer);
1258   if (err)
1259     release_prkdflist (prkdflist);
1260   else
1261     *result = prkdflist;
1262   return err;
1263 }
1264
1265
1266 /* Read and parse the Certificate Directory Files identified by FID.
1267    On success a newlist of CDF object gets stored at RESULT and the
1268    caller is then responsible of releasing this list.  On error a
1269    error code is returned and RESULT won't get changed.  */
1270 static gpg_error_t
1271 read_ef_cdf (app_t app, unsigned short fid, cdf_object_t *result)
1272 {
1273   gpg_error_t err;
1274   unsigned char *buffer = NULL;
1275   size_t buflen;
1276   const unsigned char *p;
1277   size_t n, objlen, hdrlen;
1278   int class, tag, constructed, ndef;
1279   cdf_object_t cdflist = NULL;
1280   int i;
1281
1282   if (!fid)
1283     return gpg_error (GPG_ERR_NO_DATA); /* No certificates. */
1284
1285   err = select_and_read_binary (app->slot, fid, "CDF", &buffer, &buflen);
1286   if (err)
1287     return err;
1288
1289   p = buffer;
1290   n = buflen;
1291
1292   /* Loop over the records.  We stop as soon as we detect a new record
1293      starting with 0x00 or 0xff as these values are commonly used to
1294      pad data blocks and are no valid ASN.1 encoding. */
1295   while (n && *p && *p != 0xff)
1296     {
1297       const unsigned char *pp;
1298       size_t nn;
1299       int where;
1300       const char *errstr = NULL;
1301       cdf_object_t cdf = NULL;
1302       unsigned long ul;
1303       const unsigned char *objid;
1304       size_t objidlen;
1305
1306       err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1307                               &ndef, &objlen, &hdrlen);
1308       if (!err && (objlen > n || tag != TAG_SEQUENCE))
1309         err = gpg_error (GPG_ERR_INV_OBJ);
1310       if (err)
1311         {
1312           log_error ("error parsing CDF record: %s\n", gpg_strerror (err));
1313           goto leave;
1314         }
1315       pp = p;
1316       nn = objlen;
1317       p += objlen;
1318       n -= objlen;
1319
1320       /* Skip the commonObjectAttributes.  */
1321       where = __LINE__;
1322       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1323                               &ndef, &objlen, &hdrlen);
1324       if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1325         err = gpg_error (GPG_ERR_INV_OBJ);
1326       if (err)
1327         goto parse_error;
1328       pp += objlen;
1329       nn -= objlen;
1330
1331       /* Parse the commonCertificateAttributes.  */
1332       where = __LINE__;
1333       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1334                               &ndef, &objlen, &hdrlen);
1335       if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1336         err = gpg_error (GPG_ERR_INV_OBJ);
1337       if (err)
1338         goto parse_error;
1339       {
1340         const unsigned char *ppp = pp;
1341         size_t nnn = objlen;
1342
1343         pp += objlen;
1344         nn -= objlen;
1345
1346         /* Get the Id. */
1347         where = __LINE__;
1348         err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1349                               &ndef, &objlen, &hdrlen);
1350         if (!err && (objlen > nnn
1351                      || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
1352           err = gpg_error (GPG_ERR_INV_OBJ);
1353         if (err)
1354           goto parse_error;
1355         objid = ppp;
1356         objidlen = objlen;
1357       }
1358
1359       /* Parse the certAttribute.  */
1360       where = __LINE__;
1361       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1362                               &ndef, &objlen, &hdrlen);
1363       if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1364         err = gpg_error (GPG_ERR_INV_OBJ);
1365       if (err)
1366         goto parse_error;
1367       nn = objlen;
1368
1369       where = __LINE__;
1370       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1371                               &ndef, &objlen, &hdrlen);
1372       if (!err && (objlen > nn
1373                    || class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE))
1374         err = gpg_error (GPG_ERR_INV_OBJ);
1375       if (err)
1376         goto parse_error;
1377       nn = objlen;
1378
1379       /* Check that the reference is a Path object.  */
1380       where = __LINE__;
1381       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1382                               &ndef, &objlen, &hdrlen);
1383       if (!err && objlen > nn)
1384         err = gpg_error (GPG_ERR_INV_OBJ);
1385       if (err)
1386         goto parse_error;
1387       if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
1388         {
1389           errstr = "unsupported reference type";
1390           goto parse_error;
1391         }
1392       nn = objlen;
1393
1394       /* Parse the Path object. */
1395       where = __LINE__;
1396       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1397                               &ndef, &objlen, &hdrlen);
1398       if (!err && objlen > nn)
1399         err = gpg_error (GPG_ERR_INV_OBJ);
1400       if (err)
1401         goto parse_error;
1402
1403       /* Make sure that the next element is a non zero path and of
1404          even length (FID are two bytes each). */
1405       if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
1406           ||  !objlen || (objlen & 1) )
1407         {
1408           errstr = "invalid path reference";
1409           goto parse_error;
1410         }
1411       /* Create a new CDF list item. */
1412       cdf = xtrycalloc (1, (sizeof *cdf
1413                             - sizeof(unsigned short)
1414                             + objlen/2 * sizeof(unsigned short)));
1415       if (!cdf)
1416         {
1417           err = gpg_error_from_syserror ();
1418           goto leave;
1419         }
1420       cdf->objidlen = objidlen;
1421       cdf->objid = xtrymalloc (objidlen);
1422       if (!cdf->objid)
1423         {
1424           err = gpg_error_from_syserror ();
1425           xfree (cdf);
1426           goto leave;
1427         }
1428       memcpy (cdf->objid, objid, objidlen);
1429
1430       cdf->pathlen = objlen/2;
1431       for (i=0; i < cdf->pathlen; i++, pp += 2, nn -= 2)
1432         cdf->path[i] = ((pp[0] << 8) | pp[1]);
1433
1434       if (nn)
1435         {
1436           /* An index and length follows. */
1437           cdf->have_off = 1;
1438           where = __LINE__;
1439           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1440                                   &ndef, &objlen, &hdrlen);
1441           if (!err && (objlen > nn
1442                        || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1443             err = gpg_error (GPG_ERR_INV_OBJ);
1444           if (err)
1445             goto parse_error;
1446
1447           for (ul=0; objlen; objlen--)
1448             {
1449               ul <<= 8;
1450               ul |= (*pp++) & 0xff;
1451               nn--;
1452             }
1453           cdf->off = ul;
1454
1455           where = __LINE__;
1456           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1457                                   &ndef, &objlen, &hdrlen);
1458           if (!err && (objlen > nn
1459                        || class != CLASS_CONTEXT || tag != 0))
1460             err = gpg_error (GPG_ERR_INV_OBJ);
1461           if (err)
1462             goto parse_error;
1463
1464           for (ul=0; objlen; objlen--)
1465             {
1466               ul <<= 8;
1467               ul |= (*pp++) & 0xff;
1468               nn--;
1469             }
1470           cdf->len = ul;
1471         }
1472
1473       log_debug ("CDF %04hX: id=", fid);
1474       for (i=0; i < cdf->objidlen; i++)
1475         log_printf ("%02X", cdf->objid[i]);
1476       log_printf (" path=");
1477       for (i=0; i < cdf->pathlen; i++)
1478         log_printf ("%04hX", cdf->path[i]);
1479       if (cdf->have_off)
1480         log_printf ("[%lu/%lu]", cdf->off, cdf->len);
1481       log_printf ("\n");
1482
1483       /* Put it into the list. */
1484       cdf->next = cdflist;
1485       cdflist = cdf;
1486       cdf = NULL;
1487       continue; /* Ready. */
1488
1489     parse_error:
1490       log_error ("error parsing CDF record (%d): %s - skipped\n",
1491                  where, errstr? errstr : gpg_strerror (err));
1492       xfree (cdf);
1493       err = 0;
1494     } /* End looping over all records. */
1495
1496  leave:
1497   xfree (buffer);
1498   if (err)
1499     release_cdflist (cdflist);
1500   else
1501     *result = cdflist;
1502   return err;
1503 }
1504
1505
1506 /*
1507 SEQUENCE {
1508   SEQUENCE { -- CommonObjectAttributes
1509     UTF8String 'specific PIN for DS'
1510     BIT STRING 0 unused bits
1511       '00000011'B
1512     }
1513   SEQUENCE { -- CommonAuthenticationObjectAttributes
1514     OCTET STRING
1515       07    -- iD
1516     }
1517
1518   [1] { -- typeAttributes
1519     SEQUENCE { -- PinAttributes
1520       BIT STRING 0 unused bits
1521         '0000100000110010'B  -- local,initialized,needs-padding
1522                              -- exchangeRefData
1523       ENUMERATED 1           -- ascii-numeric
1524       INTEGER 6              -- minLength
1525       INTEGER 6              -- storedLength
1526       INTEGER 8              -- maxLength
1527       [0]
1528         02                   -- pinReference
1529       GeneralizedTime 19/04/2002 12:12 GMT  -- lastPinChange
1530       SEQUENCE {
1531         OCTET STRING
1532           3F 00 40 16        -- path to DF of PIN
1533         }
1534       }
1535     }
1536   }
1537
1538 */
1539 /* Read and parse an Authentication Object Directory File identified
1540    by FID.  On success a newlist of AODF objects gets stored at RESULT
1541    and the caller is responsible of releasing this list.  On error a
1542    error code is returned and RESULT won't get changed.  */
1543 static gpg_error_t
1544 read_ef_aodf (app_t app, unsigned short fid, aodf_object_t *result)
1545 {
1546   gpg_error_t err;
1547   unsigned char *buffer = NULL;
1548   size_t buflen;
1549   const unsigned char *p;
1550   size_t n, objlen, hdrlen;
1551   int class, tag, constructed, ndef;
1552   aodf_object_t aodflist = NULL;
1553   int i;
1554
1555   if (!fid)
1556     return gpg_error (GPG_ERR_NO_DATA); /* No authentication objects. */
1557
1558   err = select_and_read_binary (app->slot, fid, "AODF", &buffer, &buflen);
1559   if (err)
1560     return err;
1561
1562   p = buffer;
1563   n = buflen;
1564
1565   /* FIXME: This shares a LOT of code with read_ef_prkdf! */
1566
1567   /* Loop over the records.  We stop as soon as we detect a new record
1568      starting with 0x00 or 0xff as these values are commonly used to
1569      pad data blocks and are no valid ASN.1 encoding. */
1570   while (n && *p && *p != 0xff)
1571     {
1572       const unsigned char *pp;
1573       size_t nn;
1574       int where;
1575       const char *errstr = NULL;
1576       aodf_object_t aodf = NULL;
1577       unsigned long ul;
1578       const char *s;
1579
1580       err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1581                               &ndef, &objlen, &hdrlen);
1582       if (!err && (objlen > n || tag != TAG_SEQUENCE))
1583         err = gpg_error (GPG_ERR_INV_OBJ);
1584       if (err)
1585         {
1586           log_error ("error parsing AODF record: %s\n", gpg_strerror (err));
1587           goto leave;
1588         }
1589       pp = p;
1590       nn = objlen;
1591       p += objlen;
1592       n -= objlen;
1593
1594       /* Allocate memory for a new AODF list item. */
1595       aodf = xtrycalloc (1, sizeof *aodf);
1596       if (!aodf)
1597         goto no_core;
1598
1599       /* Parse the commonObjectAttributes.  */
1600       where = __LINE__;
1601       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1602                               &ndef, &objlen, &hdrlen);
1603       if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1604         err = gpg_error (GPG_ERR_INV_OBJ);
1605       if (err)
1606         goto parse_error;
1607       {
1608         const unsigned char *ppp = pp;
1609         size_t nnn = objlen;
1610
1611         pp += objlen;
1612         nn -= objlen;
1613
1614         /* Search the optional AuthId.  We need to skip the optional
1615            Label (UTF8STRING) and the optional CommonObjectFlags
1616            (BITSTRING). */
1617         where = __LINE__;
1618         err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1619                                 &ndef, &objlen, &hdrlen);
1620         if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1621           err = gpg_error (GPG_ERR_INV_OBJ);
1622         if (gpg_err_code (err) == GPG_ERR_EOF)
1623           goto no_authid;
1624         if (err)
1625           goto parse_error;
1626         if (tag == TAG_UTF8_STRING)
1627           {
1628             ppp += objlen; /* Skip the Label. */
1629             nnn -= objlen;
1630
1631             where = __LINE__;
1632             err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1633                                     &ndef, &objlen, &hdrlen);
1634             if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1635               err = gpg_error (GPG_ERR_INV_OBJ);
1636             if (gpg_err_code (err) == GPG_ERR_EOF)
1637               goto no_authid;
1638             if (err)
1639               goto parse_error;
1640           }
1641         if (tag == TAG_BIT_STRING)
1642           {
1643             ppp += objlen; /* Skip the CommonObjectFlags.  */
1644             nnn -= objlen;
1645
1646             where = __LINE__;
1647             err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1648                                     &ndef, &objlen, &hdrlen);
1649             if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1650               err = gpg_error (GPG_ERR_INV_OBJ);
1651             if (gpg_err_code (err) == GPG_ERR_EOF)
1652               goto no_authid;
1653             if (err)
1654               goto parse_error;
1655           }
1656         if (tag == TAG_OCTET_STRING && objlen)
1657           {
1658             aodf->authidlen = objlen;
1659             aodf->authid = xtrymalloc (objlen);
1660             if (!aodf->authid)
1661               goto no_core;
1662             memcpy (aodf->authid, ppp, objlen);
1663           }
1664       no_authid:
1665         ;
1666       }
1667
1668       /* Parse the CommonAuthenticationObjectAttributes.  */
1669       where = __LINE__;
1670       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1671                               &ndef, &objlen, &hdrlen);
1672       if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1673         err = gpg_error (GPG_ERR_INV_OBJ);
1674       if (err)
1675         goto parse_error;
1676       {
1677         const unsigned char *ppp = pp;
1678         size_t nnn = objlen;
1679
1680         pp += objlen;
1681         nn -= objlen;
1682
1683         /* Get the Id. */
1684         where = __LINE__;
1685         err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1686                               &ndef, &objlen, &hdrlen);
1687         if (!err && (objlen > nnn
1688                      || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
1689           err = gpg_error (GPG_ERR_INV_OBJ);
1690         if (err)
1691           goto parse_error;
1692
1693         aodf->objidlen = objlen;
1694         aodf->objid = xtrymalloc (objlen);
1695         if (!aodf->objid)
1696           goto no_core;
1697         memcpy (aodf->objid, ppp, objlen);
1698       }
1699
1700       /* Parse the typeAttributes.  */
1701       where = __LINE__;
1702       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1703                               &ndef, &objlen, &hdrlen);
1704       if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1705         err = gpg_error (GPG_ERR_INV_OBJ);
1706       if (err)
1707         goto parse_error;
1708       nn = objlen;
1709
1710       where = __LINE__;
1711       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1712                               &ndef, &objlen, &hdrlen);
1713       if (!err && objlen > nn)
1714         err = gpg_error (GPG_ERR_INV_OBJ);
1715       if (err)
1716         goto parse_error;
1717       if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
1718         ; /* PinAttributes */
1719       else if (class == CLASS_CONTEXT)
1720         {
1721           switch (tag)
1722             {
1723             case 0: errstr = "biometric auth types are not supported"; break;
1724             case 1: errstr = "authKey auth types are not supported"; break;
1725             case 2: errstr = "external auth type are not supported"; break;
1726             default: errstr = "unknown privateKeyObject"; break;
1727             }
1728           goto parse_error;
1729         }
1730       else
1731         {
1732           err = gpg_error (GPG_ERR_INV_OBJ);
1733           goto parse_error;
1734         }
1735
1736       nn = objlen;
1737
1738       /* PinFlags */
1739       where = __LINE__;
1740       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1741                               &ndef, &objlen, &hdrlen);
1742       if (!err && (objlen > nn || !objlen
1743                    || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
1744         err = gpg_error (GPG_ERR_INV_OBJ);
1745       if (err)
1746         goto parse_error;
1747
1748       {
1749         unsigned int bits, mask;
1750         int unused, full;
1751
1752         unused = *pp++; nn--; objlen--;
1753         if ((!objlen && unused) || unused/8 > objlen)
1754           {
1755             err = gpg_error (GPG_ERR_ENCODING_PROBLEM);
1756             goto parse_error;
1757           }
1758         full = objlen - (unused+7)/8;
1759         unused %= 8;
1760         mask = 0;
1761         for (i=1; unused; i <<= 1, unused--)
1762           mask |= i;
1763
1764         /* The first octet */
1765         bits = 0;
1766         if (objlen)
1767           {
1768             bits = *pp++; nn--; objlen--;
1769             if (full)
1770               full--;
1771             else
1772               {
1773                 bits &= ~mask;
1774                 mask = 0;
1775               }
1776           }
1777         if ((bits & 0x80)) /* ASN.1 bit 0. */
1778           aodf->pinflags.case_sensitive = 1;
1779         if ((bits & 0x40)) /* ASN.1 bit 1. */
1780           aodf->pinflags.local = 1;
1781         if ((bits & 0x20))
1782           aodf->pinflags.change_disabled = 1;
1783         if ((bits & 0x10))
1784           aodf->pinflags.unblock_disabled = 1;
1785         if ((bits & 0x08))
1786           aodf->pinflags.initialized = 1;
1787         if ((bits & 0x04))
1788           aodf->pinflags.needs_padding = 1;
1789         if ((bits & 0x02))
1790           aodf->pinflags.unblocking_pin = 1;
1791         if ((bits & 0x01))
1792           aodf->pinflags.so_pin = 1;
1793         /* The second octet. */
1794         bits = 0;
1795         if (objlen)
1796           {
1797             bits = *pp++; nn--; objlen--;
1798             if (full)
1799               full--;
1800             else
1801               {
1802                 bits &= ~mask;
1803               }
1804           }
1805         if ((bits & 0x80))
1806           aodf->pinflags.disable_allowed = 1;
1807         if ((bits & 0x40))
1808           aodf->pinflags.integrity_protected = 1;
1809         if ((bits & 0x20))
1810           aodf->pinflags.confidentiality_protected = 1;
1811         if ((bits & 0x10))
1812           aodf->pinflags.exchange_ref_data = 1;
1813         /* Skip remaining bits. */
1814         pp += objlen;
1815         nn -= objlen;
1816       }
1817
1818
1819       /* PinType */
1820       where = __LINE__;
1821       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1822                               &ndef, &objlen, &hdrlen);
1823       if (!err && (objlen > nn
1824                    || class != CLASS_UNIVERSAL || tag != TAG_ENUMERATED))
1825         err = gpg_error (GPG_ERR_INV_OBJ);
1826       if (!err && objlen > sizeof (ul))
1827         err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1828       if (err)
1829         goto parse_error;
1830
1831       for (ul=0; objlen; objlen--)
1832         {
1833           ul <<= 8;
1834           ul |= (*pp++) & 0xff;
1835           nn--;
1836         }
1837       aodf->pintype = ul;
1838
1839
1840       /* minLength */
1841       where = __LINE__;
1842       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1843                               &ndef, &objlen, &hdrlen);
1844       if (!err && (objlen > nn
1845                    || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1846         err = gpg_error (GPG_ERR_INV_OBJ);
1847       if (!err && objlen > sizeof (ul))
1848         err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1849       if (err)
1850         goto parse_error;
1851       for (ul=0; objlen; objlen--)
1852         {
1853           ul <<= 8;
1854           ul |= (*pp++) & 0xff;
1855           nn--;
1856         }
1857       aodf->min_length = ul;
1858
1859
1860       /* storedLength */
1861       where = __LINE__;
1862       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1863                               &ndef, &objlen, &hdrlen);
1864       if (!err && (objlen > nn
1865                    || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1866         err = gpg_error (GPG_ERR_INV_OBJ);
1867       if (!err && objlen > sizeof (ul))
1868         err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1869       if (err)
1870         goto parse_error;
1871       for (ul=0; objlen; objlen--)
1872         {
1873           ul <<= 8;
1874           ul |= (*pp++) & 0xff;
1875           nn--;
1876         }
1877       aodf->stored_length = ul;
1878
1879       /* optional maxLength */
1880       where = __LINE__;
1881       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1882                               &ndef, &objlen, &hdrlen);
1883       if (gpg_err_code (err) == GPG_ERR_EOF)
1884         goto ready;
1885       if (!err && objlen > nn)
1886         err = gpg_error (GPG_ERR_INV_OBJ);
1887       if (err)
1888         goto parse_error;
1889       if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
1890         {
1891           if (objlen > sizeof (ul))
1892             {
1893               err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1894               goto parse_error;
1895             }
1896           for (ul=0; objlen; objlen--)
1897             {
1898               ul <<= 8;
1899               ul |= (*pp++) & 0xff;
1900               nn--;
1901             }
1902           aodf->max_length = ul;
1903           aodf->max_length_valid = 1;
1904
1905           where = __LINE__;
1906           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1907                                   &ndef, &objlen, &hdrlen);
1908           if (gpg_err_code (err) == GPG_ERR_EOF)
1909             goto ready;
1910           if (!err && objlen > nn)
1911             err = gpg_error (GPG_ERR_INV_OBJ);
1912           if (err)
1913             goto parse_error;
1914         }
1915
1916       /* Optional pinReference. */
1917       if (class == CLASS_CONTEXT && tag == 0)
1918         {
1919           if (objlen > sizeof (ul))
1920             {
1921               err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1922               goto parse_error;
1923             }
1924           for (ul=0; objlen; objlen--)
1925             {
1926               ul <<= 8;
1927               ul |= (*pp++) & 0xff;
1928               nn--;
1929             }
1930           aodf->pin_reference = ul;
1931           aodf->pin_reference_valid = 1;
1932
1933           where = __LINE__;
1934           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1935                                   &ndef, &objlen, &hdrlen);
1936           if (gpg_err_code (err) == GPG_ERR_EOF)
1937             goto ready;
1938           if (!err && objlen > nn)
1939             err = gpg_error (GPG_ERR_INV_OBJ);
1940           if (err)
1941             goto parse_error;
1942         }
1943
1944       /* Optional padChar. */
1945       if (class == CLASS_UNIVERSAL && tag == TAG_OCTET_STRING)
1946         {
1947           if (objlen != 1)
1948             {
1949               errstr = "padChar is not of size(1)";
1950               goto parse_error;
1951             }
1952           aodf->pad_char = *pp++; nn--;
1953           aodf->pad_char_valid = 1;
1954
1955           where = __LINE__;
1956           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1957                                   &ndef, &objlen, &hdrlen);
1958           if (gpg_err_code (err) == GPG_ERR_EOF)
1959             goto ready;
1960           if (!err && objlen > nn)
1961             err = gpg_error (GPG_ERR_INV_OBJ);
1962           if (err)
1963             goto parse_error;
1964         }
1965
1966       /* Skip optional lastPinChange. */
1967       if (class == CLASS_UNIVERSAL && tag == TAG_GENERALIZED_TIME)
1968         {
1969           pp += objlen;
1970           nn -= objlen;
1971
1972           where = __LINE__;
1973           err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1974                                   &ndef, &objlen, &hdrlen);
1975           if (gpg_err_code (err) == GPG_ERR_EOF)
1976             goto ready;
1977           if (!err && objlen > nn)
1978             err = gpg_error (GPG_ERR_INV_OBJ);
1979           if (err)
1980             goto parse_error;
1981         }
1982
1983       /* Optional Path object.  */
1984       if (class == CLASS_UNIVERSAL || tag == TAG_SEQUENCE)
1985         {
1986           const unsigned char *ppp = pp;
1987           size_t nnn = objlen;
1988
1989           pp += objlen;
1990           nn -= objlen;
1991
1992           where = __LINE__;
1993           err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1994                                   &ndef, &objlen, &hdrlen);
1995           if (!err && objlen > nnn)
1996             err = gpg_error (GPG_ERR_INV_OBJ);
1997           if (err)
1998             goto parse_error;
1999
2000           /* Make sure that the next element is a non zero FID and of
2001              even length (FID are two bytes each). */
2002           if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
2003               ||  !objlen || (objlen & 1) )
2004             {
2005               errstr = "invalid path reference";
2006               goto parse_error;
2007             }
2008
2009           aodf->pathlen = objlen/2;
2010           aodf->path = xtrymalloc (aodf->pathlen);
2011           if (!aodf->path)
2012             goto no_core;
2013           for (i=0; i < aodf->pathlen; i++, ppp += 2, nnn -= 2)
2014             aodf->path[i] = ((ppp[0] << 8) | ppp[1]);
2015
2016           if (nnn)
2017             {
2018               /* An index and length follows. */
2019               aodf->have_off = 1;
2020               where = __LINE__;
2021               err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
2022                                       &ndef, &objlen, &hdrlen);
2023               if (!err && (objlen > nnn
2024                        || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
2025                 err = gpg_error (GPG_ERR_INV_OBJ);
2026               if (err)
2027                 goto parse_error;
2028
2029               for (ul=0; objlen; objlen--)
2030                 {
2031                   ul <<= 8;
2032                   ul |= (*ppp++) & 0xff;
2033                   nnn--;
2034                 }
2035               aodf->off = ul;
2036
2037               where = __LINE__;
2038               err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
2039                                       &ndef, &objlen, &hdrlen);
2040               if (!err && (objlen > nnn
2041                            || class != CLASS_CONTEXT || tag != 0))
2042                 err = gpg_error (GPG_ERR_INV_OBJ);
2043               if (err)
2044                 goto parse_error;
2045
2046               for (ul=0; objlen; objlen--)
2047                 {
2048                   ul <<= 8;
2049                   ul |= (*ppp++) & 0xff;
2050                   nnn--;
2051                 }
2052               aodf->len = ul;
2053             }
2054         }
2055
2056       /* Igonore further objects which might be there due to future
2057          extensions of pkcs#15. */
2058
2059     ready:
2060       log_debug ("AODF %04hX: id=", fid);
2061       for (i=0; i < aodf->objidlen; i++)
2062         log_printf ("%02X", aodf->objid[i]);
2063       if (aodf->authid)
2064         {
2065           log_printf (" authid=");
2066           for (i=0; i < aodf->authidlen; i++)
2067             log_printf ("%02X", aodf->authid[i]);
2068         }
2069       log_printf (" flags=");
2070       s = "";
2071       if (aodf->pinflags.case_sensitive)
2072         log_printf ("%scase_sensitive", s), s = ",";
2073       if (aodf->pinflags.local)
2074         log_printf ("%slocal", s), s = ",";
2075       if (aodf->pinflags.change_disabled)
2076         log_printf ("%schange_disabled", s), s = ",";
2077       if (aodf->pinflags.unblock_disabled)
2078         log_printf ("%sunblock_disabled", s), s = ",";
2079       if (aodf->pinflags.initialized)
2080         log_printf ("%sinitialized", s), s = ",";
2081       if (aodf->pinflags.needs_padding)
2082         log_printf ("%sneeds_padding", s), s = ",";
2083       if (aodf->pinflags.unblocking_pin)
2084         log_printf ("%sunblocking_pin", s), s = ",";
2085       if (aodf->pinflags.so_pin)
2086         log_printf ("%sso_pin", s), s = ",";
2087       if (aodf->pinflags.disable_allowed)
2088         log_printf ("%sdisable_allowed", s), s = ",";
2089       if (aodf->pinflags.integrity_protected)
2090         log_printf ("%sintegrity_protected", s), s = ",";
2091       if (aodf->pinflags.confidentiality_protected)
2092         log_printf ("%sconfidentiality_protected", s), s = ",";
2093       if (aodf->pinflags.exchange_ref_data)
2094         log_printf ("%sexchange_ref_data", s), s = ",";
2095       {
2096         char numbuf[50];
2097         switch (aodf->pintype)
2098           {
2099           case PIN_TYPE_BCD: s = "bcd"; break;
2100           case PIN_TYPE_ASCII_NUMERIC: s = "ascii-numeric"; break;
2101           case PIN_TYPE_UTF8: s = "utf8"; break;
2102           case PIN_TYPE_HALF_NIBBLE_BCD: s = "half-nibble-bcd"; break;
2103           case PIN_TYPE_ISO9564_1: s = "iso9564-1"; break;
2104           default:
2105             sprintf (numbuf, "%lu", (unsigned long)aodf->pintype);
2106             s = numbuf;
2107           }
2108         log_printf (" type=%s", s);
2109       }
2110       log_printf (" min=%lu", aodf->min_length);
2111       log_printf (" stored=%lu", aodf->stored_length);
2112       if (aodf->max_length_valid)
2113         log_printf (" max=%lu", aodf->max_length);
2114       if (aodf->pad_char_valid)
2115         log_printf (" pad=0x%02x", aodf->pad_char);
2116       if (aodf->pin_reference_valid)
2117         log_printf (" pinref=0x%02lX", aodf->pin_reference);
2118       if (aodf->pathlen)
2119         {
2120           log_printf (" path=");
2121           for (i=0; i < aodf->pathlen; i++)
2122             log_printf ("%04hX", aodf->path[i]);
2123           if (aodf->have_off)
2124             log_printf ("[%lu/%lu]", aodf->off, aodf->len);
2125         }
2126       log_printf ("\n");
2127
2128       /* Put it into the list. */
2129       aodf->next = aodflist;
2130       aodflist = aodf;
2131       aodf = NULL;
2132       continue; /* Ready. */
2133
2134     no_core:
2135       err = gpg_error_from_syserror ();
2136       release_aodf_object (aodf);
2137       goto leave;
2138
2139     parse_error:
2140       log_error ("error parsing AODF record (%d): %s - skipped\n",
2141                  where, errstr? errstr : gpg_strerror (err));
2142       err = 0;
2143       release_aodf_object (aodf);
2144     } /* End looping over all records. */
2145
2146  leave:
2147   xfree (buffer);
2148   if (err)
2149     release_aodflist (aodflist);
2150   else
2151     *result = aodflist;
2152   return err;
2153 }
2154
2155
2156
2157
2158
2159 /* Read and parse the EF(TokenInfo).
2160
2161 TokenInfo ::= SEQUENCE {
2162     version             INTEGER {v1(0)} (v1,...),
2163     serialNumber        OCTET STRING,
2164     manufacturerID      Label OPTIONAL,
2165     label               [0] Label OPTIONAL,
2166     tokenflags          TokenFlags,
2167     seInfo              SEQUENCE OF SecurityEnvironmentInfo OPTIONAL,
2168     recordInfo          [1] RecordInfo OPTIONAL,
2169     supportedAlgorithms [2] SEQUENCE OF AlgorithmInfo OPTIONAL,
2170     ...,
2171     issuerId            [3] Label OPTIONAL,
2172     holderId            [4] Label OPTIONAL,
2173     lastUpdate          [5] LastUpdate OPTIONAL,
2174     preferredLanguage   PrintableString OPTIONAL -- In accordance with
2175     -- IETF RFC 1766
2176 } (CONSTRAINED BY { -- Each AlgorithmInfo.reference value must be unique --})
2177
2178 TokenFlags ::= BIT STRING {
2179     readOnly            (0),
2180     loginRequired       (1),
2181     prnGeneration       (2),
2182     eidCompliant        (3)
2183 }
2184
2185
2186  5032:
2187
2188 30 31 02 01 00 04 04 05 45  36 9F 0C 0C 44 2D 54   01......E6...D-T
2189 72 75 73 74 20 47 6D 62 48  80 14 4F 66 66 69 63   rust GmbH..Offic
2190 65 20 69 64 65 6E 74 69 74  79 20 63 61 72 64 03   e identity card.
2191 02 00 40 20 63 61 72 64 03  02 00 40 00 00 00 00   ..@ card...@....
2192 00 00 00 00 00 00 00 00 00  00 00 00 00 00 00 00   ................
2193
2194    0   49: SEQUENCE {
2195    2    1:   INTEGER 0
2196    5    4:   OCTET STRING 05 45 36 9F
2197   11   12:   UTF8String 'D-Trust GmbH'
2198   25   20:   [0] 'Office identity card'
2199   47    2:   BIT STRING
2200          :     '00000010'B (bit 1)
2201          :     Error: Spurious zero bits in bitstring.
2202          :   }
2203
2204
2205
2206
2207  */
2208 static gpg_error_t
2209 read_ef_tokeninfo (app_t app)
2210 {
2211   gpg_error_t err;
2212   unsigned char *buffer = NULL;
2213   size_t buflen;
2214   const unsigned char *p;
2215   size_t n, objlen, hdrlen;
2216   int class, tag, constructed, ndef;
2217   unsigned long ul;
2218
2219   err = select_and_read_binary (app->slot, 0x5032, "TokenInfo",
2220                                 &buffer, &buflen);
2221   if (err)
2222     return err;
2223
2224   p = buffer;
2225   n = buflen;
2226
2227   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2228                           &ndef, &objlen, &hdrlen);
2229   if (!err && (objlen > n || tag != TAG_SEQUENCE))
2230     err = gpg_error (GPG_ERR_INV_OBJ);
2231   if (err)
2232     {
2233       log_error ("error parsing TokenInfo: %s\n", gpg_strerror (err));
2234       goto leave;
2235     }
2236
2237   n = objlen;
2238
2239   /* Version.  */
2240   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2241                           &ndef, &objlen, &hdrlen);
2242   if (!err && (objlen > n || tag != TAG_INTEGER))
2243     err = gpg_error (GPG_ERR_INV_OBJ);
2244   if (err)
2245     goto leave;
2246
2247   for (ul=0; objlen; objlen--)
2248     {
2249       ul <<= 8;
2250       ul |= (*p++) & 0xff;
2251       n--;
2252     }
2253   if (ul)
2254     {
2255       log_error ("invalid version %lu in TokenInfo\n", ul);
2256       err = gpg_error (GPG_ERR_INV_OBJ);
2257       goto leave;
2258     }
2259
2260   /* serialNumber.  */
2261   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2262                           &ndef, &objlen, &hdrlen);
2263   if (!err && (objlen > n || tag != TAG_OCTET_STRING || !objlen))
2264     err = gpg_error (GPG_ERR_INV_OBJ);
2265   if (err)
2266     goto leave;
2267
2268   xfree (app->app_local->serialno);
2269   app->app_local->serialno = xtrymalloc (objlen);
2270   if (!app->app_local->serialno)
2271     {
2272       err = gpg_error_from_syserror ();
2273       goto leave;
2274     }
2275   memcpy (app->app_local->serialno, p, objlen);
2276   app->app_local->serialnolen = objlen;
2277   log_printhex ("Serialnumber from EF(TokenInfo) is:", p, objlen);
2278
2279  leave:
2280   xfree (buffer);
2281   return err;
2282 }
2283
2284
2285 /* Get all the basic information from the pkcs#15 card, check the
2286    structure and initialize our local context.  This is used once at
2287    application initialization. */
2288 static gpg_error_t
2289 read_p15_info (app_t app)
2290 {
2291   gpg_error_t err;
2292
2293   if (!read_ef_tokeninfo (app))
2294     {
2295       /* If we don't have a serial number yet but the TokenInfo provides
2296          one, use that. */
2297       if (!app->serialno && app->app_local->serialno)
2298         {
2299           app->serialno = app->app_local->serialno;
2300           app->serialnolen = app->app_local->serialnolen;
2301           app->app_local->serialno = NULL;
2302           app->app_local->serialnolen = 0;
2303           err = app_munge_serialno (app);
2304           if (err)
2305             return err;
2306         }
2307     }
2308
2309   /* Read the ODF so that we know the location of all directory
2310      files. */
2311   /* Fixme: We might need to get a non-standard ODF FID from TokenInfo. */
2312   err = read_ef_odf (app, 0x5031);
2313   if (err)
2314     return err;
2315
2316   /* Read certificate information. */
2317   assert (!app->app_local->certificate_info);
2318   assert (!app->app_local->trusted_certificate_info);
2319   assert (!app->app_local->useful_certificate_info);
2320   err = read_ef_cdf (app, app->app_local->odf.certificates,
2321                      &app->app_local->certificate_info);
2322   if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
2323     err = read_ef_cdf (app, app->app_local->odf.trusted_certificates,
2324                        &app->app_local->trusted_certificate_info);
2325   if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
2326     err = read_ef_cdf (app, app->app_local->odf.useful_certificates,
2327                        &app->app_local->useful_certificate_info);
2328   if (gpg_err_code (err) == GPG_ERR_NO_DATA)
2329     err = 0;
2330   if (err)
2331     return err;
2332
2333   /* Read information about private keys. */
2334   assert (!app->app_local->private_key_info);
2335   err = read_ef_prkdf (app, app->app_local->odf.private_keys,
2336                        &app->app_local->private_key_info);
2337   if (gpg_err_code (err) == GPG_ERR_NO_DATA)
2338     err = 0;
2339   if (err)
2340     return err;
2341
2342   /* Read information about authentication objects. */
2343   assert (!app->app_local->auth_object_info);
2344   err = read_ef_aodf (app, app->app_local->odf.auth_objects,
2345                       &app->app_local->auth_object_info);
2346   if (gpg_err_code (err) == GPG_ERR_NO_DATA)
2347     err = 0;
2348
2349
2350   return err;
2351 }
2352
2353
2354 /* Helper to do_learn_status: Send information about all certificates
2355    listed in CERTINFO back.  Use CERTTYPE as type of the
2356    certificate. */
2357 static gpg_error_t
2358 send_certinfo (app_t app, ctrl_t ctrl, const char *certtype,
2359                cdf_object_t certinfo)
2360 {
2361   for (; certinfo; certinfo = certinfo->next)
2362     {
2363       char *buf, *p;
2364
2365       buf = xtrymalloc (9 + certinfo->objidlen*2 + 1);
2366       if (!buf)
2367         return gpg_error_from_syserror ();
2368       p = stpcpy (buf, "P15");
2369       if (app->app_local->home_df)
2370         {
2371           snprintf (p, 6, "-%04X",
2372                     (unsigned int)(app->app_local->home_df & 0xffff));
2373           p += 5;
2374         }
2375       p = stpcpy (p, ".");
2376       bin2hex (certinfo->objid, certinfo->objidlen, p);
2377
2378       send_status_info (ctrl, "CERTINFO",
2379                         certtype, strlen (certtype),
2380                         buf, strlen (buf),
2381                         NULL, (size_t)0);
2382       xfree (buf);
2383     }
2384   return 0;
2385 }
2386
2387
2388 /* Get the keygrip of the private key object PRKDF.  On success the
2389    keygrip gets returned in the caller provided 41 byte buffer
2390    R_GRIPSTR. */
2391 static gpg_error_t
2392 keygripstr_from_prkdf (app_t app, prkdf_object_t prkdf, char *r_gripstr)
2393 {
2394   gpg_error_t err;
2395   cdf_object_t cdf;
2396   unsigned char *der;
2397   size_t derlen;
2398   ksba_cert_t cert;
2399
2400   /* FIXME: We should check whether a public key directory file and a
2401      matching public key for PRKDF is available.  This should make
2402      extraction of the key much easier.  My current test card doesn't
2403      have one, so we can only use the fallback solution bu looking for
2404      a matching certificate and extract the key from there. */
2405
2406   /* Look for a matching certificate. A certificate matches if the Id
2407      matches the one of the private key info. */
2408   for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
2409     if (cdf->objidlen == prkdf->objidlen
2410         && !memcmp (cdf->objid, prkdf->objid, prkdf->objidlen))
2411       break;
2412   if (!cdf)
2413     for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
2414       if (cdf->objidlen == prkdf->objidlen
2415           && !memcmp (cdf->objid, prkdf->objid, prkdf->objidlen))
2416         break;
2417   if (!cdf)
2418     for (cdf = app->app_local->useful_certificate_info; cdf; cdf = cdf->next)
2419       if (cdf->objidlen == prkdf->objidlen
2420           && !memcmp (cdf->objid, prkdf->objid, prkdf->objidlen))
2421         break;
2422   if (!cdf)
2423     return gpg_error (GPG_ERR_NOT_FOUND);
2424
2425   err = readcert_by_cdf (app, cdf, &der, &derlen);
2426   if (err)
2427     return err;
2428
2429   err = ksba_cert_new (&cert);
2430   if (!err)
2431     err = ksba_cert_init_from_mem (cert, der, derlen);
2432   xfree (der);
2433   if (!err)
2434     err = app_help_get_keygrip_string (cert, r_gripstr);
2435   ksba_cert_release (cert);
2436
2437   return err;
2438 }
2439
2440
2441
2442
2443 /* Helper to do_learn_status: Send information about all known
2444    keypairs back.  FIXME: much code duplication from
2445    send_certinfo(). */
2446 static gpg_error_t
2447 send_keypairinfo (app_t app, ctrl_t ctrl, prkdf_object_t keyinfo)
2448 {
2449   gpg_error_t err;
2450
2451   for (; keyinfo; keyinfo = keyinfo->next)
2452     {
2453       char gripstr[40+1];
2454       char *buf, *p;
2455       int j;
2456
2457       buf = xtrymalloc (9 + keyinfo->objidlen*2 + 1);
2458       if (!buf)
2459         return gpg_error_from_syserror ();
2460       p = stpcpy (buf, "P15");
2461       if (app->app_local->home_df)
2462         {
2463           snprintf (p, 6, "-%04X",
2464                     (unsigned int)(app->app_local->home_df & 0xffff));
2465           p += 5;
2466         }
2467       p = stpcpy (p, ".");
2468       bin2hex (keyinfo->objid, keyinfo->objidlen, p);
2469
2470       err = keygripstr_from_prkdf (app, keyinfo, gripstr);
2471       if (err)
2472         {
2473           log_error ("can't get keygrip from ");
2474           for (j=0; j < keyinfo->pathlen; j++)
2475             log_printf ("%04hX", keyinfo->path[j]);
2476           log_printf (": %s\n", gpg_strerror (err));
2477         }
2478       else
2479         {
2480           assert (strlen (gripstr) == 40);
2481           send_status_info (ctrl, "KEYPAIRINFO",
2482                             gripstr, 40,
2483                             buf, strlen (buf),
2484                             NULL, (size_t)0);
2485         }
2486       xfree (buf);
2487     }
2488   return 0;
2489 }
2490
2491
2492
2493 /* This is the handler for the LEARN command.  */
2494 static gpg_error_t
2495 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
2496 {
2497   gpg_error_t err;
2498
2499   if ((flags & 1))
2500     err = 0;
2501   else
2502     {
2503       err = send_certinfo (app, ctrl, "100", app->app_local->certificate_info);
2504       if (!err)
2505         err = send_certinfo (app, ctrl, "101",
2506                              app->app_local->trusted_certificate_info);
2507       if (!err)
2508         err = send_certinfo (app, ctrl, "102",
2509                              app->app_local->useful_certificate_info);
2510     }
2511
2512   if (!err)
2513     err = send_keypairinfo (app, ctrl, app->app_local->private_key_info);
2514
2515   return err;
2516 }
2517
2518
2519 /* Read a certifciate using the information in CDF and return the
2520    certificate in a newly llocated buffer R_CERT and its length
2521    R_CERTLEN. */
2522 static gpg_error_t
2523 readcert_by_cdf (app_t app, cdf_object_t cdf,
2524                  unsigned char **r_cert, size_t *r_certlen)
2525 {
2526   gpg_error_t err;
2527   unsigned char *buffer = NULL;
2528   const unsigned char *p, *save_p;
2529   size_t buflen, n;
2530   int class, tag, constructed, ndef;
2531   size_t totobjlen, objlen, hdrlen;
2532   int rootca;
2533   int i;
2534
2535   *r_cert = NULL;
2536   *r_certlen = 0;
2537
2538   /* First check whether it has been cached. */
2539   if (cdf->image)
2540     {
2541       *r_cert = xtrymalloc (cdf->imagelen);
2542       if (!*r_cert)
2543         return gpg_error_from_syserror ();
2544       memcpy (*r_cert, cdf->image, cdf->imagelen);
2545       *r_certlen = cdf->imagelen;
2546       return 0;
2547     }
2548
2549   /* Read the entire file.  fixme: This could be optimized by first
2550      reading the header to figure out how long the certificate
2551      actually is. */
2552   err = select_ef_by_path (app, cdf->path, cdf->pathlen);
2553   if (err)
2554     goto leave;
2555
2556   err = iso7816_read_binary (app->slot, cdf->off, cdf->len, &buffer, &buflen);
2557   if (!err && (!buflen || *buffer == 0xff))
2558     err = gpg_error (GPG_ERR_NOT_FOUND);
2559   if (err)
2560     {
2561       log_error ("error reading certificate with Id ");
2562       for (i=0; i < cdf->objidlen; i++)
2563         log_printf ("%02X", cdf->objid[i]);
2564       log_printf (": %s\n", gpg_strerror (err));
2565       goto leave;
2566     }
2567
2568   /* Check whether this is really a certificate.  */
2569   p = buffer;
2570   n = buflen;
2571   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2572                           &ndef, &objlen, &hdrlen);
2573   if (err)
2574     goto leave;
2575
2576   if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed)
2577     rootca = 0;
2578   else if ( class == CLASS_UNIVERSAL && tag == TAG_SET && constructed )
2579     rootca = 1;
2580   else
2581     {
2582       err = gpg_error (GPG_ERR_INV_OBJ);
2583       goto leave;
2584     }
2585   totobjlen = objlen + hdrlen;
2586   assert (totobjlen <= buflen);
2587
2588   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2589                           &ndef, &objlen, &hdrlen);
2590   if (err)
2591     goto leave;
2592
2593   if (!rootca
2594       && class == CLASS_UNIVERSAL && tag == TAG_OBJECT_ID && !constructed)
2595     {
2596       /* The certificate seems to be contained in a userCertificate
2597          container.  Skip this and assume the following sequence is
2598          the certificate. */
2599       if (n < objlen)
2600         {
2601           err = gpg_error (GPG_ERR_INV_OBJ);
2602           goto leave;
2603         }
2604       p += objlen;
2605       n -= objlen;
2606       save_p = p;
2607       err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2608                               &ndef, &objlen, &hdrlen);
2609       if (err)
2610         goto leave;
2611       if ( !(class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed) )
2612         {
2613           err = gpg_error (GPG_ERR_INV_OBJ);
2614           goto leave;
2615         }
2616       totobjlen = objlen + hdrlen;
2617       assert (save_p + totobjlen <= buffer + buflen);
2618       memmove (buffer, save_p, totobjlen);
2619     }
2620
2621   *r_cert = buffer;
2622   buffer = NULL;
2623   *r_certlen = totobjlen;
2624
2625   /* Try to cache it. */
2626   if (!cdf->image && (cdf->image = xtrymalloc (*r_certlen)))
2627     {
2628       memcpy (cdf->image, *r_cert, *r_certlen);
2629       cdf->imagelen = *r_certlen;
2630     }
2631
2632
2633  leave:
2634   xfree (buffer);
2635   return err;
2636 }
2637
2638
2639 /* Handler for the READCERT command.
2640
2641    Read the certificate with id CERTID (as returned by learn_status in
2642    the CERTINFO status lines) and return it in the freshly allocated
2643    buffer to be stored at R_CERT and its length at R_CERTLEN.  A error
2644    code will be returned on failure and R_CERT and R_CERTLEN will be
2645    set to (NULL,0). */
2646 static gpg_error_t
2647 do_readcert (app_t app, const char *certid,
2648              unsigned char **r_cert, size_t *r_certlen)
2649 {
2650   gpg_error_t err;
2651   cdf_object_t cdf;
2652
2653   *r_cert = NULL;
2654   *r_certlen = 0;
2655   err = cdf_object_from_certid (app, certid, &cdf);
2656   if (!err)
2657     err = readcert_by_cdf (app, cdf, r_cert, r_certlen);
2658   return err;
2659 }
2660
2661
2662
2663 /* Implement the GETATTR command.  This is similar to the LEARN
2664    command but returns just one value via the status interface. */
2665 static gpg_error_t
2666 do_getattr (app_t app, ctrl_t ctrl, const char *name)
2667 {
2668   gpg_error_t err;
2669
2670   if (!strcmp (name, "$AUTHKEYID"))
2671     {
2672       char *buf, *p;
2673       prkdf_object_t prkdf;
2674
2675       /* We return the ID of the first private keycapable of
2676          signing. */
2677       for (prkdf = app->app_local->private_key_info; prkdf;
2678            prkdf = prkdf->next)
2679         if (prkdf->usageflags.sign)
2680           break;
2681       if (prkdf)
2682         {
2683           buf = xtrymalloc (9 + prkdf->objidlen*2 + 1);
2684           if (!buf)
2685             return gpg_error_from_syserror ();
2686           p = stpcpy (buf, "P15");
2687           if (app->app_local->home_df)
2688             {
2689               snprintf (p, 6, "-%04X",
2690                         (unsigned int)(app->app_local->home_df & 0xffff));
2691               p += 5;
2692             }
2693           p = stpcpy (p, ".");
2694           bin2hex (prkdf->objid, prkdf->objidlen, p);
2695
2696           send_status_info (ctrl, name, buf, strlen (buf), NULL, 0);
2697           xfree (buf);
2698           return 0;
2699         }
2700     }
2701   else if (!strcmp (name, "$DISPSERIALNO"))
2702     {
2703       /* For certain cards we return special IDs.  There is no
2704          general rule for it so we need to decide case by case. */
2705       if (app->app_local->card_type == CARD_TYPE_BELPIC)
2706         {
2707           /* The eID card has a card number printed on the front matter
2708              which seems to be a good indication. */
2709           unsigned char *buffer;
2710           const unsigned char *p;
2711           size_t buflen, n;
2712           unsigned short path[] = { 0x3F00, 0xDF01, 0x4031 };
2713
2714           err = select_ef_by_path (app, path, DIM(path) );
2715           if (!err)
2716             err = iso7816_read_binary (app->slot, 0, 0, &buffer, &buflen);
2717           if (err)
2718             {
2719               log_error ("error accessing EF(ID): %s\n", gpg_strerror (err));
2720               return err;
2721             }
2722
2723           p = find_tlv (buffer, buflen, 1, &n);
2724           if (p && n == 12)
2725             {
2726               char tmp[12+2+1];
2727               memcpy (tmp, p, 3);
2728               tmp[3] = '-';
2729               memcpy (tmp+4, p+3, 7);
2730               tmp[11] = '-';
2731               memcpy (tmp+12, p+10, 2);
2732               tmp[14] = 0;
2733               send_status_info (ctrl, name, tmp, strlen (tmp), NULL, 0);
2734               xfree (buffer);
2735               return 0;
2736             }
2737           xfree (buffer);
2738         }
2739
2740     }
2741   return gpg_error (GPG_ERR_INV_NAME);
2742 }
2743
2744
2745
2746
2747 /* Micardo cards require special treatment. This is a helper for the
2748    crypto functions to manage the security environment.  We expect that
2749    the key file has already been selected. FID is the one of the
2750    selected key. */
2751 static gpg_error_t
2752 micardo_mse (app_t app, unsigned short fid)
2753 {
2754   gpg_error_t err;
2755   int recno;
2756   unsigned short refdata = 0;
2757   int se_num;
2758   unsigned char msebuf[10];
2759
2760   /* Read the KeyD file containing extra information on keys. */
2761   err = iso7816_select_file (app->slot, 0x0013, 0);
2762   if (err)
2763     {
2764       log_error ("error reading EF_keyD: %s\n", gpg_strerror (err));
2765       return err;
2766     }
2767
2768   for (recno = 1, se_num = -1; ; recno++)
2769     {
2770       unsigned char *buffer;
2771       size_t buflen;
2772       size_t n, nn;
2773       const unsigned char *p, *pp;
2774
2775       err = iso7816_read_record (app->slot, recno, 1, 0, &buffer, &buflen);
2776       if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2777         break; /* ready */
2778       if (err)
2779         {
2780           log_error ("error reading EF_keyD record: %s\n",
2781                      gpg_strerror (err));
2782           return err;
2783         }
2784       log_printhex ("keyD record:", buffer, buflen);
2785       p = find_tlv (buffer, buflen, 0x83, &n);
2786       if (p && n == 4 && ((p[2]<<8)|p[3]) == fid)
2787         {
2788           refdata = ((p[0]<<8)|p[1]);
2789           /* Locate the SE DO and the there included sec env number. */
2790           p = find_tlv (buffer, buflen, 0x7b, &n);
2791           if (p && n)
2792             {
2793               pp = find_tlv (p, n, 0x80, &nn);
2794               if (pp && nn == 1)
2795                 {
2796                   se_num = *pp;
2797                   xfree (buffer);
2798                   break; /* found. */
2799                 }
2800             }
2801         }
2802       xfree (buffer);
2803     }
2804   if (se_num == -1)
2805     {
2806       log_error ("CRT for keyfile %04hX not found\n", fid);
2807       return gpg_error (GPG_ERR_NOT_FOUND);
2808     }
2809
2810
2811   /* Restore the security environment to SE_NUM if needed */
2812   if (se_num)
2813     {
2814       err = iso7816_manage_security_env (app->slot, 0xf3, se_num, NULL, 0);
2815       if (err)
2816         {
2817           log_error ("restoring SE to %d failed: %s\n",
2818                      se_num, gpg_strerror (err));
2819           return err;
2820         }
2821     }
2822
2823   /* Set the DST reference data. */
2824   msebuf[0] = 0x83;
2825   msebuf[1] = 0x03;
2826   msebuf[2] = 0x80;
2827   msebuf[3] = (refdata >> 8);
2828   msebuf[4] = refdata;
2829   err = iso7816_manage_security_env (app->slot, 0x41, 0xb6, msebuf, 5);
2830   if (err)
2831     {
2832       log_error ("setting SE to reference file %04hX failed: %s\n",
2833                  refdata, gpg_strerror (err));
2834       return err;
2835     }
2836   return 0;
2837 }
2838
2839
2840
2841 /* Handler for the PKSIGN command.
2842
2843    Create the signature and return the allocated result in OUTDATA.
2844    If a PIN is required, the PINCB will be used to ask for the PIN;
2845    that callback should return the PIN in an allocated buffer and
2846    store that as the 3rd argument.  */
2847 static gpg_error_t
2848 do_sign (app_t app, const char *keyidstr, int hashalgo,
2849          gpg_error_t (*pincb)(void*, const char *, char **),
2850          void *pincb_arg,
2851          const void *indata, size_t indatalen,
2852          unsigned char **outdata, size_t *outdatalen )
2853 {
2854   static unsigned char sha1_prefix[15] = /* Object ID is 1.3.14.3.2.26 */
2855     { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
2856       0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
2857   static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
2858     { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
2859       0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
2860
2861   gpg_error_t err;
2862   int i;
2863   unsigned char data[36];   /* Must be large enough for a SHA-1 digest
2864                                + the largest OID prefix above and also
2865                                fit the 36 bytes of md5sha1.  */
2866   prkdf_object_t prkdf;    /* The private key object. */
2867   aodf_object_t aodf;      /* The associated authentication object. */
2868   int no_data_padding = 0; /* True if the card want the data without padding.*/
2869   int mse_done = 0;        /* Set to true if the MSE has been done. */
2870
2871   if (!keyidstr || !*keyidstr)
2872     return gpg_error (GPG_ERR_INV_VALUE);
2873   if (indatalen != 20 && indatalen != 16 && indatalen != 35 && indatalen != 36)
2874     return gpg_error (GPG_ERR_INV_VALUE);
2875
2876   err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
2877   if (err)
2878     return err;
2879   if (!(prkdf->usageflags.sign || prkdf->usageflags.sign_recover
2880         ||prkdf->usageflags.non_repudiation))
2881     {
2882       log_error ("key %s may not be used for signing\n", keyidstr);
2883       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
2884     }
2885
2886   if (!prkdf->authid)
2887     {
2888       log_error ("no authentication object defined for %s\n", keyidstr);
2889       /* fixme: we might want to go ahead and do without PIN
2890          verification. */
2891       return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2892     }
2893
2894   /* Find the authentication object to this private key object. */
2895   for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
2896     if (aodf->objidlen == prkdf->authidlen
2897         && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
2898       break;
2899   if (!aodf)
2900     {
2901       log_error ("authentication object for %s missing\n", keyidstr);
2902       return gpg_error (GPG_ERR_INV_CARD);
2903     }
2904   if (aodf->authid)
2905     {
2906       log_error ("PIN verification is protected by an "
2907                  "additional authentication token\n");
2908       return gpg_error (GPG_ERR_BAD_PIN_METHOD);
2909     }
2910   if (aodf->pinflags.integrity_protected
2911       || aodf->pinflags.confidentiality_protected)
2912     {
2913       log_error ("PIN verification requires unsupported protection method\n");
2914       return gpg_error (GPG_ERR_BAD_PIN_METHOD);
2915     }
2916   if (!aodf->stored_length && aodf->pinflags.needs_padding)
2917     {
2918       log_error ("PIN verification requires padding but no length known\n");
2919       return gpg_error (GPG_ERR_INV_CARD);
2920     }
2921
2922   /* Select the key file.  Note that this may change the security
2923      environment thus we do it before PIN verification. */
2924   err = select_ef_by_path (app, prkdf->path, prkdf->pathlen);
2925   if (err)
2926     {
2927       log_error ("error selecting file for key %s: %s\n",
2928                  keyidstr, gpg_strerror (errno));
2929       return err;
2930     }
2931
2932
2933   /* Due to the fact that the non-repudiation signature on a BELPIC
2934      card requires a verify immediately before the DSO we set the
2935      MSE before we do the verification.  Other cards might also allow
2936      this but I don't want to break anything, thus we do it only
2937      for the BELPIC card here. */
2938   if (app->app_local->card_type == CARD_TYPE_BELPIC)
2939     {
2940       unsigned char mse[5];
2941
2942       mse[0] = 4;    /* Length of the template. */
2943       mse[1] = 0x80; /* Algorithm reference tag. */
2944       if (hashalgo == MD_USER_TLS_MD5SHA1)
2945         mse[2] = 0x01; /* Let card do pkcs#1 0xFF padding. */
2946       else
2947         mse[2] = 0x02; /* RSASSA-PKCS1-v1.5 using SHA1. */
2948       mse[3] = 0x84; /* Private key reference tag. */
2949       mse[4] = prkdf->key_reference_valid? prkdf->key_reference : 0x82;
2950
2951       err = iso7816_manage_security_env (app->slot,
2952                                          0x41, 0xB6,
2953                                          mse, sizeof mse);
2954       no_data_padding = 1;
2955       mse_done = 1;
2956     }
2957   if (err)
2958     {
2959       log_error ("MSE failed: %s\n", gpg_strerror (err));
2960       return err;
2961     }
2962
2963
2964   /* Now that we have all the information available, prepare and run
2965      the PIN verification.*/
2966   if (1)
2967     {
2968       char *pinvalue;
2969       size_t pinvaluelen;
2970       const char *errstr;
2971       const char *s;
2972
2973       if (prkdf->usageflags.non_repudiation
2974           && app->app_local->card_type == CARD_TYPE_BELPIC)
2975         err = pincb (pincb_arg, "PIN (qualified signature!)", &pinvalue);
2976       else
2977         err = pincb (pincb_arg, "PIN", &pinvalue);
2978       if (err)
2979         {
2980           log_info ("PIN callback returned error: %s\n", gpg_strerror (err));
2981           return err;
2982         }
2983
2984       /* We might need to cope with UTF8 things here.  Not sure how
2985          min_length etc. are exactly defined, for now we take them as
2986          a plain octet count. */
2987
2988       if (strlen (pinvalue) < aodf->min_length)
2989         {
2990           log_error ("PIN is too short; minimum length is %lu\n",
2991                      aodf->min_length);
2992           err = gpg_error (GPG_ERR_BAD_PIN);
2993         }
2994       else if (aodf->stored_length && strlen (pinvalue) > aodf->stored_length)
2995         {
2996           /* This would otherwise truncate the PIN silently. */
2997           log_error ("PIN is too large; maximum length is %lu\n",
2998                      aodf->stored_length);
2999           err = gpg_error (GPG_ERR_BAD_PIN);
3000         }
3001       else if (aodf->max_length_valid && strlen (pinvalue) > aodf->max_length)
3002         {
3003           log_error ("PIN is too large; maximum length is %lu\n",
3004                      aodf->max_length);
3005           err = gpg_error (GPG_ERR_BAD_PIN);
3006         }
3007
3008       if (err)
3009         {
3010           xfree (pinvalue);
3011           return err;
3012         }
3013
3014       errstr = NULL;
3015       err = 0;
3016       switch (aodf->pintype)
3017         {
3018         case PIN_TYPE_BCD:
3019         case PIN_TYPE_ASCII_NUMERIC:
3020           for (s=pinvalue; digitp (s); s++)
3021             ;
3022           if (*s)
3023             {
3024               errstr = "Non-numeric digits found in PIN";
3025               err = gpg_error (GPG_ERR_BAD_PIN);
3026             }
3027           break;
3028         case PIN_TYPE_UTF8:
3029           break;
3030         case PIN_TYPE_HALF_NIBBLE_BCD:
3031           errstr = "PIN type Half-Nibble-BCD is not supported";
3032           break;
3033         case PIN_TYPE_ISO9564_1:
3034           errstr = "PIN type ISO9564-1 is not supported";
3035           break;
3036         default:
3037           errstr = "Unknown PIN type";
3038           break;
3039         }
3040       if (errstr)
3041         {
3042           log_error ("can't verify PIN: %s\n", errstr);
3043           xfree (pinvalue);
3044           return err? err : gpg_error (GPG_ERR_BAD_PIN_METHOD);
3045         }
3046
3047
3048       if (aodf->pintype == PIN_TYPE_BCD )
3049         {
3050           char *paddedpin;
3051           int ndigits;
3052
3053           for (ndigits=0, s=pinvalue; *s; ndigits++, s++)
3054             ;
3055           paddedpin = xtrymalloc (aodf->stored_length+1);
3056           if (!paddedpin)
3057             {
3058               err = gpg_error_from_syserror ();
3059               xfree (pinvalue);
3060               return err;
3061             }
3062
3063           i = 0;
3064           paddedpin[i++] = 0x20 | (ndigits & 0x0f);
3065           for (s=pinvalue; i < aodf->stored_length && *s && s[1]; s = s+2 )
3066             paddedpin[i++] = (((*s - '0') << 4) | ((s[1] - '0') & 0x0f));
3067           if (i < aodf->stored_length && *s)
3068             paddedpin[i++] = (((*s - '0') << 4)
3069                               |((aodf->pad_char_valid?aodf->pad_char:0)&0x0f));
3070
3071           if (aodf->pinflags.needs_padding)
3072             while (i < aodf->stored_length)
3073               paddedpin[i++] = aodf->pad_char_valid? aodf->pad_char : 0;
3074
3075           xfree (pinvalue);
3076           pinvalue = paddedpin;
3077           pinvaluelen = i;
3078         }
3079       else if (aodf->pinflags.needs_padding)
3080         {
3081           char *paddedpin;
3082
3083           paddedpin = xtrymalloc (aodf->stored_length+1);
3084           if (!paddedpin)
3085             {
3086               err = gpg_error_from_syserror ();
3087               xfree (pinvalue);
3088               return err;
3089             }
3090           for (i=0, s=pinvalue; i < aodf->stored_length && *s; i++, s++)
3091             paddedpin[i] = *s;
3092           /* Not sure what padding char to use if none has been set.
3093              For now we use 0x00; maybe a space would be better. */
3094           for (; i < aodf->stored_length; i++)
3095             paddedpin[i] = aodf->pad_char_valid? aodf->pad_char : 0;
3096           paddedpin[i] = 0;
3097           pinvaluelen = i;
3098           xfree (pinvalue);
3099           pinvalue = paddedpin;
3100         }
3101       else
3102         pinvaluelen = strlen (pinvalue);
3103
3104       err = iso7816_verify (app->slot,
3105                             aodf->pin_reference_valid? aodf->pin_reference : 0,
3106                             pinvalue, pinvaluelen);
3107       xfree (pinvalue);
3108       if (err)
3109         {
3110           log_error ("PIN verification failed: %s\n", gpg_strerror (err));
3111           return err;
3112         }
3113       log_debug ("PIN verification succeeded\n");
3114     }
3115
3116   /* Prepare the DER object from INDATA. */
3117   if (indatalen == 36)
3118     {
3119       /* No ASN.1 container used. */
3120       if (hashalgo != MD_USER_TLS_MD5SHA1)
3121         return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3122       memcpy (data, indata, indatalen);
3123     }
3124   else if (indatalen == 35)
3125     {
3126       /* Alright, the caller was so kind to send us an already
3127          prepared DER object.  Check that it is what we want and that
3128          it matches the hash algorithm. */
3129       if (hashalgo == GCRY_MD_SHA1 && !memcmp (indata, sha1_prefix, 15))
3130         ;
3131       else if (hashalgo == GCRY_MD_RMD160
3132                && !memcmp (indata, rmd160_prefix, 15))
3133         ;
3134       else
3135         return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3136       memcpy (data, indata, indatalen);
3137     }
3138   else
3139     {
3140       /* Need to prepend the prefix. */
3141       if (hashalgo == GCRY_MD_SHA1)
3142         memcpy (data, sha1_prefix, 15);
3143       else if (hashalgo == GCRY_MD_RMD160)
3144         memcpy (data, rmd160_prefix, 15);
3145       else
3146         return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3147       memcpy (data+15, indata, indatalen);
3148     }
3149
3150   /* Manage security environment needs to be weaked for certain cards. */
3151   if (mse_done)
3152     err = 0;
3153   else if (app->app_local->card_type == CARD_TYPE_TCOS)
3154     {
3155       /* TCOS creates signatures always using the local key 0.  MSE
3156          may not be used. */
3157     }
3158   else if (app->app_local->card_type == CARD_TYPE_MICARDO)
3159     {
3160       if (!prkdf->pathlen)
3161         err = gpg_error (GPG_ERR_BUG);
3162       else
3163         err = micardo_mse (app, prkdf->path[prkdf->pathlen-1]);
3164     }
3165   else if (prkdf->key_reference_valid)
3166     {
3167       unsigned char mse[3];
3168
3169       mse[0] = 0x84; /* Select asym. key. */
3170       mse[1] = 1;
3171       mse[2] = prkdf->key_reference;
3172
3173       err = iso7816_manage_security_env (app->slot,
3174                                          0x41, 0xB6,
3175                                          mse, sizeof mse);
3176     }
3177   if (err)
3178     {
3179       log_error ("MSE failed: %s\n", gpg_strerror (err));
3180       return err;
3181     }
3182
3183   if (hashalgo == MD_USER_TLS_MD5SHA1)
3184     err = iso7816_compute_ds (app->slot, 0, data, 36, 0, outdata, outdatalen);
3185   else if (no_data_padding)
3186     err = iso7816_compute_ds (app->slot, 0, data+15, 20, 0,outdata,outdatalen);
3187   else
3188     err = iso7816_compute_ds (app->slot, 0, data, 35, 0, outdata, outdatalen);
3189   return err;
3190 }
3191
3192
3193 /* Handler for the PKAUTH command.
3194
3195    This is basically the same as the PKSIGN command but we first check
3196    that the requested key is suitable for authentication; that is, it
3197    must match the criteria used for the attribute $AUTHKEYID.  See
3198    do_sign for calling conventions; there is no HASHALGO, though. */
3199 static gpg_error_t
3200 do_auth (app_t app, const char *keyidstr,
3201          gpg_error_t (*pincb)(void*, const char *, char **),
3202          void *pincb_arg,
3203          const void *indata, size_t indatalen,
3204          unsigned char **outdata, size_t *outdatalen )
3205 {
3206   gpg_error_t err;
3207   prkdf_object_t prkdf;
3208   int algo;
3209
3210   if (!keyidstr || !*keyidstr)
3211     return gpg_error (GPG_ERR_INV_VALUE);
3212
3213   err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
3214   if (err)
3215     return err;
3216   if (!prkdf->usageflags.sign)
3217     {
3218       log_error ("key %s may not be used for authentication\n", keyidstr);
3219       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
3220     }
3221
3222   algo = indatalen == 36? MD_USER_TLS_MD5SHA1 : GCRY_MD_SHA1;
3223   return do_sign (app, keyidstr, algo, pincb, pincb_arg,
3224                   indata, indatalen, outdata, outdatalen);
3225 }
3226
3227
3228 \f
3229 /* Assume that EF(DIR) has been selected.  Read its content and figure
3230    out the home EF of pkcs#15.  Return that home DF or 0 if not found
3231    and the value at the address of BELPIC indicates whether it was
3232    found by the belpic aid. */
3233 static unsigned short
3234 read_home_df (int slot, int *r_belpic)
3235 {
3236   gpg_error_t err;
3237   unsigned char *buffer;
3238   const unsigned char *p, *pp;
3239   size_t buflen, n, nn;
3240   unsigned short result = 0;
3241
3242   *r_belpic = 0;
3243
3244   err = iso7816_read_binary (slot, 0, 0, &buffer, &buflen);
3245   if (err)
3246     {
3247       log_error ("error reading EF{DIR}: %s\n", gpg_strerror (err));
3248       return 0;
3249     }
3250
3251   /* FIXME: We need to scan all records. */
3252   p = find_tlv (buffer, buflen, 0x61, &n);
3253   if (p && n)
3254     {
3255       pp = find_tlv (p, n, 0x4f, &nn);
3256       if (pp && ((nn == sizeof pkcs15_aid && !memcmp (pp, pkcs15_aid, nn))
3257                  || (*r_belpic = (nn == sizeof pkcs15be_aid
3258                                   && !memcmp (pp, pkcs15be_aid, nn)))))
3259         {
3260           pp = find_tlv (p, n, 0x50, &nn);
3261           if (pp) /* fixme: Filter log value? */
3262             log_info ("pkcs#15 application label from EF(DIR) is '%.*s'\n",
3263                       (int)nn, pp);
3264           pp = find_tlv (p, n, 0x51, &nn);
3265           if (pp && nn == 4 && *pp == 0x3f && !pp[1])
3266             {
3267               result = ((pp[2] << 8) | pp[3]);
3268               log_info ("pkcs#15 application directory is 0x%04hX\n", result);
3269             }
3270         }
3271     }
3272   xfree (buffer);
3273   return result;
3274 }
3275
3276
3277 /*
3278    Select the PKCS#15 application on the card in SLOT.
3279  */
3280 gpg_error_t
3281 app_select_p15 (app_t app)
3282 {
3283   int slot = app->slot;
3284   int rc;
3285   unsigned short def_home_df = 0;
3286   card_type_t card_type = CARD_TYPE_UNKNOWN;
3287   int direct = 0;
3288   int is_belpic = 0;
3289
3290   rc = iso7816_select_application (slot, pkcs15_aid, sizeof pkcs15_aid, 0);
3291   if (rc)
3292     { /* Not found: Try to locate it from 2F00.  We use direct path
3293          selection here because it seems that the Belgian eID card
3294          does only allow for that.  Many other cards supports this
3295          selection method too.  Note, that we don't use
3296          select_application above for the Belgian card - the call
3297          works but it seems that it did not switch to the correct DF.
3298          Using the 2f02 just works. */
3299       unsigned short path[1] = { 0x2f00 };
3300
3301       rc = iso7816_select_path (app->slot, path, 1);
3302       if (!rc)
3303         {
3304           direct = 1;
3305           def_home_df = read_home_df (slot, &is_belpic);
3306           if (def_home_df)
3307             {
3308               path[0] = def_home_df;
3309               rc = iso7816_select_path (app->slot, path, 1);
3310             }
3311         }
3312     }
3313   if (rc)
3314     { /* Still not found:  Try the default DF. */
3315       def_home_df = 0x5015;
3316       rc = iso7816_select_file (slot, def_home_df, 1);
3317     }
3318   if (!rc)
3319     {
3320       /* Determine the type of the card.  The general case is to look
3321          it up from the ATR table.  For the Belgian eID card we know
3322          it instantly from the AID. */
3323       if (is_belpic)
3324         {
3325           card_type = CARD_TYPE_BELPIC;
3326         }
3327       else
3328         {
3329           unsigned char *atr;
3330           size_t atrlen;
3331           int i;
3332
3333           atr = apdu_get_atr (app->slot, &atrlen);
3334           if (!atr)
3335             rc = gpg_error (GPG_ERR_INV_CARD);
3336           else
3337             {
3338               for (i=0; card_atr_list[i].atrlen; i++)
3339                 if (card_atr_list[i].atrlen == atrlen
3340                     && !memcmp (card_atr_list[i].atr, atr, atrlen))
3341                   {
3342                     card_type = card_atr_list[i].type;
3343                     break;
3344                   }
3345               xfree (atr);
3346             }
3347         }
3348     }
3349   if (!rc)
3350     {
3351       app->apptype = "P15";
3352
3353       app->app_local = xtrycalloc (1, sizeof *app->app_local);
3354       if (!app->app_local)
3355         {
3356           rc = gpg_error_from_syserror ();
3357           goto leave;
3358         }
3359
3360       /* Set the home DF.  Note that we currently can't do that if the
3361          selection via application ID worked.  This will store 0 there
3362          instead.  FIXME: We either need to figure the home_df via the
3363          DIR file or using the return values from the select file
3364          APDU. */
3365       app->app_local->home_df = def_home_df;
3366
3367       /* Store the card type.  FIXME: We might want to put this into
3368          the common APP structure. */
3369       app->app_local->card_type = card_type;
3370
3371       /* Store whether we may and should use direct path selection. */
3372       app->app_local->direct_path_selection = direct;
3373
3374       /* Read basic information and thus check whether this is a real
3375          card.  */
3376       rc = read_p15_info (app);
3377       if (rc)
3378         goto leave;
3379
3380       /* Special serial number munging.  We need to check for a German
3381          prototype card right here because we need to access to
3382          EF(TokenInfo).  We mark such a serial number by the using a
3383          prefix of FF0100. */
3384       if (app->serialnolen == 12
3385           && !memcmp (app->serialno, "\xD2\x76\0\0\0\0\0\0\0\0\0\0", 12))
3386         {
3387           /* This is a German card with a silly serial number.  Try to get
3388              the serial number from the EF(TokenInfo). . */
3389           unsigned char *p;
3390
3391           /* FIXME: actually get it from EF(TokenInfo). */
3392
3393           p = xtrymalloc (3 + app->serialnolen);
3394           if (!p)
3395             rc = gpg_error (gpg_err_code_from_errno (errno));
3396           else
3397             {
3398               memcpy (p, "\xff\x01", 3);
3399               memcpy (p+3, app->serialno, app->serialnolen);
3400               app->serialnolen += 3;
3401               xfree (app->serialno);
3402               app->serialno = p;
3403             }
3404         }
3405
3406       app->fnc.deinit = do_deinit;
3407       app->fnc.learn_status = do_learn_status;
3408       app->fnc.readcert = do_readcert;
3409       app->fnc.getattr = do_getattr;
3410       app->fnc.setattr = NULL;
3411       app->fnc.genkey = NULL;
3412       app->fnc.sign = do_sign;
3413       app->fnc.auth = do_auth;
3414       app->fnc.decipher = NULL;
3415       app->fnc.change_pin = NULL;
3416       app->fnc.check_pin = NULL;
3417
3418     leave:
3419       if (rc)
3420         do_deinit (app);
3421    }
3422
3423   return rc;
3424 }