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