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