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