2006-09-01 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / scd / app-p15.c
blob8a7732c85fea308933af74b39116cb6b4969a835
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 2 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, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
19 * USA.
22 /* Information pertaining to the BELPIC developer card samples:
24 Unblock PUK: "222222111111"
25 Reset PIN: "333333111111")
27 e.g. the APDUs 00:20:00:02:08:2C:33:33:33:11:11:11:FF
28 and 00:24:01:01:08:24:12:34:FF:FF:FF:FF:FF
29 should change the PIN into 1234.
32 #include <config.h>
33 #include <errno.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <assert.h>
38 #include <time.h>
40 #include "scdaemon.h"
42 #include "iso7816.h"
43 #include "app-common.h"
44 #include "tlv.h"
45 #include "apdu.h" /* fixme: we should move the card detection to a
46 separate file */
48 /* Types of cards we know and which needs special treatment. */
49 typedef enum
51 CARD_TYPE_UNKNOWN,
52 CARD_TYPE_TCOS,
53 CARD_TYPE_MICARDO,
54 CARD_TYPE_BELPIC /* Belgian eID card specs. */
56 card_type_t;
58 /* A list card types with ATRs noticed with these cards. */
59 #define X(a) ((unsigned char const *)(a))
60 static struct
62 size_t atrlen;
63 unsigned char const *atr;
64 card_type_t type;
65 } card_atr_list[] = {
66 { 19, X("\x3B\xBA\x13\x00\x81\x31\x86\x5D\x00\x64\x05\x0A\x02\x01\x31\x80"
67 "\x90\x00\x8B"),
68 CARD_TYPE_TCOS }, /* SLE44 */
69 { 19, X("\x3B\xBA\x14\x00\x81\x31\x86\x5D\x00\x64\x05\x14\x02\x02\x31\x80"
70 "\x90\x00\x91"),
71 CARD_TYPE_TCOS }, /* SLE66S */
72 { 19, X("\x3B\xBA\x96\x00\x81\x31\x86\x5D\x00\x64\x05\x60\x02\x03\x31\x80"
73 "\x90\x00\x66"),
74 CARD_TYPE_TCOS }, /* SLE66P */
75 { 27, X("\x3B\xFF\x94\x00\xFF\x80\xB1\xFE\x45\x1F\x03\x00\x68\xD2\x76\x00"
76 "\x00\x28\xFF\x05\x1E\x31\x80\x00\x90\x00\x23"),
77 CARD_TYPE_MICARDO }, /* German BMI card */
78 { 19, X("\x3B\x6F\x00\xFF\x00\x68\xD2\x76\x00\x00\x28\xFF\x05\x1E\x31\x80"
79 "\x00\x90\x00"),
80 CARD_TYPE_MICARDO }, /* German BMI card (ATR due to reader problem) */
81 { 26, X("\x3B\xFE\x94\x00\xFF\x80\xB1\xFA\x45\x1F\x03\x45\x73\x74\x45\x49"
82 "\x44\x20\x76\x65\x72\x20\x31\x2E\x30\x43"),
83 CARD_TYPE_MICARDO }, /* EstEID (Estonian Big Brother card) */
85 { 0 }
87 #undef X
90 /* The AID of PKCS15. */
91 static char const pkcs15_aid[] = { 0xA0, 0, 0, 0, 0x63,
92 0x50, 0x4B, 0x43, 0x53, 0x2D, 0x31, 0x35 };
94 /* The Belgian eID variant - they didn't understood why a shared AID
95 is useful for a standard. Oh well. */
96 static char const pkcs15be_aid[] = { 0xA0, 0, 0, 0x01, 0x77,
97 0x50, 0x4B, 0x43, 0x53, 0x2D, 0x31, 0x35 };
100 /* The PIN types as defined in pkcs#15 v1.1 */
101 typedef enum
103 PIN_TYPE_BCD = 0,
104 PIN_TYPE_ASCII_NUMERIC = 1,
105 PIN_TYPE_UTF8 = 2,
106 PIN_TYPE_HALF_NIBBLE_BCD = 3,
107 PIN_TYPE_ISO9564_1 = 4
108 } pin_type_t;
111 /* A bit array with for the key usage flags from the
112 commonKeyAttributes. */
113 struct keyusage_flags_s
115 unsigned int encrypt: 1;
116 unsigned int decrypt: 1;
117 unsigned int sign: 1;
118 unsigned int sign_recover: 1;
119 unsigned int wrap: 1;
120 unsigned int unwrap: 1;
121 unsigned int verify: 1;
122 unsigned int verify_recover: 1;
123 unsigned int derive: 1;
124 unsigned int non_repudiation: 1;
126 typedef struct keyusage_flags_s keyusage_flags_t;
130 /* This is an object to store information about a Certificate
131 Directory File (CDF) in a format suitable for further processing by
132 us. To keep memory management, simple we use a linked list of
133 items; i.e. one such object represents one certificate and the list
134 the entire CDF. */
135 struct cdf_object_s
137 /* Link to next item when used in a linked list. */
138 struct cdf_object_s *next;
140 /* Length and allocated buffer with the Id of this object. */
141 size_t objidlen;
142 unsigned char *objid;
144 /* To avoid reading a certificate more than once, we cache it in an
145 allocated memory IMAGE of IMAGELEN. */
146 size_t imagelen;
147 unsigned char *image;
149 /* Set to true if a length and offset is available. */
150 int have_off;
151 /* The offset and length of the object. They are only valid if
152 HAVE_OFF is true and set to 0 if HAVE_OFF is false. */
153 unsigned long off, len;
155 /* The length of the path as given in the CDF and the path itself.
156 path[0] is the top DF (usually 0x3f00). The path will never be
157 empty. */
158 size_t pathlen;
159 unsigned short path[1];
161 typedef struct cdf_object_s *cdf_object_t;
164 /* This is an object to store information about a Private Key
165 Directory File (PrKDF) in a format suitable for further processing
166 by us. To keep memory management, simple we use a linked list of
167 items; i.e. one such object represents one certificate and the list
168 the entire PrKDF. */
169 struct prkdf_object_s
171 /* Link to next item when used in a linked list. */
172 struct prkdf_object_s *next;
174 /* Length and allocated buffer with the Id of this object. */
175 size_t objidlen;
176 unsigned char *objid;
178 /* Length and allocated buffer with the authId of this object or
179 NULL if no authID is known. */
180 size_t authidlen;
181 unsigned char *authid;
183 /* The key's usage flags. */
184 keyusage_flags_t usageflags;
186 /* The keyReference and a flag telling whether it is valid. */
187 unsigned long key_reference;
188 int key_reference_valid;
190 /* Set to true if a length and offset is available. */
191 int have_off;
192 /* The offset and length of the object. They are only valid if
193 HAVE_OFF is true and set to 0 if HAVE_OFF is false. */
194 unsigned long off, len;
196 /* The length of the path as given in the PrKDF and the path itself.
197 path[0] is the top DF (usually 0x3f00). */
198 size_t pathlen;
199 unsigned short path[1];
201 typedef struct prkdf_object_s *prkdf_object_t;
204 /* This is an object to store information about a Authentication
205 Object Directory File (AODF) in a format suitable for further
206 processing by us. To keep memory management, simple we use a linked
207 list of items; i.e. one such object represents one authentication
208 object and the list the entire AOKDF. */
209 struct aodf_object_s
211 /* Link to next item when used in a linked list. */
212 struct aodf_object_s *next;
214 /* Length and allocated buffer with the Id of this object. */
215 size_t objidlen;
216 unsigned char *objid;
218 /* Length and allocated buffer with the authId of this object or
219 NULL if no authID is known. */
220 size_t authidlen;
221 unsigned char *authid;
223 /* The PIN Flags. */
224 struct
226 unsigned int case_sensitive: 1;
227 unsigned int local: 1;
228 unsigned int change_disabled: 1;
229 unsigned int unblock_disabled: 1;
230 unsigned int initialized: 1;
231 unsigned int needs_padding: 1;
232 unsigned int unblocking_pin: 1;
233 unsigned int so_pin: 1;
234 unsigned int disable_allowed: 1;
235 unsigned int integrity_protected: 1;
236 unsigned int confidentiality_protected: 1;
237 unsigned int exchange_ref_data: 1;
238 } pinflags;
240 /* The PIN Type. */
241 pin_type_t pintype;
243 /* The minimum length of a PIN. */
244 unsigned long min_length;
246 /* The stored length of a PIN. */
247 unsigned long stored_length;
249 /* The maximum length of a PIN and a flag telling whether it is valid. */
250 unsigned long max_length;
251 int max_length_valid;
253 /* The pinReference and a flag telling whether it is valid. */
254 unsigned long pin_reference;
255 int pin_reference_valid;
257 /* The padChar and a flag telling whether it is valid. */
258 char pad_char;
259 int pad_char_valid;
262 /* Set to true if a length and offset is available. */
263 int have_off;
264 /* The offset and length of the object. They are only valid if
265 HAVE_OFF is true and set to 0 if HAVE_OFF is false. */
266 unsigned long off, len;
268 /* The length of the path as given in the Aodf and the path itself.
269 path[0] is the top DF (usually 0x3f00). PATH is optional and thus
270 may be NULL. Malloced.*/
271 size_t pathlen;
272 unsigned short *path;
274 typedef struct aodf_object_s *aodf_object_t;
277 /* Context local to this application. */
278 struct app_local_s
280 /* The home DF. Note, that we don't yet support a multilevel
281 hierachy. Thus we assume this is directly below the MF. */
282 unsigned short home_df;
284 /* The type of the card. */
285 card_type_t card_type;
287 /* Flag indicating whether we may use direct path selection. */
288 int direct_path_selection;
290 /* Structure with the EFIDs of the objects described in the ODF
291 file. */
292 struct
294 unsigned short private_keys;
295 unsigned short public_keys;
296 unsigned short trusted_public_keys;
297 unsigned short secret_keys;
298 unsigned short certificates;
299 unsigned short trusted_certificates;
300 unsigned short useful_certificates;
301 unsigned short data_objects;
302 unsigned short auth_objects;
303 } odf;
305 /* The PKCS#15 serialnumber from EF(TokeiNFo) or NULL. Malloced. */
306 unsigned char *serialno;
307 size_t serialnolen;
309 /* Information on all certificates. */
310 cdf_object_t certificate_info;
311 /* Information on all trusted certificates. */
312 cdf_object_t trusted_certificate_info;
313 /* Information on all useful certificates. */
314 cdf_object_t useful_certificate_info;
316 /* Information on all private keys. */
317 prkdf_object_t private_key_info;
319 /* Information on all authentication objects. */
320 aodf_object_t auth_object_info;
325 /*** Local prototypes. ***/
326 static gpg_error_t readcert_by_cdf (app_t app, cdf_object_t cdf,
327 unsigned char **r_cert, size_t *r_certlen);
331 /* Release the CDF object A */
332 static void
333 release_cdflist (cdf_object_t a)
335 while (a)
337 cdf_object_t tmp = a->next;
338 xfree (a->image);
339 xfree (a->objid);
340 xfree (a);
341 a = tmp;
345 /* Release the PrKDF object A. */
346 static void
347 release_prkdflist (prkdf_object_t a)
349 while (a)
351 prkdf_object_t tmp = a->next;
352 xfree (a->objid);
353 xfree (a->authid);
354 xfree (a);
355 a = tmp;
359 /* Release just one aodf object. */
360 void
361 release_aodf_object (aodf_object_t a)
363 if (a)
365 xfree (a->objid);
366 xfree (a->authid);
367 xfree (a->path);
368 xfree (a);
372 /* Release the AODF list A. */
373 static void
374 release_aodflist (aodf_object_t a)
376 while (a)
378 aodf_object_t tmp = a->next;
379 release_aodf_object (a);
380 a = tmp;
385 /* Release all local resources. */
386 static void
387 do_deinit (app_t app)
389 if (app && app->app_local)
391 release_cdflist (app->app_local->certificate_info);
392 release_cdflist (app->app_local->trusted_certificate_info);
393 release_cdflist (app->app_local->useful_certificate_info);
394 release_prkdflist (app->app_local->private_key_info);
395 release_aodflist (app->app_local->auth_object_info);
396 xfree (app->app_local->serialno);
397 xfree (app->app_local);
398 app->app_local = NULL;
404 /* Do a select and a read for the file with EFID. EFID_DESC is a
405 desctription of the EF to be used with error messages. On success
406 BUFFER and BUFLEN contain the entire content of the EF. The caller
407 must free BUFFER only on success. */
408 static gpg_error_t
409 select_and_read_binary (int slot, unsigned short efid, const char *efid_desc,
410 unsigned char **buffer, size_t *buflen)
412 gpg_error_t err;
414 err = iso7816_select_file (slot, efid, 0, NULL, NULL);
415 if (err)
417 log_error ("error selecting %s (0x%04X): %s\n",
418 efid_desc, efid, gpg_strerror (err));
419 return err;
421 err = iso7816_read_binary (slot, 0, 0, buffer, buflen);
422 if (err)
424 log_error ("error reading %s (0x%04X): %s\n",
425 efid_desc, efid, gpg_strerror (err));
426 return err;
428 return 0;
432 /* This function calls select file to read a file using a complete
433 path which may or may not start at the master file (MF). */
434 static gpg_error_t
435 select_ef_by_path (app_t app, const unsigned short *path, size_t pathlen)
437 gpg_error_t err;
438 int i, j;
440 if (!pathlen)
441 return gpg_error (GPG_ERR_INV_VALUE);
443 if (pathlen && *path != 0x3f00 )
444 log_debug ("WARNING: relative path selection not yet implemented\n");
446 if (app->app_local->direct_path_selection)
448 err = iso7816_select_path (app->slot, path+1, pathlen-1, NULL, NULL);
449 if (err)
451 log_error ("error selecting path ");
452 for (j=0; j < pathlen; j++)
453 log_printf ("%04hX", path[j]);
454 log_printf (": %s\n", gpg_strerror (err));
455 return err;
458 else
460 /* FIXME: Need code to remember the last PATH so that we can decide
461 what select commands to send in case the path does not start off
462 with 3F00. We might also want to use direct path selection if
463 supported by the card. */
464 for (i=0; i < pathlen; i++)
466 err = iso7816_select_file (app->slot, path[i],
467 !(i+1 == pathlen), NULL, NULL);
468 if (err)
470 log_error ("error selecting part %d from path ", i);
471 for (j=0; j < pathlen; j++)
472 log_printf ("%04hX", path[j]);
473 log_printf (": %s\n", gpg_strerror (err));
474 return err;
478 return 0;
481 /* Parse a cert Id string (or a key Id string) and return the binary
482 object Id string in a newly allocated buffer stored at R_OBJID and
483 R_OBJIDLEN. On Error NULL will be stored there and an error code
484 returned. On success caller needs to free the buffer at R_OBJID. */
485 static gpg_error_t
486 parse_certid (app_t app, const char *certid,
487 unsigned char **r_objid, size_t *r_objidlen)
489 char tmpbuf[10];
490 const char *s;
491 size_t objidlen;
492 unsigned char *objid;
493 int i;
495 *r_objid = NULL;
496 *r_objidlen = 0;
498 if (app->app_local->home_df)
499 sprintf (tmpbuf, "P15-%04hX.", (app->app_local->home_df & 0xffff));
500 else
501 strcpy (tmpbuf, "P15.");
502 if (strncmp (certid, tmpbuf, strlen (tmpbuf)) )
504 if (!strncmp (certid, "P15.", 4)
505 || (!strncmp (certid, "P15-", 4)
506 && hexdigitp (certid+4)
507 && hexdigitp (certid+5)
508 && hexdigitp (certid+6)
509 && hexdigitp (certid+7)
510 && certid[8] == '.'))
511 return gpg_error (GPG_ERR_NOT_FOUND);
512 return gpg_error (GPG_ERR_INV_ID);
514 certid += strlen (tmpbuf);
516 for (s=certid, objidlen=0; hexdigitp (s); s++, objidlen++)
518 if (*s || !objidlen || (objidlen%2))
519 return gpg_error (GPG_ERR_INV_ID);
520 objidlen /= 2;
521 objid = xtrymalloc (objidlen);
522 if (!objid)
523 return gpg_error_from_errno (errno);
524 for (s=certid, i=0; i < objidlen; i++, s+=2)
525 objid[i] = xtoi_2 (s);
526 *r_objid = objid;
527 *r_objidlen = objidlen;
528 return 0;
532 /* Find a certificate object by the certificate ID CERTID and store a
533 pointer to it at R_CDF. */
534 static gpg_error_t
535 cdf_object_from_certid (app_t app, const char *certid, cdf_object_t *r_cdf)
537 gpg_error_t err;
538 size_t objidlen;
539 unsigned char *objid;
540 cdf_object_t cdf;
542 err = parse_certid (app, certid, &objid, &objidlen);
543 if (err)
544 return err;
546 for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
547 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
548 break;
549 if (!cdf)
550 for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
551 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
552 break;
553 if (!cdf)
554 for (cdf = app->app_local->useful_certificate_info; cdf; cdf = cdf->next)
555 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
556 break;
557 xfree (objid);
558 if (!cdf)
559 return gpg_error (GPG_ERR_NOT_FOUND);
560 *r_cdf = cdf;
561 return 0;
565 /* Find a private key object by the key Id string KEYIDSTR and store a
566 pointer to it at R_PRKDF. */
567 static gpg_error_t
568 prkdf_object_from_keyidstr (app_t app, const char *keyidstr,
569 prkdf_object_t *r_prkdf)
571 gpg_error_t err;
572 size_t objidlen;
573 unsigned char *objid;
574 prkdf_object_t prkdf;
576 err = parse_certid (app, keyidstr, &objid, &objidlen);
577 if (err)
578 return err;
580 for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
581 if (prkdf->objidlen == objidlen && !memcmp (prkdf->objid, objid, objidlen))
582 break;
583 xfree (objid);
584 if (!prkdf)
585 return gpg_error (GPG_ERR_NOT_FOUND);
586 *r_prkdf = prkdf;
587 return 0;
593 /* Read and parse the Object Directory File and store away the
594 pointers. ODF_FID shall contain the FID of the ODF.
596 Example of such a file:
598 A0 06 30 04 04 02 60 34 = Private Keys
599 A4 06 30 04 04 02 60 35 = Certificates
600 A5 06 30 04 04 02 60 36 = TrustedCertificates
601 A7 06 30 04 04 02 60 37 = DataObjects
602 A8 06 30 04 04 02 60 38 = AuthObjects
604 These are all PathOrObjects using the path CHOICE element. The
605 paths are octet strings of length 2. Using this Path CHOICE
606 element is recommended, so we only implement that for now.
608 static gpg_error_t
609 read_ef_odf (app_t app, unsigned short odf_fid)
611 gpg_error_t err;
612 unsigned char *buffer, *p;
613 size_t buflen;
614 unsigned short value;
615 size_t offset;
617 err = select_and_read_binary (app->slot, odf_fid, "ODF", &buffer, &buflen);
618 if (err)
619 return err;
621 if (buflen < 8)
623 log_error ("error: ODF too short\n");
624 xfree (buffer);
625 return gpg_error (GPG_ERR_INV_OBJ);
627 p = buffer;
628 while (buflen && *p && *p != 0xff)
630 if ( buflen >= 8
631 && (p[0] & 0xf0) == 0xA0
632 && !memcmp (p+1, "\x06\x30\x04\x04\x02", 5) )
634 offset = 6;
636 else if ( buflen >= 12
637 && (p[0] & 0xf0) == 0xA0
638 && !memcmp (p+1, "\x0a\x30\x08\x04\x06\x3F\x00", 7)
639 && app->app_local->home_df == ((p[8]<<8)|p[9]) )
641 /* We only allow a full path if all files are at the same
642 level and below the home directory. The extend this we
643 would need to make use of new data type capable of
644 keeping a full path. */
645 offset = 10;
647 else
649 log_error ("ODF format is not supported by us\n");
650 xfree (buffer);
651 return gpg_error (GPG_ERR_INV_OBJ);
653 switch ((p[0] & 0x0f))
655 case 0: value = app->app_local->odf.private_keys; break;
656 case 1: value = app->app_local->odf.public_keys; break;
657 case 2: value = app->app_local->odf.trusted_public_keys; break;
658 case 3: value = app->app_local->odf.secret_keys; break;
659 case 4: value = app->app_local->odf.certificates; break;
660 case 5: value = app->app_local->odf.trusted_certificates; break;
661 case 6: value = app->app_local->odf.useful_certificates; break;
662 case 7: value = app->app_local->odf.data_objects; break;
663 case 8: value = app->app_local->odf.auth_objects; break;
664 default: value = 0; break;
666 if (value)
668 log_error ("duplicate object type %d in ODF ignored\n",(p[0]&0x0f));
669 continue;
671 value = ((p[offset] << 8) | p[offset+1]);
672 switch ((p[0] & 0x0f))
674 case 0: app->app_local->odf.private_keys = value; break;
675 case 1: app->app_local->odf.public_keys = value; break;
676 case 2: app->app_local->odf.trusted_public_keys = value; break;
677 case 3: app->app_local->odf.secret_keys = value; break;
678 case 4: app->app_local->odf.certificates = value; break;
679 case 5: app->app_local->odf.trusted_certificates = value; break;
680 case 6: app->app_local->odf.useful_certificates = value; break;
681 case 7: app->app_local->odf.data_objects = value; break;
682 case 8: app->app_local->odf.auth_objects = value; break;
683 default:
684 log_error ("unknown object type %d in ODF ignored\n", (p[0]&0x0f));
686 offset += 2;
688 if (buflen < offset)
689 break;
690 p += offset;
691 buflen -= offset;
694 if (buflen)
695 log_info ("warning: %u bytes of garbage detected at end of ODF\n", buflen);
697 xfree (buffer);
698 return 0;
702 /* Parse the BIT STRING with the keyUsageFlags from teh
703 CommonKeyAttributes. */
704 static gpg_error_t
705 parse_keyusage_flags (const unsigned char *der, size_t derlen,
706 keyusage_flags_t *usageflags)
708 unsigned int bits, mask;
709 int i, unused, full;
711 memset (usageflags, 0, sizeof *usageflags);
712 if (!derlen)
713 return gpg_error (GPG_ERR_INV_OBJ);
715 unused = *der++; derlen--;
716 if ((!derlen && unused) || unused/8 > derlen)
717 return gpg_error (GPG_ERR_ENCODING_PROBLEM);
718 full = derlen - (unused+7)/8;
719 unused %= 8;
720 mask = 0;
721 for (i=1; unused; i <<= 1, unused--)
722 mask |= i;
724 /* First octet */
725 if (derlen)
727 bits = *der++; derlen--;
728 if (full)
729 full--;
730 else
732 bits &= ~mask;
733 mask = 0;
736 else
737 bits = 0;
738 if ((bits & 0x80)) usageflags->encrypt = 1;
739 if ((bits & 0x40)) usageflags->decrypt = 1;
740 if ((bits & 0x20)) usageflags->sign = 1;
741 if ((bits & 0x10)) usageflags->sign_recover = 1;
742 if ((bits & 0x08)) usageflags->wrap = 1;
743 if ((bits & 0x04)) usageflags->unwrap = 1;
744 if ((bits & 0x02)) usageflags->verify = 1;
745 if ((bits & 0x01)) usageflags->verify_recover = 1;
747 /* Second octet. */
748 if (derlen)
750 bits = *der++; derlen--;
751 if (full)
752 full--;
753 else
755 bits &= ~mask;
756 mask = 0;
759 else
760 bits = 0;
761 if ((bits & 0x80)) usageflags->derive = 1;
762 if ((bits & 0x40)) usageflags->non_repudiation = 1;
764 return 0;
767 /* Read and parse the Private Key Directory Files. */
769 6034 (privatekeys)
771 30 33 30 11 0C 08 53 4B 2E 43 48 2E 44 53 03 02 030...SK.CH.DS..
772 06 80 04 01 07 30 0C 04 01 01 03 03 06 00 40 02 .....0........@.
773 02 00 50 A1 10 30 0E 30 08 04 06 3F 00 40 16 00 ..P..0.0...?.@..
774 50 02 02 04 00 30 33 30 11 0C 08 53 4B 2E 43 48 P....030...SK.CH
775 2E 4B 45 03 02 06 80 04 01 0A 30 0C 04 01 0C 03 .KE.......0.....
776 03 06 44 00 02 02 00 52 A1 10 30 0E 30 08 04 06 ..D....R..0.0...
777 3F 00 40 16 00 52 02 02 04 00 30 34 30 12 0C 09 ?.@..R....040...
778 53 4B 2E 43 48 2E 41 55 54 03 02 06 80 04 01 0A SK.CH.AUT.......
779 30 0C 04 01 0D 03 03 06 20 00 02 02 00 51 A1 10 0....... ....Q..
780 30 0E 30 08 04 06 3F 00 40 16 00 51 02 02 04 00 0.0...?.@..Q....
781 30 37 30 15 0C 0C 53 4B 2E 43 48 2E 44 53 2D 53 070...SK.CH.DS-S
782 50 58 03 02 06 80 04 01 0A 30 0C 04 01 02 03 03 PX.......0......
783 06 20 00 02 02 00 53 A1 10 30 0E 30 08 04 06 3F . ....S..0.0...?
784 00 40 16 00 53 02 02 04 00 00 00 00 00 00 00 00 .@..S...........
785 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
786 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
788 0 30 51: SEQUENCE {
789 2 30 17: SEQUENCE { -- commonObjectAttributes
790 4 0C 8: UTF8String 'SK.CH.DS'
791 14 03 2: BIT STRING 6 unused bits
792 : '01'B (bit 0)
793 18 04 1: OCTET STRING --authid
794 : 07
796 21 30 12: SEQUENCE { -- commonKeyAttributes
797 23 04 1: OCTET STRING
798 : 01
799 26 03 3: BIT STRING 6 unused bits
800 : '1000000000'B (bit 9)
801 31 02 2: INTEGER 80 -- keyReference (optional)
803 35 A1 16: [1] { -- keyAttributes
804 37 30 14: SEQUENCE { -- privateRSAKeyAttributes
805 39 30 8: SEQUENCE { -- objectValue
806 41 04 6: OCTET STRING --path
807 : 3F 00 40 16 00 50
809 49 02 2: INTEGER 1024 -- modulus
816 static gpg_error_t
817 read_ef_prkdf (app_t app, unsigned short fid, prkdf_object_t *result)
819 gpg_error_t err;
820 unsigned char *buffer = NULL;
821 size_t buflen;
822 const unsigned char *p;
823 size_t n, objlen, hdrlen;
824 int class, tag, constructed, ndef;
825 prkdf_object_t prkdflist = NULL;
826 int i;
828 if (!fid)
829 return gpg_error (GPG_ERR_NO_DATA); /* No private keys. */
831 err = select_and_read_binary (app->slot, fid, "PrKDF", &buffer, &buflen);
832 if (err)
833 return err;
835 p = buffer;
836 n = buflen;
838 /* FIXME: This shares a LOT of code with read_ef_cdf! */
840 /* Loop over the records. We stop as soon as we detect a new record
841 starting with 0x00 or 0xff as these values are commonly used to
842 pad data blocks and are no valid ASN.1 encoding. */
843 while (n && *p && *p != 0xff)
845 const unsigned char *pp;
846 size_t nn;
847 int where;
848 const char *errstr = NULL;
849 prkdf_object_t prkdf = NULL;
850 unsigned long ul;
851 const unsigned char *objid;
852 size_t objidlen;
853 const unsigned char *authid = NULL;
854 size_t authidlen = 0;
855 keyusage_flags_t usageflags;
856 unsigned long key_reference = 0;
857 int key_reference_valid = 0;
858 const char *s;
860 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
861 &ndef, &objlen, &hdrlen);
862 if (!err && (objlen > n || tag != TAG_SEQUENCE))
863 err = gpg_error (GPG_ERR_INV_OBJ);
864 if (err)
866 log_error ("error parsing PrKDF record: %s\n", gpg_strerror (err));
867 goto leave;
869 pp = p;
870 nn = objlen;
871 p += objlen;
872 n -= objlen;
874 /* Parse the commonObjectAttributes. */
875 where = __LINE__;
876 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
877 &ndef, &objlen, &hdrlen);
878 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
879 err = gpg_error (GPG_ERR_INV_OBJ);
880 if (err)
881 goto parse_error;
883 const unsigned char *ppp = pp;
884 size_t nnn = objlen;
886 pp += objlen;
887 nn -= objlen;
889 /* Search the optional AuthId. We need to skip the optional
890 Label (UTF8STRING) and the optional CommonObjectFlags
891 (BITSTRING). */
892 where = __LINE__;
893 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
894 &ndef, &objlen, &hdrlen);
895 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
896 err = gpg_error (GPG_ERR_INV_OBJ);
897 if (gpg_err_code (err) == GPG_ERR_EOF)
898 goto no_authid;
899 if (err)
900 goto parse_error;
901 if (tag == TAG_UTF8_STRING)
903 ppp += objlen; /* Skip the Label. */
904 nnn -= objlen;
906 where = __LINE__;
907 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
908 &ndef, &objlen, &hdrlen);
909 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
910 err = gpg_error (GPG_ERR_INV_OBJ);
911 if (gpg_err_code (err) == GPG_ERR_EOF)
912 goto no_authid;
913 if (err)
914 goto parse_error;
916 if (tag == TAG_BIT_STRING)
918 ppp += objlen; /* Skip the CommonObjectFlags. */
919 nnn -= objlen;
921 where = __LINE__;
922 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
923 &ndef, &objlen, &hdrlen);
924 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
925 err = gpg_error (GPG_ERR_INV_OBJ);
926 if (gpg_err_code (err) == GPG_ERR_EOF)
927 goto no_authid;
928 if (err)
929 goto parse_error;
931 if (tag == TAG_OCTET_STRING && objlen)
933 authid = ppp;
934 authidlen = objlen;
936 no_authid:
940 /* Parse the commonKeyAttributes. */
941 where = __LINE__;
942 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
943 &ndef, &objlen, &hdrlen);
944 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
945 err = gpg_error (GPG_ERR_INV_OBJ);
946 if (err)
947 goto parse_error;
949 const unsigned char *ppp = pp;
950 size_t nnn = objlen;
952 pp += objlen;
953 nn -= objlen;
955 /* Get the Id. */
956 where = __LINE__;
957 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
958 &ndef, &objlen, &hdrlen);
959 if (!err && (objlen > nnn
960 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
961 err = gpg_error (GPG_ERR_INV_OBJ);
962 if (err)
963 goto parse_error;
964 objid = ppp;
965 objidlen = objlen;
966 ppp += objlen;
967 nnn -= objlen;
969 /* Get the KeyUsageFlags. */
970 where = __LINE__;
971 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
972 &ndef, &objlen, &hdrlen);
973 if (!err && (objlen > nnn
974 || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
975 err = gpg_error (GPG_ERR_INV_OBJ);
976 if (err)
977 goto parse_error;
978 err = parse_keyusage_flags (ppp, objlen, &usageflags);
979 if (err)
980 goto parse_error;
981 ppp += objlen;
982 nnn -= objlen;
984 /* Find the keyReference */
985 where = __LINE__;
986 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
987 &ndef, &objlen, &hdrlen);
988 if (gpg_err_code (err) == GPG_ERR_EOF)
989 goto leave_cki;
990 if (!err && objlen > nnn)
991 err = gpg_error (GPG_ERR_INV_OBJ);
992 if (err)
993 goto parse_error;
994 if (class == CLASS_UNIVERSAL && tag == TAG_BOOLEAN)
996 /* Skip the native element. */
997 ppp += objlen;
998 nnn -= objlen;
1000 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1001 &ndef, &objlen, &hdrlen);
1002 if (gpg_err_code (err) == GPG_ERR_EOF)
1003 goto leave_cki;
1004 if (!err && objlen > nnn)
1005 err = gpg_error (GPG_ERR_INV_OBJ);
1006 if (err)
1007 goto parse_error;
1009 if (class == CLASS_UNIVERSAL && tag == TAG_BIT_STRING)
1011 /* Skip the accessFlags. */
1012 ppp += objlen;
1013 nnn -= objlen;
1015 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1016 &ndef, &objlen, &hdrlen);
1017 if (gpg_err_code (err) == GPG_ERR_EOF)
1018 goto leave_cki;
1019 if (!err && objlen > nnn)
1020 err = gpg_error (GPG_ERR_INV_OBJ);
1021 if (err)
1022 goto parse_error;
1024 if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
1026 /* Yep, this is the keyReference. */
1027 for (ul=0; objlen; objlen--)
1029 ul <<= 8;
1030 ul |= (*ppp++) & 0xff;
1031 nnn--;
1033 key_reference = ul;
1034 key_reference_valid = 1;
1037 leave_cki:
1042 /* Skip subClassAttributes. */
1043 where = __LINE__;
1044 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1045 &ndef, &objlen, &hdrlen);
1046 if (!err && objlen > nn)
1047 err = gpg_error (GPG_ERR_INV_OBJ);
1048 if (err)
1049 goto parse_error;
1050 if (class == CLASS_CONTEXT && tag == 0)
1052 pp += objlen;
1053 nn -= objlen;
1055 where = __LINE__;
1056 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1057 &ndef, &objlen, &hdrlen);
1059 /* Parse the keyAttributes. */
1060 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1061 err = gpg_error (GPG_ERR_INV_OBJ);
1062 if (err)
1063 goto parse_error;
1064 nn = objlen;
1066 where = __LINE__;
1067 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1068 &ndef, &objlen, &hdrlen);
1069 if (!err && objlen > nn)
1070 err = gpg_error (GPG_ERR_INV_OBJ);
1071 if (err)
1072 goto parse_error;
1073 if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
1074 ; /* RSA */
1075 else if (class == CLASS_CONTEXT)
1077 switch (tag)
1079 case 0: errstr = "EC key objects are not supported"; break;
1080 case 1: errstr = "DH key objects are not supported"; break;
1081 case 2: errstr = "DSA key objects are not supported"; break;
1082 case 3: errstr = "KEA key objects are not supported"; break;
1083 default: errstr = "unknown privateKeyObject"; break;
1085 goto parse_error;
1087 else
1089 err = gpg_error (GPG_ERR_INV_OBJ);
1090 goto parse_error;
1093 nn = objlen;
1095 /* Check that the reference is a Path object. */
1096 where = __LINE__;
1097 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1098 &ndef, &objlen, &hdrlen);
1099 if (!err && objlen > nn)
1100 err = gpg_error (GPG_ERR_INV_OBJ);
1101 if (err)
1102 goto parse_error;
1103 if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
1105 errstr = "unsupported reference type";
1106 goto parse_error;
1108 nn = objlen;
1110 /* Parse the Path object. */
1111 where = __LINE__;
1112 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1113 &ndef, &objlen, &hdrlen);
1114 if (!err && objlen > nn)
1115 err = gpg_error (GPG_ERR_INV_OBJ);
1116 if (err)
1117 goto parse_error;
1119 /* Make sure that the next element is a non zero path and of
1120 even length (FID are two bytes each). */
1121 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
1122 || !objlen || (objlen & 1) )
1124 errstr = "invalid path reference";
1125 goto parse_error;
1127 /* Create a new PrKDF list item. */
1128 prkdf = xtrycalloc (1, (sizeof *prkdf
1129 - sizeof(unsigned short)
1130 + objlen/2 * sizeof(unsigned short)));
1131 if (!prkdf)
1133 err = gpg_error_from_errno (errno);
1134 goto leave;
1136 prkdf->objidlen = objidlen;
1137 prkdf->objid = xtrymalloc (objidlen);
1138 if (!prkdf->objid)
1140 err = gpg_error_from_errno (errno);
1141 xfree (prkdf);
1142 goto leave;
1144 memcpy (prkdf->objid, objid, objidlen);
1145 if (authid)
1147 prkdf->authidlen = authidlen;
1148 prkdf->authid = xtrymalloc (authidlen);
1149 if (!prkdf->authid)
1151 err = gpg_error_from_errno (errno);
1152 xfree (prkdf->objid);
1153 xfree (prkdf);
1154 goto leave;
1156 memcpy (prkdf->authid, authid, authidlen);
1159 prkdf->pathlen = objlen/2;
1160 for (i=0; i < prkdf->pathlen; i++, pp += 2, nn -= 2)
1161 prkdf->path[i] = ((pp[0] << 8) | pp[1]);
1163 prkdf->usageflags = usageflags;
1164 prkdf->key_reference = key_reference;
1165 prkdf->key_reference_valid = key_reference_valid;
1167 if (nn)
1169 /* An index and length follows. */
1170 prkdf->have_off = 1;
1171 where = __LINE__;
1172 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1173 &ndef, &objlen, &hdrlen);
1174 if (!err && (objlen > nn
1175 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1176 err = gpg_error (GPG_ERR_INV_OBJ);
1177 if (err)
1178 goto parse_error;
1180 for (ul=0; objlen; objlen--)
1182 ul <<= 8;
1183 ul |= (*pp++) & 0xff;
1184 nn--;
1186 prkdf->off = ul;
1188 where = __LINE__;
1189 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1190 &ndef, &objlen, &hdrlen);
1191 if (!err && (objlen > nn
1192 || class != CLASS_CONTEXT || tag != 0))
1193 err = gpg_error (GPG_ERR_INV_OBJ);
1194 if (err)
1195 goto parse_error;
1197 for (ul=0; objlen; objlen--)
1199 ul <<= 8;
1200 ul |= (*pp++) & 0xff;
1201 nn--;
1203 prkdf->len = ul;
1207 log_debug ("PrKDF %04hX: id=", fid);
1208 for (i=0; i < prkdf->objidlen; i++)
1209 log_printf ("%02X", prkdf->objid[i]);
1210 log_printf (" path=");
1211 for (i=0; i < prkdf->pathlen; i++)
1212 log_printf ("%04hX", prkdf->path[i]);
1213 if (prkdf->have_off)
1214 log_printf ("[%lu/%lu]", prkdf->off, prkdf->len);
1215 if (prkdf->authid)
1217 log_printf (" authid=");
1218 for (i=0; i < prkdf->authidlen; i++)
1219 log_printf ("%02X", prkdf->authid[i]);
1221 if (prkdf->key_reference_valid)
1222 log_printf (" keyref=0x%02lX", prkdf->key_reference);
1223 log_printf (" usage=");
1224 s = "";
1225 if (prkdf->usageflags.encrypt) log_printf ("%sencrypt", s), s = ",";
1226 if (prkdf->usageflags.decrypt) log_printf ("%sdecrypt", s), s = ",";
1227 if (prkdf->usageflags.sign ) log_printf ("%ssign", s), s = ",";
1228 if (prkdf->usageflags.sign_recover)
1229 log_printf ("%ssign_recover", s), s = ",";
1230 if (prkdf->usageflags.wrap ) log_printf ("%swrap", s), s = ",";
1231 if (prkdf->usageflags.unwrap ) log_printf ("%sunwrap", s), s = ",";
1232 if (prkdf->usageflags.verify ) log_printf ("%sverify", s), s = ",";
1233 if (prkdf->usageflags.verify_recover)
1234 log_printf ("%sverify_recover", s), s = ",";
1235 if (prkdf->usageflags.derive ) log_printf ("%sderive", s), s = ",";
1236 if (prkdf->usageflags.non_repudiation)
1237 log_printf ("%snon_repudiation", s), s = ",";
1238 log_printf ("\n");
1240 /* Put it into the list. */
1241 prkdf->next = prkdflist;
1242 prkdflist = prkdf;
1243 prkdf = NULL;
1244 continue; /* Ready. */
1246 parse_error:
1247 log_error ("error parsing PrKDF record (%d): %s - skipped\n",
1248 where, errstr? errstr : gpg_strerror (err));
1249 if (prkdf)
1251 xfree (prkdf->objid);
1252 xfree (prkdf->authid);
1253 xfree (prkdf);
1255 err = 0;
1256 } /* End looping over all records. */
1258 leave:
1259 xfree (buffer);
1260 if (err)
1261 release_prkdflist (prkdflist);
1262 else
1263 *result = prkdflist;
1264 return err;
1268 /* Read and parse the Certificate Directory Files identified by FID.
1269 On success a newlist of CDF object gets stored at RESULT and the
1270 caller is then responsible of releasing this list. On error a
1271 error code is returned and RESULT won't get changed. */
1272 static gpg_error_t
1273 read_ef_cdf (app_t app, unsigned short fid, cdf_object_t *result)
1275 gpg_error_t err;
1276 unsigned char *buffer = NULL;
1277 size_t buflen;
1278 const unsigned char *p;
1279 size_t n, objlen, hdrlen;
1280 int class, tag, constructed, ndef;
1281 cdf_object_t cdflist = NULL;
1282 int i;
1284 if (!fid)
1285 return gpg_error (GPG_ERR_NO_DATA); /* No certificates. */
1287 err = select_and_read_binary (app->slot, fid, "CDF", &buffer, &buflen);
1288 if (err)
1289 return err;
1291 p = buffer;
1292 n = buflen;
1294 /* Loop over the records. We stop as soon as we detect a new record
1295 starting with 0x00 or 0xff as these values are commonly used to
1296 pad data blocks and are no valid ASN.1 encoding. */
1297 while (n && *p && *p != 0xff)
1299 const unsigned char *pp;
1300 size_t nn;
1301 int where;
1302 const char *errstr = NULL;
1303 cdf_object_t cdf = NULL;
1304 unsigned long ul;
1305 const unsigned char *objid;
1306 size_t objidlen;
1308 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1309 &ndef, &objlen, &hdrlen);
1310 if (!err && (objlen > n || tag != TAG_SEQUENCE))
1311 err = gpg_error (GPG_ERR_INV_OBJ);
1312 if (err)
1314 log_error ("error parsing CDF record: %s\n", gpg_strerror (err));
1315 goto leave;
1317 pp = p;
1318 nn = objlen;
1319 p += objlen;
1320 n -= objlen;
1322 /* Skip the commonObjectAttributes. */
1323 where = __LINE__;
1324 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1325 &ndef, &objlen, &hdrlen);
1326 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1327 err = gpg_error (GPG_ERR_INV_OBJ);
1328 if (err)
1329 goto parse_error;
1330 pp += objlen;
1331 nn -= objlen;
1333 /* Parse the commonCertificateAttributes. */
1334 where = __LINE__;
1335 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1336 &ndef, &objlen, &hdrlen);
1337 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1338 err = gpg_error (GPG_ERR_INV_OBJ);
1339 if (err)
1340 goto parse_error;
1342 const unsigned char *ppp = pp;
1343 size_t nnn = objlen;
1345 pp += objlen;
1346 nn -= objlen;
1348 /* Get the Id. */
1349 where = __LINE__;
1350 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1351 &ndef, &objlen, &hdrlen);
1352 if (!err && (objlen > nnn
1353 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
1354 err = gpg_error (GPG_ERR_INV_OBJ);
1355 if (err)
1356 goto parse_error;
1357 objid = ppp;
1358 objidlen = objlen;
1361 /* Parse the certAttribute. */
1362 where = __LINE__;
1363 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1364 &ndef, &objlen, &hdrlen);
1365 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1366 err = gpg_error (GPG_ERR_INV_OBJ);
1367 if (err)
1368 goto parse_error;
1369 nn = objlen;
1371 where = __LINE__;
1372 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1373 &ndef, &objlen, &hdrlen);
1374 if (!err && (objlen > nn
1375 || class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE))
1376 err = gpg_error (GPG_ERR_INV_OBJ);
1377 if (err)
1378 goto parse_error;
1379 nn = objlen;
1381 /* Check that the reference is a Path object. */
1382 where = __LINE__;
1383 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1384 &ndef, &objlen, &hdrlen);
1385 if (!err && objlen > nn)
1386 err = gpg_error (GPG_ERR_INV_OBJ);
1387 if (err)
1388 goto parse_error;
1389 if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
1391 errstr = "unsupported reference type";
1392 continue;
1394 nn = objlen;
1396 /* Parse the Path object. */
1397 where = __LINE__;
1398 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1399 &ndef, &objlen, &hdrlen);
1400 if (!err && objlen > nn)
1401 err = gpg_error (GPG_ERR_INV_OBJ);
1402 if (err)
1403 goto parse_error;
1405 /* Make sure that the next element is a non zero path and of
1406 even length (FID are two bytes each). */
1407 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
1408 || !objlen || (objlen & 1) )
1410 errstr = "invalid path reference";
1411 goto parse_error;
1413 /* Create a new CDF list item. */
1414 cdf = xtrycalloc (1, (sizeof *cdf
1415 - sizeof(unsigned short)
1416 + objlen/2 * sizeof(unsigned short)));
1417 if (!cdf)
1419 err = gpg_error_from_errno (errno);
1420 goto leave;
1422 cdf->objidlen = objidlen;
1423 cdf->objid = xtrymalloc (objidlen);
1424 if (!cdf->objid)
1426 err = gpg_error_from_errno (errno);
1427 xfree (cdf);
1428 goto leave;
1430 memcpy (cdf->objid, objid, objidlen);
1432 cdf->pathlen = objlen/2;
1433 for (i=0; i < cdf->pathlen; i++, pp += 2, nn -= 2)
1434 cdf->path[i] = ((pp[0] << 8) | pp[1]);
1436 if (nn)
1438 /* An index and length follows. */
1439 cdf->have_off = 1;
1440 where = __LINE__;
1441 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1442 &ndef, &objlen, &hdrlen);
1443 if (!err && (objlen > nn
1444 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1445 err = gpg_error (GPG_ERR_INV_OBJ);
1446 if (err)
1447 goto parse_error;
1449 for (ul=0; objlen; objlen--)
1451 ul <<= 8;
1452 ul |= (*pp++) & 0xff;
1453 nn--;
1455 cdf->off = ul;
1457 where = __LINE__;
1458 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1459 &ndef, &objlen, &hdrlen);
1460 if (!err && (objlen > nn
1461 || class != CLASS_CONTEXT || tag != 0))
1462 err = gpg_error (GPG_ERR_INV_OBJ);
1463 if (err)
1464 goto parse_error;
1466 for (ul=0; objlen; objlen--)
1468 ul <<= 8;
1469 ul |= (*pp++) & 0xff;
1470 nn--;
1472 cdf->len = ul;
1475 log_debug ("CDF %04hX: id=", fid);
1476 for (i=0; i < cdf->objidlen; i++)
1477 log_printf ("%02X", cdf->objid[i]);
1478 log_printf (" path=");
1479 for (i=0; i < cdf->pathlen; i++)
1480 log_printf ("%04hX", cdf->path[i]);
1481 if (cdf->have_off)
1482 log_printf ("[%lu/%lu]", cdf->off, cdf->len);
1483 log_printf ("\n");
1485 /* Put it into the list. */
1486 cdf->next = cdflist;
1487 cdflist = cdf;
1488 cdf = NULL;
1489 continue; /* Ready. */
1491 parse_error:
1492 log_error ("error parsing CDF record (%d): %s - skipped\n",
1493 where, errstr? errstr : gpg_strerror (err));
1494 xfree (cdf);
1495 err = 0;
1496 } /* End looping over all records. */
1498 leave:
1499 xfree (buffer);
1500 if (err)
1501 release_cdflist (cdflist);
1502 else
1503 *result = cdflist;
1504 return err;
1509 SEQUENCE {
1510 SEQUENCE { -- CommonObjectAttributes
1511 UTF8String 'specific PIN for DS'
1512 BIT STRING 0 unused bits
1513 '00000011'B
1515 SEQUENCE { -- CommonAuthenticationObjectAttributes
1516 OCTET STRING
1517 07 -- iD
1520 [1] { -- typeAttributes
1521 SEQUENCE { -- PinAttributes
1522 BIT STRING 0 unused bits
1523 '0000100000110010'B -- local,initialized,needs-padding
1524 -- exchangeRefData
1525 ENUMERATED 1 -- ascii-numeric
1526 INTEGER 6 -- minLength
1527 INTEGER 6 -- storedLength
1528 INTEGER 8 -- maxLength
1530 02 -- pinReference
1531 GeneralizedTime 19/04/2002 12:12 GMT -- lastPinChange
1532 SEQUENCE {
1533 OCTET STRING
1534 3F 00 40 16 -- path to DF of PIN
1541 /* Read and parse an Authentication Object Directory File identified
1542 by FID. On success a newlist of AODF objects gets stored at RESULT
1543 and the caller is responsible of releasing this list. On error a
1544 error code is returned and RESULT won't get changed. */
1545 static gpg_error_t
1546 read_ef_aodf (app_t app, unsigned short fid, aodf_object_t *result)
1548 gpg_error_t err;
1549 unsigned char *buffer = NULL;
1550 size_t buflen;
1551 const unsigned char *p;
1552 size_t n, objlen, hdrlen;
1553 int class, tag, constructed, ndef;
1554 aodf_object_t aodflist = NULL;
1555 int i;
1557 if (!fid)
1558 return gpg_error (GPG_ERR_NO_DATA); /* No authentication objects. */
1560 err = select_and_read_binary (app->slot, fid, "AODF", &buffer, &buflen);
1561 if (err)
1562 return err;
1564 p = buffer;
1565 n = buflen;
1567 /* FIXME: This shares a LOT of code with read_ef_prkdf! */
1569 /* Loop over the records. We stop as soon as we detect a new record
1570 starting with 0x00 or 0xff as these values are commonly used to
1571 pad data blocks and are no valid ASN.1 encoding. */
1572 while (n && *p && *p != 0xff)
1574 const unsigned char *pp;
1575 size_t nn;
1576 int where;
1577 const char *errstr = NULL;
1578 aodf_object_t aodf = NULL;
1579 unsigned long ul;
1580 const char *s;
1582 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1583 &ndef, &objlen, &hdrlen);
1584 if (!err && (objlen > n || tag != TAG_SEQUENCE))
1585 err = gpg_error (GPG_ERR_INV_OBJ);
1586 if (err)
1588 log_error ("error parsing AODF record: %s\n", gpg_strerror (err));
1589 goto leave;
1591 pp = p;
1592 nn = objlen;
1593 p += objlen;
1594 n -= objlen;
1596 /* Allocate memory for a new AODF list item. */
1597 aodf = xtrycalloc (1, sizeof *aodf);
1598 if (!aodf)
1599 goto no_core;
1601 /* Parse the commonObjectAttributes. */
1602 where = __LINE__;
1603 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1604 &ndef, &objlen, &hdrlen);
1605 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1606 err = gpg_error (GPG_ERR_INV_OBJ);
1607 if (err)
1608 goto parse_error;
1610 const unsigned char *ppp = pp;
1611 size_t nnn = objlen;
1613 pp += objlen;
1614 nn -= objlen;
1616 /* Search the optional AuthId. We need to skip the optional
1617 Label (UTF8STRING) and the optional CommonObjectFlags
1618 (BITSTRING). */
1619 where = __LINE__;
1620 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1621 &ndef, &objlen, &hdrlen);
1622 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1623 err = gpg_error (GPG_ERR_INV_OBJ);
1624 if (gpg_err_code (err) == GPG_ERR_EOF)
1625 goto no_authid;
1626 if (err)
1627 goto parse_error;
1628 if (tag == TAG_UTF8_STRING)
1630 ppp += objlen; /* Skip the Label. */
1631 nnn -= objlen;
1633 where = __LINE__;
1634 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1635 &ndef, &objlen, &hdrlen);
1636 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1637 err = gpg_error (GPG_ERR_INV_OBJ);
1638 if (gpg_err_code (err) == GPG_ERR_EOF)
1639 goto no_authid;
1640 if (err)
1641 goto parse_error;
1643 if (tag == TAG_BIT_STRING)
1645 ppp += objlen; /* Skip the CommonObjectFlags. */
1646 nnn -= objlen;
1648 where = __LINE__;
1649 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1650 &ndef, &objlen, &hdrlen);
1651 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1652 err = gpg_error (GPG_ERR_INV_OBJ);
1653 if (gpg_err_code (err) == GPG_ERR_EOF)
1654 goto no_authid;
1655 if (err)
1656 goto parse_error;
1658 if (tag == TAG_OCTET_STRING && objlen)
1660 aodf->authidlen = objlen;
1661 aodf->authid = xtrymalloc (objlen);
1662 if (!aodf->authid)
1663 goto no_core;
1664 memcpy (aodf->authid, ppp, objlen);
1666 no_authid:
1670 /* Parse the CommonAuthenticationObjectAttributes. */
1671 where = __LINE__;
1672 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1673 &ndef, &objlen, &hdrlen);
1674 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1675 err = gpg_error (GPG_ERR_INV_OBJ);
1676 if (err)
1677 goto parse_error;
1679 const unsigned char *ppp = pp;
1680 size_t nnn = objlen;
1682 pp += objlen;
1683 nn -= objlen;
1685 /* Get the Id. */
1686 where = __LINE__;
1687 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1688 &ndef, &objlen, &hdrlen);
1689 if (!err && (objlen > nnn
1690 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
1691 err = gpg_error (GPG_ERR_INV_OBJ);
1692 if (err)
1693 goto parse_error;
1695 aodf->objidlen = objlen;
1696 aodf->objid = xtrymalloc (objlen);
1697 if (!aodf->objid)
1698 goto no_core;
1699 memcpy (aodf->objid, ppp, objlen);
1702 /* Parse the typeAttributes. */
1703 where = __LINE__;
1704 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1705 &ndef, &objlen, &hdrlen);
1706 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1707 err = gpg_error (GPG_ERR_INV_OBJ);
1708 if (err)
1709 goto parse_error;
1710 nn = objlen;
1712 where = __LINE__;
1713 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1714 &ndef, &objlen, &hdrlen);
1715 if (!err && objlen > nn)
1716 err = gpg_error (GPG_ERR_INV_OBJ);
1717 if (err)
1718 goto parse_error;
1719 if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
1720 ; /* PinAttributes */
1721 else if (class == CLASS_CONTEXT)
1723 switch (tag)
1725 case 0: errstr = "biometric auth types are not supported"; break;
1726 case 1: errstr = "authKey auth types are not supported"; break;
1727 case 2: errstr = "external auth type are not supported"; break;
1728 default: errstr = "unknown privateKeyObject"; break;
1730 goto parse_error;
1732 else
1734 err = gpg_error (GPG_ERR_INV_OBJ);
1735 goto parse_error;
1738 nn = objlen;
1740 /* PinFlags */
1741 where = __LINE__;
1742 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1743 &ndef, &objlen, &hdrlen);
1744 if (!err && (objlen > nn || !objlen
1745 || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
1746 err = gpg_error (GPG_ERR_INV_OBJ);
1747 if (err)
1748 goto parse_error;
1751 unsigned int bits, mask;
1752 int unused, full;
1754 unused = *pp++; nn--; objlen--;
1755 if ((!objlen && unused) || unused/8 > objlen)
1757 err = gpg_error (GPG_ERR_ENCODING_PROBLEM);
1758 goto parse_error;
1760 full = objlen - (unused+7)/8;
1761 unused %= 8;
1762 mask = 0;
1763 for (i=1; unused; i <<= 1, unused--)
1764 mask |= i;
1766 /* The first octet */
1767 bits = 0;
1768 if (objlen)
1770 bits = *pp++; nn--; objlen--;
1771 if (full)
1772 full--;
1773 else
1775 bits &= ~mask;
1776 mask = 0;
1779 if ((bits & 0x80)) /* ASN.1 bit 0. */
1780 aodf->pinflags.case_sensitive = 1;
1781 if ((bits & 0x40)) /* ASN.1 bit 1. */
1782 aodf->pinflags.local = 1;
1783 if ((bits & 0x20))
1784 aodf->pinflags.change_disabled = 1;
1785 if ((bits & 0x10))
1786 aodf->pinflags.unblock_disabled = 1;
1787 if ((bits & 0x08))
1788 aodf->pinflags.initialized = 1;
1789 if ((bits & 0x04))
1790 aodf->pinflags.needs_padding = 1;
1791 if ((bits & 0x02))
1792 aodf->pinflags.unblocking_pin = 1;
1793 if ((bits & 0x01))
1794 aodf->pinflags.so_pin = 1;
1795 /* The second octet. */
1796 bits = 0;
1797 if (objlen)
1799 bits = *pp++; nn--; objlen--;
1800 if (full)
1801 full--;
1802 else
1804 bits &= ~mask;
1805 mask = 0;
1808 if ((bits & 0x80))
1809 aodf->pinflags.disable_allowed = 1;
1810 if ((bits & 0x40))
1811 aodf->pinflags.integrity_protected = 1;
1812 if ((bits & 0x20))
1813 aodf->pinflags.confidentiality_protected = 1;
1814 if ((bits & 0x10))
1815 aodf->pinflags.exchange_ref_data = 1;
1816 /* Skip remaining bits. */
1817 pp += objlen;
1818 nn -= objlen;
1822 /* PinType */
1823 where = __LINE__;
1824 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1825 &ndef, &objlen, &hdrlen);
1826 if (!err && (objlen > nn
1827 || class != CLASS_UNIVERSAL || tag != TAG_ENUMERATED))
1828 err = gpg_error (GPG_ERR_INV_OBJ);
1829 if (!err && (objlen > sizeof (pin_type_t) || objlen > sizeof (ul)))
1830 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1831 if (err)
1832 goto parse_error;
1834 for (ul=0; objlen; objlen--)
1836 ul <<= 8;
1837 ul |= (*pp++) & 0xff;
1838 nn--;
1840 aodf->pintype = ul;
1843 /* minLength */
1844 where = __LINE__;
1845 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1846 &ndef, &objlen, &hdrlen);
1847 if (!err && (objlen > nn
1848 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1849 err = gpg_error (GPG_ERR_INV_OBJ);
1850 if (!err && objlen > sizeof (ul))
1851 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1852 if (err)
1853 goto parse_error;
1854 for (ul=0; objlen; objlen--)
1856 ul <<= 8;
1857 ul |= (*pp++) & 0xff;
1858 nn--;
1860 aodf->min_length = ul;
1863 /* storedLength */
1864 where = __LINE__;
1865 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1866 &ndef, &objlen, &hdrlen);
1867 if (!err && (objlen > nn
1868 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1869 err = gpg_error (GPG_ERR_INV_OBJ);
1870 if (!err && objlen > sizeof (ul))
1871 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1872 if (err)
1873 goto parse_error;
1874 for (ul=0; objlen; objlen--)
1876 ul <<= 8;
1877 ul |= (*pp++) & 0xff;
1878 nn--;
1880 aodf->stored_length = ul;
1882 /* optional maxLength */
1883 where = __LINE__;
1884 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1885 &ndef, &objlen, &hdrlen);
1886 if (gpg_err_code (err) == GPG_ERR_EOF)
1887 goto ready;
1888 if (!err && objlen > nn)
1889 err = gpg_error (GPG_ERR_INV_OBJ);
1890 if (err)
1891 goto parse_error;
1892 if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
1894 if (objlen > sizeof (ul))
1896 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1897 goto parse_error;
1899 for (ul=0; objlen; objlen--)
1901 ul <<= 8;
1902 ul |= (*pp++) & 0xff;
1903 nn--;
1905 aodf->max_length = ul;
1906 aodf->max_length_valid = 1;
1908 where = __LINE__;
1909 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1910 &ndef, &objlen, &hdrlen);
1911 if (gpg_err_code (err) == GPG_ERR_EOF)
1912 goto ready;
1913 if (!err && objlen > nn)
1914 err = gpg_error (GPG_ERR_INV_OBJ);
1915 if (err)
1916 goto parse_error;
1919 /* Optional pinReference. */
1920 if (class == CLASS_CONTEXT && tag == 0)
1922 if (objlen > sizeof (ul))
1924 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1925 goto parse_error;
1927 for (ul=0; objlen; objlen--)
1929 ul <<= 8;
1930 ul |= (*pp++) & 0xff;
1931 nn--;
1933 aodf->pin_reference = ul;
1934 aodf->pin_reference_valid = 1;
1936 where = __LINE__;
1937 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1938 &ndef, &objlen, &hdrlen);
1939 if (gpg_err_code (err) == GPG_ERR_EOF)
1940 goto ready;
1941 if (!err && objlen > nn)
1942 err = gpg_error (GPG_ERR_INV_OBJ);
1943 if (err)
1944 goto parse_error;
1947 /* Optional padChar. */
1948 if (class == CLASS_UNIVERSAL && tag == TAG_OCTET_STRING)
1950 if (objlen != 1)
1952 errstr = "padChar is not of size(1)";
1953 goto parse_error;
1955 aodf->pad_char = *pp++; nn--;
1956 aodf->pad_char_valid = 1;
1958 where = __LINE__;
1959 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1960 &ndef, &objlen, &hdrlen);
1961 if (gpg_err_code (err) == GPG_ERR_EOF)
1962 goto ready;
1963 if (!err && objlen > nn)
1964 err = gpg_error (GPG_ERR_INV_OBJ);
1965 if (err)
1966 goto parse_error;
1969 /* Skip optional lastPinChange. */
1970 if (class == CLASS_UNIVERSAL && tag == TAG_GENERALIZED_TIME)
1972 pp += objlen;
1973 nn -= objlen;
1975 where = __LINE__;
1976 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1977 &ndef, &objlen, &hdrlen);
1978 if (gpg_err_code (err) == GPG_ERR_EOF)
1979 goto ready;
1980 if (!err && objlen > nn)
1981 err = gpg_error (GPG_ERR_INV_OBJ);
1982 if (err)
1983 goto parse_error;
1986 /* Optional Path object. */
1987 if (class == CLASS_UNIVERSAL || tag == TAG_SEQUENCE)
1989 const unsigned char *ppp = pp;
1990 size_t nnn = objlen;
1992 pp += objlen;
1993 nn -= objlen;
1995 where = __LINE__;
1996 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1997 &ndef, &objlen, &hdrlen);
1998 if (!err && objlen > nnn)
1999 err = gpg_error (GPG_ERR_INV_OBJ);
2000 if (err)
2001 goto parse_error;
2003 /* Make sure that the next element is a non zero FID and of
2004 even length (FID are two bytes each). */
2005 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
2006 || !objlen || (objlen & 1) )
2008 errstr = "invalid path reference";
2009 goto parse_error;
2012 aodf->pathlen = objlen/2;
2013 aodf->path = xtrymalloc (aodf->pathlen);
2014 if (!aodf->path)
2015 goto no_core;
2016 for (i=0; i < aodf->pathlen; i++, ppp += 2, nnn -= 2)
2017 aodf->path[i] = ((ppp[0] << 8) | ppp[1]);
2019 if (nnn)
2021 /* An index and length follows. */
2022 aodf->have_off = 1;
2023 where = __LINE__;
2024 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
2025 &ndef, &objlen, &hdrlen);
2026 if (!err && (objlen > nnn
2027 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
2028 err = gpg_error (GPG_ERR_INV_OBJ);
2029 if (err)
2030 goto parse_error;
2032 for (ul=0; objlen; objlen--)
2034 ul <<= 8;
2035 ul |= (*ppp++) & 0xff;
2036 nnn--;
2038 aodf->off = ul;
2040 where = __LINE__;
2041 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
2042 &ndef, &objlen, &hdrlen);
2043 if (!err && (objlen > nnn
2044 || class != CLASS_CONTEXT || tag != 0))
2045 err = gpg_error (GPG_ERR_INV_OBJ);
2046 if (err)
2047 goto parse_error;
2049 for (ul=0; objlen; objlen--)
2051 ul <<= 8;
2052 ul |= (*ppp++) & 0xff;
2053 nnn--;
2055 aodf->len = ul;
2059 /* Igonore further objects which might be there due to future
2060 extensions of pkcs#15. */
2062 ready:
2063 log_debug ("AODF %04hX: id=", fid);
2064 for (i=0; i < aodf->objidlen; i++)
2065 log_printf ("%02X", aodf->objid[i]);
2066 if (aodf->authid)
2068 log_printf (" authid=");
2069 for (i=0; i < aodf->authidlen; i++)
2070 log_printf ("%02X", aodf->authid[i]);
2072 log_printf (" flags=");
2073 s = "";
2074 if (aodf->pinflags.case_sensitive)
2075 log_printf ("%scase_sensitive", s), s = ",";
2076 if (aodf->pinflags.local)
2077 log_printf ("%slocal", s), s = ",";
2078 if (aodf->pinflags.change_disabled)
2079 log_printf ("%schange_disabled", s), s = ",";
2080 if (aodf->pinflags.unblock_disabled)
2081 log_printf ("%sunblock_disabled", s), s = ",";
2082 if (aodf->pinflags.initialized)
2083 log_printf ("%sinitialized", s), s = ",";
2084 if (aodf->pinflags.needs_padding)
2085 log_printf ("%sneeds_padding", s), s = ",";
2086 if (aodf->pinflags.unblocking_pin)
2087 log_printf ("%sunblocking_pin", s), s = ",";
2088 if (aodf->pinflags.so_pin)
2089 log_printf ("%sso_pin", s), s = ",";
2090 if (aodf->pinflags.disable_allowed)
2091 log_printf ("%sdisable_allowed", s), s = ",";
2092 if (aodf->pinflags.integrity_protected)
2093 log_printf ("%sintegrity_protected", s), s = ",";
2094 if (aodf->pinflags.confidentiality_protected)
2095 log_printf ("%sconfidentiality_protected", s), s = ",";
2096 if (aodf->pinflags.exchange_ref_data)
2097 log_printf ("%sexchange_ref_data", s), s = ",";
2099 char numbuf[50];
2100 switch (aodf->pintype)
2102 case PIN_TYPE_BCD: s = "bcd"; break;
2103 case PIN_TYPE_ASCII_NUMERIC: s = "ascii-numeric"; break;
2104 case PIN_TYPE_UTF8: s = "utf8"; break;
2105 case PIN_TYPE_HALF_NIBBLE_BCD: s = "half-nibble-bcd"; break;
2106 case PIN_TYPE_ISO9564_1: s = "iso9564-1"; break;
2107 default:
2108 sprintf (numbuf, "%lu", (unsigned long)aodf->pintype);
2109 s = numbuf;
2111 log_printf (" type=%s", s);
2113 log_printf (" min=%lu", aodf->min_length);
2114 log_printf (" stored=%lu", aodf->stored_length);
2115 if (aodf->max_length_valid)
2116 log_printf (" max=%lu", aodf->max_length);
2117 if (aodf->pad_char_valid)
2118 log_printf (" pad=0x%02x", aodf->pad_char);
2119 if (aodf->pin_reference_valid)
2120 log_printf (" pinref=0x%02lX", aodf->pin_reference);
2121 if (aodf->pathlen)
2123 log_printf (" path=");
2124 for (i=0; i < aodf->pathlen; i++)
2125 log_printf ("%04hX", aodf->path[i]);
2126 if (aodf->have_off)
2127 log_printf ("[%lu/%lu]", aodf->off, aodf->len);
2129 log_printf ("\n");
2131 /* Put it into the list. */
2132 aodf->next = aodflist;
2133 aodflist = aodf;
2134 aodf = NULL;
2135 continue; /* Ready. */
2137 no_core:
2138 err = gpg_error_from_errno (errno);
2139 release_aodf_object (aodf);
2140 goto leave;
2142 parse_error:
2143 log_error ("error parsing AODF record (%d): %s - skipped\n",
2144 where, errstr? errstr : gpg_strerror (err));
2145 err = 0;
2146 release_aodf_object (aodf);
2147 } /* End looping over all records. */
2149 leave:
2150 xfree (buffer);
2151 if (err)
2152 release_aodflist (aodflist);
2153 else
2154 *result = aodflist;
2155 return err;
2162 /* Read and parse the EF(TokenInfo).
2164 TokenInfo ::= SEQUENCE {
2165 version INTEGER {v1(0)} (v1,...),
2166 serialNumber OCTET STRING,
2167 manufacturerID Label OPTIONAL,
2168 label [0] Label OPTIONAL,
2169 tokenflags TokenFlags,
2170 seInfo SEQUENCE OF SecurityEnvironmentInfo OPTIONAL,
2171 recordInfo [1] RecordInfo OPTIONAL,
2172 supportedAlgorithms [2] SEQUENCE OF AlgorithmInfo OPTIONAL,
2173 ...,
2174 issuerId [3] Label OPTIONAL,
2175 holderId [4] Label OPTIONAL,
2176 lastUpdate [5] LastUpdate OPTIONAL,
2177 preferredLanguage PrintableString OPTIONAL -- In accordance with
2178 -- IETF RFC 1766
2179 } (CONSTRAINED BY { -- Each AlgorithmInfo.reference value must be unique --})
2181 TokenFlags ::= BIT STRING {
2182 readonly (0),
2183 loginRequired (1),
2184 prnGeneration (2),
2185 eidCompliant (3)
2189 5032:
2191 30 31 02 01 00 04 04 05 45 36 9F 0C 0C 44 2D 54 01......E6...D-T
2192 72 75 73 74 20 47 6D 62 48 80 14 4F 66 66 69 63 rust GmbH..Offic
2193 65 20 69 64 65 6E 74 69 74 79 20 63 61 72 64 03 e identity card.
2194 02 00 40 20 63 61 72 64 03 02 00 40 00 00 00 00 ..@ card...@....
2195 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
2197 0 49: SEQUENCE {
2198 2 1: INTEGER 0
2199 5 4: OCTET STRING 05 45 36 9F
2200 11 12: UTF8String 'D-Trust GmbH'
2201 25 20: [0] 'Office identity card'
2202 47 2: BIT STRING
2203 : '00000010'B (bit 1)
2204 : Error: Spurious zero bits in bitstring.
2211 static gpg_error_t
2212 read_ef_tokeninfo (app_t app)
2214 gpg_error_t err;
2215 unsigned char *buffer = NULL;
2216 size_t buflen;
2217 const unsigned char *p;
2218 size_t n, objlen, hdrlen;
2219 int class, tag, constructed, ndef;
2220 unsigned long ul;
2222 err = select_and_read_binary (app->slot, 0x5032, "TokenInfo",
2223 &buffer, &buflen);
2224 if (err)
2225 return err;
2227 p = buffer;
2228 n = buflen;
2230 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2231 &ndef, &objlen, &hdrlen);
2232 if (!err && (objlen > n || tag != TAG_SEQUENCE))
2233 err = gpg_error (GPG_ERR_INV_OBJ);
2234 if (err)
2236 log_error ("error parsing TokenInfo: %s\n", gpg_strerror (err));
2237 goto leave;
2240 n = objlen;
2242 /* Version. */
2243 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2244 &ndef, &objlen, &hdrlen);
2245 if (!err && (objlen > n || tag != TAG_INTEGER))
2246 err = gpg_error (GPG_ERR_INV_OBJ);
2247 if (err)
2248 goto leave;
2250 for (ul=0; objlen; objlen--)
2252 ul <<= 8;
2253 ul |= (*p++) & 0xff;
2254 n--;
2256 if (ul)
2258 log_error ("invalid version %lu in TokenInfo\n", ul);
2259 err = gpg_error (GPG_ERR_INV_OBJ);
2260 goto leave;
2263 /* serialNumber. */
2264 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2265 &ndef, &objlen, &hdrlen);
2266 if (!err && (objlen > n || tag != TAG_OCTET_STRING || !objlen))
2267 err = gpg_error (GPG_ERR_INV_OBJ);
2268 if (err)
2269 goto leave;
2271 xfree (app->app_local->serialno);
2272 app->app_local->serialno = xtrymalloc (objlen);
2273 if (!app->app_local->serialno)
2275 err = gpg_error_from_errno (errno);
2276 goto leave;
2278 memcpy (app->app_local->serialno, p, objlen);
2279 app->app_local->serialnolen = objlen;
2280 log_printhex ("Serialnumber from EF(TokenInfo) is:", p, objlen);
2282 leave:
2283 xfree (buffer);
2284 return err;
2288 /* Get all the basic information from the pkcs#15 card, check the
2289 structure and initialize our local context. This is used once at
2290 application initialization. */
2291 static gpg_error_t
2292 read_p15_info (app_t app)
2294 gpg_error_t err;
2296 if (!read_ef_tokeninfo (app))
2298 /* If we don't have a serial number yet but the TokenInfo provides
2299 one, use that. */
2300 if (!app->serialno && app->app_local->serialno)
2302 app->serialno = app->app_local->serialno;
2303 app->serialnolen = app->app_local->serialnolen;
2304 app->app_local->serialno = NULL;
2305 app->app_local->serialnolen = 0;
2306 err = app_munge_serialno (app);
2307 if (err)
2308 return err;
2312 /* Read the ODF so that we know the location of all directory
2313 files. */
2314 /* Fixme: We might need to get a non-standard ODF FID from TokenInfo. */
2315 err = read_ef_odf (app, 0x5031);
2316 if (err)
2317 return err;
2319 /* Read certificate information. */
2320 assert (!app->app_local->certificate_info);
2321 assert (!app->app_local->trusted_certificate_info);
2322 assert (!app->app_local->useful_certificate_info);
2323 err = read_ef_cdf (app, app->app_local->odf.certificates,
2324 &app->app_local->certificate_info);
2325 if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
2326 err = read_ef_cdf (app, app->app_local->odf.trusted_certificates,
2327 &app->app_local->trusted_certificate_info);
2328 if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
2329 err = read_ef_cdf (app, app->app_local->odf.useful_certificates,
2330 &app->app_local->useful_certificate_info);
2331 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
2332 err = 0;
2333 if (err)
2334 return err;
2336 /* Read information about private keys. */
2337 assert (!app->app_local->private_key_info);
2338 err = read_ef_prkdf (app, app->app_local->odf.private_keys,
2339 &app->app_local->private_key_info);
2340 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
2341 err = 0;
2342 if (err)
2343 return err;
2345 /* Read information about authentication objects. */
2346 assert (!app->app_local->auth_object_info);
2347 err = read_ef_aodf (app, app->app_local->odf.auth_objects,
2348 &app->app_local->auth_object_info);
2349 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
2350 err = 0;
2353 return err;
2357 /* Helper to do_learn_status: Send information about all certificates
2358 listed in CERTINFO back. Use CERTTYPE as type of the
2359 certificate. */
2360 static gpg_error_t
2361 send_certinfo (app_t app, ctrl_t ctrl, const char *certtype,
2362 cdf_object_t certinfo)
2364 for (; certinfo; certinfo = certinfo->next)
2366 char *buf, *p;
2367 int i;
2369 buf = xtrymalloc (9 + certinfo->objidlen*2 + 1);
2370 if (!buf)
2371 return gpg_error_from_errno (errno);
2372 p = stpcpy (buf, "P15");
2373 if (app->app_local->home_df)
2375 sprintf (p, "-%04hX", (app->app_local->home_df & 0xffff));
2376 p += 5;
2378 p = stpcpy (p, ".");
2379 for (i=0; i < certinfo->objidlen; i++)
2381 sprintf (p, "%02X", certinfo->objid[i]);
2382 p += 2;
2385 send_status_info (ctrl, "CERTINFO",
2386 certtype, strlen (certtype),
2387 buf, strlen (buf),
2388 NULL, (size_t)0);
2389 xfree (buf);
2391 return 0;
2395 /* Get the keygrip of the private key object PRKDF. On success the
2396 keygrip gets returned in the caller provided 41 byte buffer
2397 R_GRIPSTR. */
2398 static gpg_error_t
2399 keygripstr_from_prkdf (app_t app, prkdf_object_t prkdf, char *r_gripstr)
2401 gpg_error_t err;
2402 cdf_object_t cdf;
2403 unsigned char *der;
2404 size_t derlen;
2405 ksba_cert_t cert;
2407 /* FIXME: We should check whether a public key directory file and a
2408 matching public key for PRKDF is available. This should make
2409 extraction of the key much easier. My current test card doesn't
2410 have one, so we can only use the fallback solution bu looking for
2411 a matching certificate and extract the key from there. */
2413 /* Look for a matching certificate. A certificate matches if the Id
2414 matches the obne of the private key info. */
2415 for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
2416 if (cdf->objidlen == prkdf->objidlen
2417 && !memcmp (cdf->objid, prkdf->objid, prkdf->objidlen))
2418 break;
2419 if (!cdf)
2420 for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
2421 if (cdf->objidlen == prkdf->objidlen
2422 && !memcmp (cdf->objid, prkdf->objid, prkdf->objidlen))
2423 break;
2424 if (!cdf)
2425 for (cdf = app->app_local->useful_certificate_info; cdf; cdf = cdf->next)
2426 if (cdf->objidlen == prkdf->objidlen
2427 && !memcmp (cdf->objid, prkdf->objid, prkdf->objidlen))
2428 break;
2429 if (!cdf)
2430 return gpg_error (GPG_ERR_NOT_FOUND);
2432 err = readcert_by_cdf (app, cdf, &der, &derlen);
2433 if (err)
2434 return err;
2436 err = ksba_cert_new (&cert);
2437 if (!err)
2438 err = ksba_cert_init_from_mem (cert, der, derlen);
2439 xfree (der);
2440 if (!err)
2441 err = app_help_get_keygrip_string (cert, r_gripstr);
2442 ksba_cert_release (cert);
2444 return err;
2450 /* Helper to do_learn_status: Send information about all known
2451 keypairs back. FIXME: much code duplication from
2452 send_sertinfo(). */
2453 static gpg_error_t
2454 send_keypairinfo (app_t app, ctrl_t ctrl, prkdf_object_t keyinfo)
2456 gpg_error_t err;
2458 for (; keyinfo; keyinfo = keyinfo->next)
2460 char gripstr[40+1];
2461 char *buf, *p;
2462 int i, j;
2464 buf = xtrymalloc (9 + keyinfo->objidlen*2 + 1);
2465 if (!buf)
2466 return gpg_error_from_errno (errno);
2467 p = stpcpy (buf, "P15");
2468 if (app->app_local->home_df)
2470 sprintf (p, "-%04hX", (app->app_local->home_df & 0xffff));
2471 p += 5;
2473 p = stpcpy (p, ".");
2474 for (i=0; i < keyinfo->objidlen; i++)
2476 sprintf (p, "%02X", keyinfo->objid[i]);
2477 p += 2;
2480 err = keygripstr_from_prkdf (app, keyinfo, gripstr);
2481 if (err)
2483 log_error ("can't get keygrip from ");
2484 for (j=0; j < keyinfo->pathlen; j++)
2485 log_printf ("%04hX", keyinfo->path[j]);
2486 log_printf (": %s\n", gpg_strerror (err));
2488 else
2490 assert (strlen (gripstr) == 40);
2491 send_status_info (ctrl, "KEYPAIRINFO",
2492 gripstr, 40,
2493 buf, strlen (buf),
2494 NULL, (size_t)0);
2496 xfree (buf);
2498 return 0;
2503 /* This is the handler for the LEARN command. */
2504 static gpg_error_t
2505 do_learn_status (app_t app, ctrl_t ctrl)
2507 gpg_error_t err;
2509 err = send_certinfo (app, ctrl, "100", app->app_local->certificate_info);
2510 if (!err)
2511 err = send_certinfo (app, ctrl, "101",
2512 app->app_local->trusted_certificate_info);
2513 if (!err)
2514 err = send_certinfo (app, ctrl, "102",
2515 app->app_local->useful_certificate_info);
2516 if (!err)
2517 err = send_keypairinfo (app, ctrl, app->app_local->private_key_info);
2519 return err;
2523 /* Read a certifciate using the information in CDF and return the
2524 certificate in a newly llocated buffer R_CERT and its length
2525 R_CERTLEN. */
2526 static gpg_error_t
2527 readcert_by_cdf (app_t app, cdf_object_t cdf,
2528 unsigned char **r_cert, size_t *r_certlen)
2530 gpg_error_t err;
2531 unsigned char *buffer = NULL;
2532 const unsigned char *p, *save_p;
2533 size_t buflen, n;
2534 int class, tag, constructed, ndef;
2535 size_t totobjlen, objlen, hdrlen;
2536 int rootca;
2537 int i;
2539 *r_cert = NULL;
2540 *r_certlen = 0;
2542 /* First check whether it has been cached. */
2543 if (cdf->image)
2545 *r_cert = xtrymalloc (cdf->imagelen);
2546 if (!*r_cert)
2547 return gpg_error_from_errno (errno);
2548 memcpy (*r_cert, cdf->image, cdf->imagelen);
2549 *r_certlen = cdf->imagelen;
2550 return 0;
2553 /* Read the entire file. fixme: This could be optimized by first
2554 reading the header to figure out how long the certificate
2555 actually is. */
2556 err = select_ef_by_path (app, cdf->path, cdf->pathlen);
2557 if (err)
2558 goto leave;
2560 err = iso7816_read_binary (app->slot, cdf->off, cdf->len, &buffer, &buflen);
2561 if (!err && (!buflen || *buffer == 0xff))
2562 err = gpg_error (GPG_ERR_NOT_FOUND);
2563 if (err)
2565 log_error ("error reading certificate with Id ");
2566 for (i=0; i < cdf->objidlen; i++)
2567 log_printf ("%02X", cdf->objid[i]);
2568 log_printf (": %s\n", gpg_strerror (err));
2569 goto leave;
2572 /* Check whether this is really a certificate. */
2573 p = buffer;
2574 n = buflen;
2575 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2576 &ndef, &objlen, &hdrlen);
2577 if (err)
2578 goto leave;
2580 if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed)
2581 rootca = 0;
2582 else if ( class == CLASS_UNIVERSAL && tag == TAG_SET && constructed )
2583 rootca = 1;
2584 else
2586 err = gpg_error (GPG_ERR_INV_OBJ);
2587 goto leave;
2589 totobjlen = objlen + hdrlen;
2590 assert (totobjlen <= buflen);
2592 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2593 &ndef, &objlen, &hdrlen);
2594 if (err)
2595 goto leave;
2597 if (!rootca
2598 && class == CLASS_UNIVERSAL && tag == TAG_OBJECT_ID && !constructed)
2600 /* The certificate seems to be contained in a userCertificate
2601 container. Skip this and assume the following sequence is
2602 the certificate. */
2603 if (n < objlen)
2605 err = gpg_error (GPG_ERR_INV_OBJ);
2606 goto leave;
2608 p += objlen;
2609 n -= objlen;
2610 save_p = p;
2611 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2612 &ndef, &objlen, &hdrlen);
2613 if (err)
2614 goto leave;
2615 if ( !(class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed) )
2617 err = gpg_error (GPG_ERR_INV_OBJ);
2618 goto leave;
2620 totobjlen = objlen + hdrlen;
2621 assert (save_p + totobjlen <= buffer + buflen);
2622 memmove (buffer, save_p, totobjlen);
2625 *r_cert = buffer;
2626 buffer = NULL;
2627 *r_certlen = totobjlen;
2629 /* Try to cache it. */
2630 if (!cdf->image && (cdf->image = xtrymalloc (*r_certlen)))
2632 memcpy (cdf->image, *r_cert, *r_certlen);
2633 cdf->imagelen = *r_certlen;
2637 leave:
2638 xfree (buffer);
2639 return err;
2643 /* Handler for the READCERT command.
2645 Read the certificate with id CERTID (as returned by learn_status in
2646 the CERTINFO status lines) and return it in the freshly allocated
2647 buffer to be stored at R_CERT and its length at R_CERTLEN. A error
2648 code will be returned on failure and R_CERT and R_CERTLEN will be
2649 set to NULL/0. */
2650 static gpg_error_t
2651 do_readcert (app_t app, const char *certid,
2652 unsigned char **r_cert, size_t *r_certlen)
2654 gpg_error_t err;
2655 cdf_object_t cdf;
2657 *r_cert = NULL;
2658 *r_certlen = 0;
2659 err = cdf_object_from_certid (app, certid, &cdf);
2660 if (!err)
2661 err =readcert_by_cdf (app, cdf, r_cert, r_certlen);
2662 return err;
2667 /* Implement the GETATTR command. This is similar to the LEARN
2668 command but returns just one value via the status interface. */
2669 static gpg_error_t
2670 do_getattr (app_t app, ctrl_t ctrl, const char *name)
2672 gpg_error_t err;
2673 int i;
2675 if (!strcmp (name, "$AUTHKEYID"))
2677 char *buf, *p;
2678 prkdf_object_t prkdf;
2680 /* We return the ID of the first private keycapable of
2681 signing. */
2682 for (prkdf = app->app_local->private_key_info; prkdf;
2683 prkdf = prkdf->next)
2684 if (prkdf->usageflags.sign)
2685 break;
2686 if (prkdf)
2688 buf = xtrymalloc (9 + prkdf->objidlen*2 + 1);
2689 if (!buf)
2690 return gpg_error_from_errno (errno);
2691 p = stpcpy (buf, "P15");
2692 if (app->app_local->home_df)
2694 sprintf (p, "-%04hX", (app->app_local->home_df & 0xffff));
2695 p += 5;
2697 p = stpcpy (p, ".");
2698 for (i=0; i < prkdf->objidlen; i++)
2700 sprintf (p, "%02X", prkdf->objid[i]);
2701 p += 2;
2704 send_status_info (ctrl, name, buf, strlen (buf), NULL, 0);
2705 xfree (buf);
2706 return 0;
2709 else if (!strcmp (name, "$DISPSERIALNO"))
2711 /* For certain cards we return special IDs. There is no
2712 general rule for it so we need to decide case by case. */
2713 if (app->app_local->card_type == CARD_TYPE_BELPIC)
2715 /* The eID card has a card number printed on the fron matter
2716 which seems to be a good indication. */
2717 unsigned char *buffer;
2718 const unsigned char *p;
2719 size_t buflen, n;
2720 unsigned short path[] = { 0x3F00, 0xDF01, 0x4031 };
2722 err = select_ef_by_path (app, path, DIM(path) );
2723 if (!err)
2724 err = iso7816_read_binary (app->slot, 0, 0, &buffer, &buflen);
2725 if (err)
2727 log_error ("error accessing EF(ID): %s\n", gpg_strerror (err));
2728 return err;
2731 p = find_tlv (buffer, buflen, 1, &n);
2732 if (p && n == 12)
2734 char tmp[12+2+1];
2735 memcpy (tmp, p, 3);
2736 tmp[3] = '-';
2737 memcpy (tmp+4, p+3, 7);
2738 tmp[11] = '-';
2739 memcpy (tmp+12, p+10, 2);
2740 tmp[14] = 0;
2741 send_status_info (ctrl, name, tmp, strlen (tmp), NULL, 0);
2742 xfree (buffer);
2743 return 0;
2745 xfree (buffer);
2749 return gpg_error (GPG_ERR_INV_NAME);
2755 /* Micardo cards require special treatment. This is a helper for the
2756 crypto functions to manage the security environment. We expect that
2757 the key file has already been selected. FID is the one of the
2758 selected key. */
2759 static gpg_error_t
2760 micardo_mse (app_t app, unsigned short fid)
2762 gpg_error_t err;
2763 int recno;
2764 unsigned short refdata = 0;
2765 int se_num;
2766 unsigned char msebuf[10];
2768 /* Read the KeyD file containing extra information on keys. */
2769 err = iso7816_select_file (app->slot, 0x0013, 0, NULL, NULL);
2770 if (err)
2772 log_error ("error reading EF_keyD: %s\n", gpg_strerror (err));
2773 return err;
2776 for (recno = 1, se_num = -1; ; recno++)
2778 unsigned char *buffer;
2779 size_t buflen;
2780 size_t n, nn;
2781 const unsigned char *p, *pp;
2783 err = iso7816_read_record (app->slot, recno, 1, 0, &buffer, &buflen);
2784 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2785 break; /* ready */
2786 if (err)
2788 log_error ("error reading EF_keyD record: %s\n",
2789 gpg_strerror (err));
2790 return err;
2792 log_printhex ("keyD record:", buffer, buflen);
2793 p = find_tlv (buffer, buflen, 0x83, &n);
2794 if (p && n == 4 && ((p[2]<<8)|p[3]) == fid)
2796 refdata = ((p[0]<<8)|p[1]);
2797 /* Locate the SE DO and the there included sec env number. */
2798 p = find_tlv (buffer, buflen, 0x7b, &n);
2799 if (p && n)
2801 pp = find_tlv (p, n, 0x80, &nn);
2802 if (pp && nn == 1)
2804 se_num = *pp;
2805 xfree (buffer);
2806 break; /* found. */
2810 xfree (buffer);
2812 if (se_num == -1)
2814 log_error ("CRT for keyfile %04hX not found\n", fid);
2815 return gpg_error (GPG_ERR_NOT_FOUND);
2819 /* Restore the security environment to SE_NUM if needed */
2820 if (se_num)
2822 err = iso7816_manage_security_env (app->slot, 0xf3, se_num, NULL, 0);
2823 if (err)
2825 log_error ("restoring SE to %d failed: %s\n",
2826 se_num, gpg_strerror (err));
2827 return err;
2831 /* Set the DST reference data. */
2832 msebuf[0] = 0x83;
2833 msebuf[1] = 0x03;
2834 msebuf[2] = 0x80;
2835 msebuf[3] = (refdata >> 8);
2836 msebuf[4] = refdata;
2837 err = iso7816_manage_security_env (app->slot, 0x41, 0xb6, msebuf, 5);
2838 if (err)
2840 log_error ("setting SE to reference file %04hX failed: %s\n",
2841 refdata, gpg_strerror (err));
2842 return err;
2844 return 0;
2849 /* Handler for the PKSIGN command.
2851 Create the signature and return the allocated result in OUTDATA.
2852 If a PIN is required, the PINCB will be used to ask for the PIN;
2853 that callback should return the PIN in an allocated buffer and
2854 store that as the 3rd argument. */
2855 static gpg_error_t
2856 do_sign (app_t app, const char *keyidstr, int hashalgo,
2857 gpg_error_t (*pincb)(void*, const char *, char **),
2858 void *pincb_arg,
2859 const void *indata, size_t indatalen,
2860 unsigned char **outdata, size_t *outdatalen )
2862 static unsigned char sha1_prefix[15] = /* Object ID is 1.3.14.3.2.26 */
2863 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
2864 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
2865 static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
2866 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
2867 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
2869 gpg_error_t err;
2870 int i;
2871 unsigned char data[35]; /* Must be large enough for a SHA-1 digest
2872 + the largest OID prefix above. */
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)
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 ver 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 mse[2] = 0x02; /* Algorithm: RSASSA-PKCS1-v1.5 using SHA1. */
2952 mse[3] = 0x84; /* Private key reference tag. */
2953 mse[4] = prkdf->key_reference_valid? prkdf->key_reference : 0x82;
2955 err = iso7816_manage_security_env (app->slot,
2956 0x41, 0xB6,
2957 mse, sizeof mse);
2958 no_data_padding = 1;
2959 mse_done = 1;
2961 if (err)
2963 log_error ("MSE failed: %s\n", gpg_strerror (err));
2964 return err;
2968 /* Now that we have all the information available, prepare and run
2969 the PIN verification.*/
2970 if (1)
2972 char *pinvalue;
2973 size_t pinvaluelen;
2974 const char *errstr;
2975 const char *s;
2977 if (prkdf->usageflags.non_repudiation
2978 && app->app_local->card_type == CARD_TYPE_BELPIC)
2979 err = pincb (pincb_arg, "PIN (qualified signature!)", &pinvalue);
2980 else
2981 err = pincb (pincb_arg, "PIN", &pinvalue);
2982 if (err)
2984 log_info ("PIN callback returned error: %s\n", gpg_strerror (err));
2985 return err;
2988 /* We might need to cope with UTF8 things here. Not sure how
2989 min_length etc. are exactly defined, for now we take them as
2990 a plain octet count. */
2992 if (strlen (pinvalue) < aodf->min_length)
2994 log_error ("PIN is too short; minimum length is %lu\n",
2995 aodf->min_length);
2996 err = gpg_error (GPG_ERR_BAD_PIN);
2998 else if (aodf->stored_length && strlen (pinvalue) > aodf->stored_length)
3000 /* This would otherwise truncate the PIN silently. */
3001 log_error ("PIN is too large; maximum length is %lu\n",
3002 aodf->stored_length);
3003 err = gpg_error (GPG_ERR_BAD_PIN);
3005 else if (aodf->max_length_valid && strlen (pinvalue) > aodf->max_length)
3007 log_error ("PIN is too large; maximum length is %lu\n",
3008 aodf->max_length);
3009 err = gpg_error (GPG_ERR_BAD_PIN);
3012 if (err)
3014 xfree (pinvalue);
3015 return err;
3018 errstr = NULL;
3019 err = 0;
3020 switch (aodf->pintype)
3022 case PIN_TYPE_BCD:
3023 case PIN_TYPE_ASCII_NUMERIC:
3024 for (s=pinvalue; digitp (s); s++)
3026 if (*s)
3028 errstr = "Non-numeric digits found in PIN";
3029 err = gpg_error (GPG_ERR_BAD_PIN);
3031 break;
3032 case PIN_TYPE_UTF8:
3033 break;
3034 case PIN_TYPE_HALF_NIBBLE_BCD:
3035 errstr = "PIN type Half-Nibble-BCD is not supported";
3036 break;
3037 case PIN_TYPE_ISO9564_1:
3038 errstr = "PIN type ISO9564-1 is not supported";
3039 break;
3040 default:
3041 errstr = "Unknown PIN type";
3042 break;
3044 if (errstr)
3046 log_error ("can't verify PIN: %s\n", errstr);
3047 xfree (pinvalue);
3048 return err? err : gpg_error (GPG_ERR_BAD_PIN_METHOD);
3052 if (aodf->pintype == PIN_TYPE_BCD )
3054 char *paddedpin;
3055 int ndigits;
3057 for (ndigits=0, s=pinvalue; *s; ndigits++, s++)
3059 paddedpin = xtrymalloc (aodf->stored_length+1);
3060 if (!paddedpin)
3062 err = gpg_error_from_errno (errno);
3063 xfree (pinvalue);
3064 return err;
3067 i = 0;
3068 paddedpin[i++] = 0x20 | (ndigits & 0x0f);
3069 for (s=pinvalue; i < aodf->stored_length && *s && s[1]; s = s+2 )
3070 paddedpin[i++] = (((*s - '0') << 4) | ((s[1] - '0') & 0x0f));
3071 if (i < aodf->stored_length && *s)
3072 paddedpin[i++] = (((*s - '0') << 4)
3073 |((aodf->pad_char_valid?aodf->pad_char:0)&0x0f));
3075 if (aodf->pinflags.needs_padding)
3076 while (i < aodf->stored_length)
3077 paddedpin[i++] = aodf->pad_char_valid? aodf->pad_char : 0;
3079 xfree (pinvalue);
3080 pinvalue = paddedpin;
3081 pinvaluelen = i;
3083 else if (aodf->pinflags.needs_padding)
3085 char *paddedpin;
3087 paddedpin = xtrymalloc (aodf->stored_length+1);
3088 if (!paddedpin)
3090 err = gpg_error_from_errno (errno);
3091 xfree (pinvalue);
3092 return err;
3094 for (i=0, s=pinvalue; i < aodf->stored_length && *s; i++, s++)
3095 paddedpin[i] = *s;
3096 /* Not sure what padding char to use if none has been set.
3097 For now we use 0x00; maybe a space would be better. */
3098 for (; i < aodf->stored_length; i++)
3099 paddedpin[i] = aodf->pad_char_valid? aodf->pad_char : 0;
3100 paddedpin[i] = 0;
3101 pinvaluelen = i;
3102 xfree (pinvalue);
3103 pinvalue = paddedpin;
3105 else
3106 pinvaluelen = strlen (pinvalue);
3108 err = iso7816_verify (app->slot,
3109 aodf->pin_reference_valid? aodf->pin_reference : 0,
3110 pinvalue, pinvaluelen);
3111 xfree (pinvalue);
3112 if (err)
3114 log_error ("PIN verification failed: %s\n", gpg_strerror (err));
3115 return err;
3117 log_debug ("PIN verification succeeded\n");
3120 /* Prepare the DER object from INDATA. */
3121 if (indatalen == 35)
3123 /* Alright, the caller was so kind to send us an already
3124 prepared DER object. Check that it is what we want and that
3125 it matches the hash algorithm. */
3126 if (hashalgo == GCRY_MD_SHA1 && !memcmp (indata, sha1_prefix, 15))
3128 else if (hashalgo == GCRY_MD_RMD160
3129 && !memcmp (indata, rmd160_prefix, 15))
3131 else
3132 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3133 memcpy (data, indata, indatalen);
3135 else
3137 /* Need to prepend the prefix. */
3138 if (hashalgo == GCRY_MD_SHA1)
3139 memcpy (data, sha1_prefix, 15);
3140 else if (hashalgo == GCRY_MD_RMD160)
3141 memcpy (data, rmd160_prefix, 15);
3142 else
3143 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3144 memcpy (data+15, indata, indatalen);
3147 /* Manage security environment needs to be weaked for certain cards. */
3148 if (mse_done)
3149 err = 0;
3150 else if (app->app_local->card_type == CARD_TYPE_TCOS)
3152 /* TCOS creates signatures always using the local key 0. MSE
3153 may not be used. */
3155 else if (app->app_local->card_type == CARD_TYPE_MICARDO)
3157 if (!prkdf->pathlen)
3158 err = gpg_error (GPG_ERR_BUG);
3159 else
3160 err = micardo_mse (app, prkdf->path[prkdf->pathlen-1]);
3162 else if (prkdf->key_reference_valid)
3164 unsigned char mse[3];
3166 mse[0] = 0x84; /* Select asym. key. */
3167 mse[1] = 1;
3168 mse[2] = prkdf->key_reference;
3170 err = iso7816_manage_security_env (app->slot,
3171 0x41, 0xB6,
3172 mse, sizeof mse);
3174 if (err)
3176 log_error ("MSE failed: %s\n", gpg_strerror (err));
3177 return err;
3180 if (no_data_padding)
3181 err = iso7816_compute_ds (app->slot, data+15, 20, outdata, outdatalen);
3182 else
3183 err = iso7816_compute_ds (app->slot, data, 35, outdata, outdatalen);
3184 return err;
3188 /* Handler for the PKAUTH command.
3190 This is basically the same as the PKSIGN command but we firstcheck
3191 that the requested key is suitable for authentication; that is, it
3192 must match the criteria used for the attribute $AUTHKEYID. See
3193 do_sign for calling conventions; there is no HASHALGO, though. */
3194 static gpg_error_t
3195 do_auth (app_t app, const char *keyidstr,
3196 gpg_error_t (*pincb)(void*, const char *, char **),
3197 void *pincb_arg,
3198 const void *indata, size_t indatalen,
3199 unsigned char **outdata, size_t *outdatalen )
3201 gpg_error_t err;
3202 prkdf_object_t prkdf;
3204 if (!keyidstr || !*keyidstr)
3205 return gpg_error (GPG_ERR_INV_VALUE);
3207 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
3208 if (err)
3209 return err;
3210 if (!prkdf->usageflags.sign)
3212 log_error ("key %s may not be used for authentication\n", keyidstr);
3213 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
3215 return do_sign (app, keyidstr, GCRY_MD_SHA1, pincb, pincb_arg,
3216 indata, indatalen, outdata, outdatalen);
3221 /* Assume that EF(DIR) has been selected. Read its content and figure
3222 out the home EF of pkcs#15. Return that home DF or 0 if not found
3223 and the value at the address of BELPIC indicates whether it was
3224 found by the belpic aid. */
3225 static unsigned short
3226 read_home_df (int slot, int *r_belpic)
3228 gpg_error_t err;
3229 unsigned char *buffer;
3230 const unsigned char *p, *pp;
3231 size_t buflen, n, nn;
3232 unsigned short result = 0;
3234 *r_belpic = 0;
3236 err = iso7816_read_binary (slot, 0, 0, &buffer, &buflen);
3237 if (err)
3239 log_error ("error reading EF{DIR}: %s\n", gpg_strerror (err));
3240 return 0;
3243 /* FIXME: We need to scan all records. */
3244 p = find_tlv (buffer, buflen, 0x61, &n);
3245 if (p && n)
3247 pp = find_tlv (p, n, 0x4f, &nn);
3248 if (pp && ((nn == sizeof pkcs15_aid && !memcmp (pp, pkcs15_aid, nn))
3249 || (*r_belpic = (nn == sizeof pkcs15be_aid
3250 && !memcmp (pp, pkcs15be_aid, nn)))))
3252 pp = find_tlv (p, n, 0x50, &nn);
3253 if (pp) /* fixme: Filter log value? */
3254 log_info ("pkcs#15 application label from EF(DIR) is `%.*s'\n",
3255 (int)nn, pp);
3256 pp = find_tlv (p, n, 0x51, &nn);
3257 if (pp && nn == 4 && *pp == 0x3f && !pp[1])
3259 result = ((pp[2] << 8) | pp[3]);
3260 log_info ("pkcs#15 application directory is 0x%04hX\n", result);
3264 xfree (buffer);
3265 return result;
3270 Select the PKCS#15 application on the card in SLOT.
3272 gpg_error_t
3273 app_select_p15 (app_t app)
3275 int slot = app->slot;
3276 int rc;
3277 unsigned short def_home_df = 0;
3278 card_type_t card_type = CARD_TYPE_UNKNOWN;
3279 int direct = 0;
3280 int is_belpic = 0;
3282 rc = iso7816_select_application (slot, pkcs15_aid, sizeof pkcs15_aid, 0);
3283 if (rc)
3284 { /* Not found: Try to locate it from 2F00. We use direct path
3285 selection here because it seems that the Belgian eID card
3286 does only allow for that. Many other cards supports this
3287 selection method too. Note, that we don't use
3288 select_application above for the Belgian card - the call
3289 works but it seems that it did not switch to the correct DF.
3290 Using the 2f02 just works. */
3291 unsigned short path[1] = { 0x2f00 };
3293 rc = iso7816_select_path (app->slot, path, 1, NULL, NULL);
3294 if (!rc)
3296 direct = 1;
3297 def_home_df = read_home_df (slot, &is_belpic);
3298 if (def_home_df)
3300 path[0] = def_home_df;
3301 rc = iso7816_select_path (app->slot, path, 1, NULL, NULL);
3305 if (rc)
3306 { /* Still not found: Try the default DF. */
3307 def_home_df = 0x5015;
3308 rc = iso7816_select_file (slot, def_home_df, 1, NULL, NULL);
3310 if (!rc)
3312 /* Determine the type of the card. The general case is to look
3313 it up from the ATR table. For the Belgian eID card we know
3314 it instantly from the AID. */
3315 if (is_belpic)
3317 card_type = CARD_TYPE_BELPIC;
3319 else
3321 unsigned char *atr;
3322 size_t atrlen;
3323 int i;
3325 atr = apdu_get_atr (app->slot, &atrlen);
3326 if (!atr)
3327 rc = gpg_error (GPG_ERR_INV_CARD);
3328 else
3330 for (i=0; card_atr_list[i].atrlen; i++)
3331 if (card_atr_list[i].atrlen == atrlen
3332 && !memcmp (card_atr_list[i].atr, atr, atrlen))
3334 card_type = card_atr_list[i].type;
3335 break;
3337 xfree (atr);
3341 if (!rc)
3343 app->apptype = "P15";
3345 app->app_local = xtrycalloc (1, sizeof *app->app_local);
3346 if (!app->app_local)
3348 rc = gpg_error_from_errno (errno);
3349 goto leave;
3352 /* Set the home DF. Note that we currently can't do that if the
3353 selection via application ID worked. This will store 0 there
3354 instead. FIXME: We either need to figure the home_df via the
3355 DIR file or using the return values from the select file
3356 APDU. */
3357 app->app_local->home_df = def_home_df;
3359 /* Store the card type. FIXME: We might want to put this into
3360 the common APP structure. */
3361 app->app_local->card_type = card_type;
3363 /* Store whether we may and should use direct path selection. */
3364 app->app_local->direct_path_selection = direct;
3366 /* Read basic information and thus check whether this is a real
3367 card. */
3368 rc = read_p15_info (app);
3369 if (rc)
3370 goto leave;
3372 /* Special serial number munging. We need to check for a German
3373 prototype card right here because we need to access to
3374 EF(TokenInfo). We mark such a serial number by the using a
3375 prefix of FF0100. */
3376 if (app->serialnolen == 12
3377 && !memcmp (app->serialno, "\xD2\x76\0\0\0\0\0\0\0\0\0\0", 12))
3379 /* This is a German card with a silly serial number. Try to get
3380 the serial number from the EF(TokenInfo). . */
3381 unsigned char *p;
3383 /* FIXME: actually get it from EF(TokenInfo). */
3385 p = xtrymalloc (3 + app->serialnolen);
3386 if (!p)
3387 rc = gpg_error (gpg_err_code_from_errno (errno));
3388 else
3390 memcpy (p, "\xff\x01", 3);
3391 memcpy (p+3, app->serialno, app->serialnolen);
3392 app->serialnolen += 3;
3393 xfree (app->serialno);
3394 app->serialno = p;
3398 app->fnc.deinit = do_deinit;
3399 app->fnc.learn_status = do_learn_status;
3400 app->fnc.readcert = do_readcert;
3401 app->fnc.getattr = do_getattr;
3402 app->fnc.setattr = NULL;
3403 app->fnc.genkey = NULL;
3404 app->fnc.sign = do_sign;
3405 app->fnc.auth = do_auth;
3406 app->fnc.decipher = NULL;
3407 app->fnc.change_pin = NULL;
3408 app->fnc.check_pin = NULL;
3410 leave:
3411 if (rc)
3412 do_deinit (app);
3415 return rc;