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