1 /* app-p15.c - The pkcs#15 card application.
2 * Copyright (C) 2005 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <https://www.gnu.org/licenses/>.
20 /* Information pertaining to the BELPIC developer card samples:
22 Unblock PUK: "222222111111"
23 Reset PIN: "333333111111")
25 e.g. the APDUs 00:20:00:02:08:2C:33:33:33:11:11:11:FF
26 and 00:24:01:01:08:24:12:34:FF:FF:FF:FF:FF
27 should change the PIN into 1234.
41 #include "app-common.h"
42 #include "../common/tlv.h"
43 #include "apdu.h" /* fixme: we should move the card detection to a
46 /* Types of cards we know and which needs special treatment. */
52 CARD_TYPE_BELPIC /* Belgian eID card specs. */
56 /* A list card types with ATRs noticed with these cards. */
57 #define X(a) ((unsigned char const *)(a))
61 unsigned char const *atr;
64 { 19, X("\x3B\xBA\x13\x00\x81\x31\x86\x5D\x00\x64\x05\x0A\x02\x01\x31\x80"
66 CARD_TYPE_TCOS }, /* SLE44 */
67 { 19, X("\x3B\xBA\x14\x00\x81\x31\x86\x5D\x00\x64\x05\x14\x02\x02\x31\x80"
69 CARD_TYPE_TCOS }, /* SLE66S */
70 { 19, X("\x3B\xBA\x96\x00\x81\x31\x86\x5D\x00\x64\x05\x60\x02\x03\x31\x80"
72 CARD_TYPE_TCOS }, /* SLE66P */
73 { 27, X("\x3B\xFF\x94\x00\xFF\x80\xB1\xFE\x45\x1F\x03\x00\x68\xD2\x76\x00"
74 "\x00\x28\xFF\x05\x1E\x31\x80\x00\x90\x00\x23"),
75 CARD_TYPE_MICARDO }, /* German BMI card */
76 { 19, X("\x3B\x6F\x00\xFF\x00\x68\xD2\x76\x00\x00\x28\xFF\x05\x1E\x31\x80"
78 CARD_TYPE_MICARDO }, /* German BMI card (ATR due to reader problem) */
79 { 26, X("\x3B\xFE\x94\x00\xFF\x80\xB1\xFA\x45\x1F\x03\x45\x73\x74\x45\x49"
80 "\x44\x20\x76\x65\x72\x20\x31\x2E\x30\x43"),
81 CARD_TYPE_MICARDO }, /* EstEID (Estonian Big Brother card) */
88 /* The AID of PKCS15. */
89 static char const pkcs15_aid[] = { 0xA0, 0, 0, 0, 0x63,
90 0x50, 0x4B, 0x43, 0x53, 0x2D, 0x31, 0x35 };
92 /* The Belgian eID variant - they didn't understood why a shared AID
93 is useful for a standard. Oh well. */
94 static char const pkcs15be_aid[] = { 0xA0, 0, 0, 0x01, 0x77,
95 0x50, 0x4B, 0x43, 0x53, 0x2D, 0x31, 0x35 };
98 /* The PIN types as defined in pkcs#15 v1.1 */
102 PIN_TYPE_ASCII_NUMERIC = 1,
104 PIN_TYPE_HALF_NIBBLE_BCD = 3,
105 PIN_TYPE_ISO9564_1 = 4
109 /* A bit array with for the key usage flags from the
110 commonKeyAttributes. */
111 struct keyusage_flags_s
113 unsigned int encrypt: 1;
114 unsigned int decrypt: 1;
115 unsigned int sign: 1;
116 unsigned int sign_recover: 1;
117 unsigned int wrap: 1;
118 unsigned int unwrap: 1;
119 unsigned int verify: 1;
120 unsigned int verify_recover: 1;
121 unsigned int derive: 1;
122 unsigned int non_repudiation: 1;
124 typedef struct keyusage_flags_s keyusage_flags_t;
128 /* This is an object to store information about a Certificate
129 Directory File (CDF) in a format suitable for further processing by
130 us. To keep memory management, simple we use a linked list of
131 items; i.e. one such object represents one certificate and the list
135 /* Link to next item when used in a linked list. */
136 struct cdf_object_s *next;
138 /* Length and allocated buffer with the Id of this object. */
140 unsigned char *objid;
142 /* To avoid reading a certificate more than once, we cache it in an
143 allocated memory IMAGE of IMAGELEN. */
145 unsigned char *image;
147 /* Set to true if a length and offset is available. */
149 /* The offset and length of the object. They are only valid if
150 HAVE_OFF is true and set to 0 if HAVE_OFF is false. */
151 unsigned long off, len;
153 /* The length of the path as given in the CDF and the path itself.
154 path[0] is the top DF (usually 0x3f00). The path will never be
157 unsigned short path[1];
159 typedef struct cdf_object_s *cdf_object_t;
162 /* This is an object to store information about a Private Key
163 Directory File (PrKDF) in a format suitable for further processing
164 by us. To keep memory management, simple we use a linked list of
165 items; i.e. one such object represents one certificate and the list
167 struct prkdf_object_s
169 /* Link to next item when used in a linked list. */
170 struct prkdf_object_s *next;
172 /* Length and allocated buffer with the Id of this object. */
174 unsigned char *objid;
176 /* Length and allocated buffer with the authId of this object or
177 NULL if no authID is known. */
179 unsigned char *authid;
181 /* The key's usage flags. */
182 keyusage_flags_t usageflags;
184 /* The keyReference and a flag telling whether it is valid. */
185 unsigned long key_reference;
186 int key_reference_valid;
188 /* Set to true if a length and offset is available. */
190 /* The offset and length of the object. They are only valid if
191 HAVE_OFF is true and set to 0 if HAVE_OFF is false. */
192 unsigned long off, len;
194 /* The length of the path as given in the PrKDF and the path itself.
195 path[0] is the top DF (usually 0x3f00). */
197 unsigned short path[1];
199 typedef struct prkdf_object_s *prkdf_object_t;
202 /* This is an object to store information about a Authentication
203 Object Directory File (AODF) in a format suitable for further
204 processing by us. To keep memory management, simple we use a linked
205 list of items; i.e. one such object represents one authentication
206 object and the list the entire AOKDF. */
209 /* Link to next item when used in a linked list. */
210 struct aodf_object_s *next;
212 /* Length and allocated buffer with the Id of this object. */
214 unsigned char *objid;
216 /* Length and allocated buffer with the authId of this object or
217 NULL if no authID is known. */
219 unsigned char *authid;
224 unsigned int case_sensitive: 1;
225 unsigned int local: 1;
226 unsigned int change_disabled: 1;
227 unsigned int unblock_disabled: 1;
228 unsigned int initialized: 1;
229 unsigned int needs_padding: 1;
230 unsigned int unblocking_pin: 1;
231 unsigned int so_pin: 1;
232 unsigned int disable_allowed: 1;
233 unsigned int integrity_protected: 1;
234 unsigned int confidentiality_protected: 1;
235 unsigned int exchange_ref_data: 1;
241 /* The minimum length of a PIN. */
242 unsigned long min_length;
244 /* The stored length of a PIN. */
245 unsigned long stored_length;
247 /* The maximum length of a PIN and a flag telling whether it is valid. */
248 unsigned long max_length;
249 int max_length_valid;
251 /* The pinReference and a flag telling whether it is valid. */
252 unsigned long pin_reference;
253 int pin_reference_valid;
255 /* The padChar and a flag telling whether it is valid. */
260 /* Set to true if a length and offset is available. */
262 /* The offset and length of the object. They are only valid if
263 HAVE_OFF is true and set to 0 if HAVE_OFF is false. */
264 unsigned long off, len;
266 /* The length of the path as given in the Aodf and the path itself.
267 path[0] is the top DF (usually 0x3f00). PATH is optional and thus
268 may be NULL. Malloced.*/
270 unsigned short *path;
272 typedef struct aodf_object_s *aodf_object_t;
275 /* Context local to this application. */
278 /* The home DF. Note, that we don't yet support a multilevel
279 hierarchy. Thus we assume this is directly below the MF. */
280 unsigned short home_df;
282 /* The type of the card. */
283 card_type_t card_type;
285 /* Flag indicating whether we may use direct path selection. */
286 int direct_path_selection;
288 /* Structure with the EFIDs of the objects described in the ODF
292 unsigned short private_keys;
293 unsigned short public_keys;
294 unsigned short trusted_public_keys;
295 unsigned short secret_keys;
296 unsigned short certificates;
297 unsigned short trusted_certificates;
298 unsigned short useful_certificates;
299 unsigned short data_objects;
300 unsigned short auth_objects;
303 /* The PKCS#15 serialnumber from EF(TokeiNFo) or NULL. Malloced. */
304 unsigned char *serialno;
307 /* Information on all certificates. */
308 cdf_object_t certificate_info;
309 /* Information on all trusted certificates. */
310 cdf_object_t trusted_certificate_info;
311 /* Information on all useful certificates. */
312 cdf_object_t useful_certificate_info;
314 /* Information on all private keys. */
315 prkdf_object_t private_key_info;
317 /* Information on all authentication objects. */
318 aodf_object_t auth_object_info;
323 /*** Local prototypes. ***/
324 static gpg_error_t readcert_by_cdf (app_t app, cdf_object_t cdf,
325 unsigned char **r_cert, size_t *r_certlen);
329 /* Release the CDF object A */
331 release_cdflist (cdf_object_t a)
335 cdf_object_t tmp = a->next;
343 /* Release the PrKDF object A. */
345 release_prkdflist (prkdf_object_t a)
349 prkdf_object_t tmp = a->next;
357 /* Release just one aodf object. */
359 release_aodf_object (aodf_object_t a)
370 /* Release the AODF list A. */
372 release_aodflist (aodf_object_t a)
376 aodf_object_t tmp = a->next;
377 release_aodf_object (a);
383 /* Release all local resources. */
385 do_deinit (app_t app)
387 if (app && app->app_local)
389 release_cdflist (app->app_local->certificate_info);
390 release_cdflist (app->app_local->trusted_certificate_info);
391 release_cdflist (app->app_local->useful_certificate_info);
392 release_prkdflist (app->app_local->private_key_info);
393 release_aodflist (app->app_local->auth_object_info);
394 xfree (app->app_local->serialno);
395 xfree (app->app_local);
396 app->app_local = NULL;
402 /* Do a select and a read for the file with EFID. EFID_DESC is a
403 desctription of the EF to be used with error messages. On success
404 BUFFER and BUFLEN contain the entire content of the EF. The caller
405 must free BUFFER only on success. */
407 select_and_read_binary (int slot, unsigned short efid, const char *efid_desc,
408 unsigned char **buffer, size_t *buflen)
412 err = iso7816_select_file (slot, efid, 0);
415 log_error ("error selecting %s (0x%04X): %s\n",
416 efid_desc, efid, gpg_strerror (err));
419 err = iso7816_read_binary (slot, 0, 0, buffer, buflen);
422 log_error ("error reading %s (0x%04X): %s\n",
423 efid_desc, efid, gpg_strerror (err));
430 /* This function calls select file to read a file using a complete
431 path which may or may not start at the master file (MF). */
433 select_ef_by_path (app_t app, const unsigned short *path, size_t pathlen)
439 return gpg_error (GPG_ERR_INV_VALUE);
441 if (pathlen && *path != 0x3f00 )
442 log_debug ("WARNING: relative path selection not yet implemented\n");
444 if (app->app_local->direct_path_selection)
446 err = iso7816_select_path (app->slot, path+1, pathlen-1);
449 log_error ("error selecting path ");
450 for (j=0; j < pathlen; j++)
451 log_printf ("%04hX", path[j]);
452 log_printf (": %s\n", gpg_strerror (err));
458 /* FIXME: Need code to remember the last PATH so that we can decide
459 what select commands to send in case the path does not start off
460 with 3F00. We might also want to use direct path selection if
461 supported by the card. */
462 for (i=0; i < pathlen; i++)
464 err = iso7816_select_file (app->slot, path[i], !(i+1 == pathlen));
467 log_error ("error selecting part %d from path ", i);
468 for (j=0; j < pathlen; j++)
469 log_printf ("%04hX", path[j]);
470 log_printf (": %s\n", gpg_strerror (err));
478 /* Parse a cert Id string (or a key Id string) and return the binary
479 object Id string in a newly allocated buffer stored at R_OBJID and
480 R_OBJIDLEN. On Error NULL will be stored there and an error code
481 returned. On success caller needs to free the buffer at R_OBJID. */
483 parse_certid (app_t app, const char *certid,
484 unsigned char **r_objid, size_t *r_objidlen)
489 unsigned char *objid;
495 if (app->app_local->home_df)
496 snprintf (tmpbuf, sizeof tmpbuf,
497 "P15-%04X.", (unsigned int)(app->app_local->home_df & 0xffff));
499 strcpy (tmpbuf, "P15.");
500 if (strncmp (certid, tmpbuf, strlen (tmpbuf)) )
502 if (!strncmp (certid, "P15.", 4)
503 || (!strncmp (certid, "P15-", 4)
504 && hexdigitp (certid+4)
505 && hexdigitp (certid+5)
506 && hexdigitp (certid+6)
507 && hexdigitp (certid+7)
508 && certid[8] == '.'))
509 return gpg_error (GPG_ERR_NOT_FOUND);
510 return gpg_error (GPG_ERR_INV_ID);
512 certid += strlen (tmpbuf);
514 for (s=certid, objidlen=0; hexdigitp (s); s++, objidlen++)
516 if (*s || !objidlen || (objidlen%2))
517 return gpg_error (GPG_ERR_INV_ID);
519 objid = xtrymalloc (objidlen);
521 return gpg_error_from_syserror ();
522 for (s=certid, i=0; i < objidlen; i++, s+=2)
523 objid[i] = xtoi_2 (s);
525 *r_objidlen = objidlen;
530 /* Find a certificate object by the certificate ID CERTID and store a
531 pointer to it at R_CDF. */
533 cdf_object_from_certid (app_t app, const char *certid, cdf_object_t *r_cdf)
537 unsigned char *objid;
540 err = parse_certid (app, certid, &objid, &objidlen);
544 for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
545 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
548 for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
549 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
552 for (cdf = app->app_local->useful_certificate_info; cdf; cdf = cdf->next)
553 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
557 return gpg_error (GPG_ERR_NOT_FOUND);
563 /* Find a private key object by the key Id string KEYIDSTR and store a
564 pointer to it at R_PRKDF. */
566 prkdf_object_from_keyidstr (app_t app, const char *keyidstr,
567 prkdf_object_t *r_prkdf)
571 unsigned char *objid;
572 prkdf_object_t prkdf;
574 err = parse_certid (app, keyidstr, &objid, &objidlen);
578 for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
579 if (prkdf->objidlen == objidlen && !memcmp (prkdf->objid, objid, objidlen))
583 return gpg_error (GPG_ERR_NOT_FOUND);
591 /* Read and parse the Object Directory File and store away the
592 pointers. ODF_FID shall contain the FID of the ODF.
594 Example of such a file:
596 A0 06 30 04 04 02 60 34 = Private Keys
597 A4 06 30 04 04 02 60 35 = Certificates
598 A5 06 30 04 04 02 60 36 = TrustedCertificates
599 A7 06 30 04 04 02 60 37 = DataObjects
600 A8 06 30 04 04 02 60 38 = AuthObjects
602 These are all PathOrObjects using the path CHOICE element. The
603 paths are octet strings of length 2. Using this Path CHOICE
604 element is recommended, so we only implement that for now.
607 read_ef_odf (app_t app, unsigned short odf_fid)
610 unsigned char *buffer, *p;
612 unsigned short value;
615 err = select_and_read_binary (app->slot, odf_fid, "ODF", &buffer, &buflen);
621 log_error ("error: ODF too short\n");
623 return gpg_error (GPG_ERR_INV_OBJ);
626 while (buflen && *p && *p != 0xff)
629 && (p[0] & 0xf0) == 0xA0
630 && !memcmp (p+1, "\x06\x30\x04\x04\x02", 5) )
634 else if ( buflen >= 12
635 && (p[0] & 0xf0) == 0xA0
636 && !memcmp (p+1, "\x0a\x30\x08\x04\x06\x3F\x00", 7)
637 && app->app_local->home_df == ((p[8]<<8)|p[9]) )
639 /* We only allow a full path if all files are at the same
640 level and below the home directory. The extend this we
641 would need to make use of new data type capable of
642 keeping a full path. */
647 log_error ("ODF format is not supported by us\n");
649 return gpg_error (GPG_ERR_INV_OBJ);
651 switch ((p[0] & 0x0f))
653 case 0: value = app->app_local->odf.private_keys; break;
654 case 1: value = app->app_local->odf.public_keys; break;
655 case 2: value = app->app_local->odf.trusted_public_keys; break;
656 case 3: value = app->app_local->odf.secret_keys; break;
657 case 4: value = app->app_local->odf.certificates; break;
658 case 5: value = app->app_local->odf.trusted_certificates; break;
659 case 6: value = app->app_local->odf.useful_certificates; break;
660 case 7: value = app->app_local->odf.data_objects; break;
661 case 8: value = app->app_local->odf.auth_objects; break;
662 default: value = 0; break;
666 log_error ("duplicate object type %d in ODF ignored\n",(p[0]&0x0f));
669 value = ((p[offset] << 8) | p[offset+1]);
670 switch ((p[0] & 0x0f))
672 case 0: app->app_local->odf.private_keys = value; break;
673 case 1: app->app_local->odf.public_keys = value; break;
674 case 2: app->app_local->odf.trusted_public_keys = value; break;
675 case 3: app->app_local->odf.secret_keys = value; break;
676 case 4: app->app_local->odf.certificates = value; break;
677 case 5: app->app_local->odf.trusted_certificates = value; break;
678 case 6: app->app_local->odf.useful_certificates = value; break;
679 case 7: app->app_local->odf.data_objects = value; break;
680 case 8: app->app_local->odf.auth_objects = value; break;
682 log_error ("unknown object type %d in ODF ignored\n", (p[0]&0x0f));
693 log_info ("warning: %u bytes of garbage detected at end of ODF\n",
694 (unsigned int)buflen);
701 /* Parse the BIT STRING with the keyUsageFlags from the
702 CommonKeyAttributes. */
704 parse_keyusage_flags (const unsigned char *der, size_t derlen,
705 keyusage_flags_t *usageflags)
707 unsigned int bits, mask;
710 memset (usageflags, 0, sizeof *usageflags);
712 return gpg_error (GPG_ERR_INV_OBJ);
714 unused = *der++; derlen--;
715 if ((!derlen && unused) || unused/8 > derlen)
716 return gpg_error (GPG_ERR_ENCODING_PROBLEM);
717 full = derlen - (unused+7)/8;
720 for (i=1; unused; i <<= 1, unused--)
726 bits = *der++; derlen--;
737 if ((bits & 0x80)) usageflags->encrypt = 1;
738 if ((bits & 0x40)) usageflags->decrypt = 1;
739 if ((bits & 0x20)) usageflags->sign = 1;
740 if ((bits & 0x10)) usageflags->sign_recover = 1;
741 if ((bits & 0x08)) usageflags->wrap = 1;
742 if ((bits & 0x04)) usageflags->unwrap = 1;
743 if ((bits & 0x02)) usageflags->verify = 1;
744 if ((bits & 0x01)) usageflags->verify_recover = 1;
749 bits = *der++; derlen--;
759 if ((bits & 0x80)) usageflags->derive = 1;
760 if ((bits & 0x40)) usageflags->non_repudiation = 1;
765 /* Read and parse the Private Key Directory Files. */
769 30 33 30 11 0C 08 53 4B 2E 43 48 2E 44 53 03 02 030...SK.CH.DS..
770 06 80 04 01 07 30 0C 04 01 01 03 03 06 00 40 02 .....0........@.
771 02 00 50 A1 10 30 0E 30 08 04 06 3F 00 40 16 00 ..P..0.0...?.@..
772 50 02 02 04 00 30 33 30 11 0C 08 53 4B 2E 43 48 P....030...SK.CH
773 2E 4B 45 03 02 06 80 04 01 0A 30 0C 04 01 0C 03 .KE.......0.....
774 03 06 44 00 02 02 00 52 A1 10 30 0E 30 08 04 06 ..D....R..0.0...
775 3F 00 40 16 00 52 02 02 04 00 30 34 30 12 0C 09 ?.@..R....040...
776 53 4B 2E 43 48 2E 41 55 54 03 02 06 80 04 01 0A SK.CH.AUT.......
777 30 0C 04 01 0D 03 03 06 20 00 02 02 00 51 A1 10 0....... ....Q..
778 30 0E 30 08 04 06 3F 00 40 16 00 51 02 02 04 00 0.0...?.@..Q....
779 30 37 30 15 0C 0C 53 4B 2E 43 48 2E 44 53 2D 53 070...SK.CH.DS-S
780 50 58 03 02 06 80 04 01 0A 30 0C 04 01 02 03 03 PX.......0......
781 06 20 00 02 02 00 53 A1 10 30 0E 30 08 04 06 3F . ....S..0.0...?
782 00 40 16 00 53 02 02 04 00 00 00 00 00 00 00 00 .@..S...........
783 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
784 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
787 2 30 17: SEQUENCE { -- commonObjectAttributes
788 4 0C 8: UTF8String 'SK.CH.DS'
789 14 03 2: BIT STRING 6 unused bits
791 18 04 1: OCTET STRING --authid
794 21 30 12: SEQUENCE { -- commonKeyAttributes
795 23 04 1: OCTET STRING
797 26 03 3: BIT STRING 6 unused bits
798 : '1000000000'B (bit 9)
799 31 02 2: INTEGER 80 -- keyReference (optional)
801 35 A1 16: [1] { -- keyAttributes
802 37 30 14: SEQUENCE { -- privateRSAKeyAttributes
803 39 30 8: SEQUENCE { -- objectValue
804 41 04 6: OCTET STRING --path
807 49 02 2: INTEGER 1024 -- modulus
815 read_ef_prkdf (app_t app, unsigned short fid, prkdf_object_t *result)
818 unsigned char *buffer = NULL;
820 const unsigned char *p;
821 size_t n, objlen, hdrlen;
822 int class, tag, constructed, ndef;
823 prkdf_object_t prkdflist = NULL;
827 return gpg_error (GPG_ERR_NO_DATA); /* No private keys. */
829 err = select_and_read_binary (app->slot, fid, "PrKDF", &buffer, &buflen);
836 /* FIXME: This shares a LOT of code with read_ef_cdf! */
838 /* Loop over the records. We stop as soon as we detect a new record
839 starting with 0x00 or 0xff as these values are commonly used to
840 pad data blocks and are no valid ASN.1 encoding. */
841 while (n && *p && *p != 0xff)
843 const unsigned char *pp;
846 const char *errstr = NULL;
847 prkdf_object_t prkdf = NULL;
849 const unsigned char *objid;
851 const unsigned char *authid = NULL;
852 size_t authidlen = 0;
853 keyusage_flags_t usageflags;
854 unsigned long key_reference = 0;
855 int key_reference_valid = 0;
858 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
859 &ndef, &objlen, &hdrlen);
860 if (!err && (objlen > n || tag != TAG_SEQUENCE))
861 err = gpg_error (GPG_ERR_INV_OBJ);
864 log_error ("error parsing PrKDF record: %s\n", gpg_strerror (err));
872 /* Parse the commonObjectAttributes. */
874 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
875 &ndef, &objlen, &hdrlen);
876 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
877 err = gpg_error (GPG_ERR_INV_OBJ);
881 const unsigned char *ppp = pp;
887 /* Search the optional AuthId. We need to skip the optional
888 Label (UTF8STRING) and the optional CommonObjectFlags
891 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
892 &ndef, &objlen, &hdrlen);
893 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
894 err = gpg_error (GPG_ERR_INV_OBJ);
895 if (gpg_err_code (err) == GPG_ERR_EOF)
899 if (tag == TAG_UTF8_STRING)
901 ppp += objlen; /* Skip the Label. */
905 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
906 &ndef, &objlen, &hdrlen);
907 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
908 err = gpg_error (GPG_ERR_INV_OBJ);
909 if (gpg_err_code (err) == GPG_ERR_EOF)
914 if (tag == TAG_BIT_STRING)
916 ppp += objlen; /* Skip the CommonObjectFlags. */
920 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
921 &ndef, &objlen, &hdrlen);
922 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
923 err = gpg_error (GPG_ERR_INV_OBJ);
924 if (gpg_err_code (err) == GPG_ERR_EOF)
929 if (tag == TAG_OCTET_STRING && objlen)
938 /* Parse the commonKeyAttributes. */
940 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
941 &ndef, &objlen, &hdrlen);
942 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
943 err = gpg_error (GPG_ERR_INV_OBJ);
947 const unsigned char *ppp = pp;
955 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
956 &ndef, &objlen, &hdrlen);
957 if (!err && (objlen > nnn
958 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
959 err = gpg_error (GPG_ERR_INV_OBJ);
967 /* Get the KeyUsageFlags. */
969 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
970 &ndef, &objlen, &hdrlen);
971 if (!err && (objlen > nnn
972 || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
973 err = gpg_error (GPG_ERR_INV_OBJ);
976 err = parse_keyusage_flags (ppp, objlen, &usageflags);
982 /* Find the keyReference */
984 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
985 &ndef, &objlen, &hdrlen);
986 if (gpg_err_code (err) == GPG_ERR_EOF)
988 if (!err && objlen > nnn)
989 err = gpg_error (GPG_ERR_INV_OBJ);
992 if (class == CLASS_UNIVERSAL && tag == TAG_BOOLEAN)
994 /* Skip the native element. */
998 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
999 &ndef, &objlen, &hdrlen);
1000 if (gpg_err_code (err) == GPG_ERR_EOF)
1002 if (!err && objlen > nnn)
1003 err = gpg_error (GPG_ERR_INV_OBJ);
1007 if (class == CLASS_UNIVERSAL && tag == TAG_BIT_STRING)
1009 /* Skip the accessFlags. */
1013 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1014 &ndef, &objlen, &hdrlen);
1015 if (gpg_err_code (err) == GPG_ERR_EOF)
1017 if (!err && objlen > nnn)
1018 err = gpg_error (GPG_ERR_INV_OBJ);
1022 if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
1024 /* Yep, this is the keyReference. */
1025 for (ul=0; objlen; objlen--)
1028 ul |= (*ppp++) & 0xff;
1032 key_reference_valid = 1;
1040 /* Skip subClassAttributes. */
1042 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1043 &ndef, &objlen, &hdrlen);
1044 if (!err && objlen > nn)
1045 err = gpg_error (GPG_ERR_INV_OBJ);
1048 if (class == CLASS_CONTEXT && tag == 0)
1054 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1055 &ndef, &objlen, &hdrlen);
1057 /* Parse the keyAttributes. */
1058 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1059 err = gpg_error (GPG_ERR_INV_OBJ);
1065 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1066 &ndef, &objlen, &hdrlen);
1067 if (!err && objlen > nn)
1068 err = gpg_error (GPG_ERR_INV_OBJ);
1071 if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
1073 else if (class == CLASS_CONTEXT)
1077 case 0: errstr = "EC key objects are not supported"; break;
1078 case 1: errstr = "DH key objects are not supported"; break;
1079 case 2: errstr = "DSA key objects are not supported"; break;
1080 case 3: errstr = "KEA key objects are not supported"; break;
1081 default: errstr = "unknown privateKeyObject"; break;
1087 err = gpg_error (GPG_ERR_INV_OBJ);
1093 /* Check that the reference is a Path object. */
1095 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1096 &ndef, &objlen, &hdrlen);
1097 if (!err && objlen > nn)
1098 err = gpg_error (GPG_ERR_INV_OBJ);
1101 if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
1103 errstr = "unsupported reference type";
1108 /* Parse the Path object. */
1110 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1111 &ndef, &objlen, &hdrlen);
1112 if (!err && objlen > nn)
1113 err = gpg_error (GPG_ERR_INV_OBJ);
1117 /* Make sure that the next element is a non zero path and of
1118 even length (FID are two bytes each). */
1119 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
1120 || !objlen || (objlen & 1) )
1122 errstr = "invalid path reference";
1125 /* Create a new PrKDF list item. */
1126 prkdf = xtrycalloc (1, (sizeof *prkdf
1127 - sizeof(unsigned short)
1128 + objlen/2 * sizeof(unsigned short)));
1131 err = gpg_error_from_syserror ();
1134 prkdf->objidlen = objidlen;
1135 prkdf->objid = xtrymalloc (objidlen);
1138 err = gpg_error_from_syserror ();
1142 memcpy (prkdf->objid, objid, objidlen);
1145 prkdf->authidlen = authidlen;
1146 prkdf->authid = xtrymalloc (authidlen);
1149 err = gpg_error_from_syserror ();
1150 xfree (prkdf->objid);
1154 memcpy (prkdf->authid, authid, authidlen);
1157 prkdf->pathlen = objlen/2;
1158 for (i=0; i < prkdf->pathlen; i++, pp += 2, nn -= 2)
1159 prkdf->path[i] = ((pp[0] << 8) | pp[1]);
1161 prkdf->usageflags = usageflags;
1162 prkdf->key_reference = key_reference;
1163 prkdf->key_reference_valid = key_reference_valid;
1167 /* An index and length follows. */
1168 prkdf->have_off = 1;
1170 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1171 &ndef, &objlen, &hdrlen);
1172 if (!err && (objlen > nn
1173 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1174 err = gpg_error (GPG_ERR_INV_OBJ);
1178 for (ul=0; objlen; objlen--)
1181 ul |= (*pp++) & 0xff;
1187 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1188 &ndef, &objlen, &hdrlen);
1189 if (!err && (objlen > nn
1190 || class != CLASS_CONTEXT || tag != 0))
1191 err = gpg_error (GPG_ERR_INV_OBJ);
1195 for (ul=0; objlen; objlen--)
1198 ul |= (*pp++) & 0xff;
1205 log_debug ("PrKDF %04hX: id=", fid);
1206 for (i=0; i < prkdf->objidlen; i++)
1207 log_printf ("%02X", prkdf->objid[i]);
1208 log_printf (" path=");
1209 for (i=0; i < prkdf->pathlen; i++)
1210 log_printf ("%04hX", prkdf->path[i]);
1211 if (prkdf->have_off)
1212 log_printf ("[%lu/%lu]", prkdf->off, prkdf->len);
1215 log_printf (" authid=");
1216 for (i=0; i < prkdf->authidlen; i++)
1217 log_printf ("%02X", prkdf->authid[i]);
1219 if (prkdf->key_reference_valid)
1220 log_printf (" keyref=0x%02lX", prkdf->key_reference);
1221 log_printf (" usage=");
1223 if (prkdf->usageflags.encrypt) log_printf ("%sencrypt", s), s = ",";
1224 if (prkdf->usageflags.decrypt) log_printf ("%sdecrypt", s), s = ",";
1225 if (prkdf->usageflags.sign ) log_printf ("%ssign", s), s = ",";
1226 if (prkdf->usageflags.sign_recover)
1227 log_printf ("%ssign_recover", s), s = ",";
1228 if (prkdf->usageflags.wrap ) log_printf ("%swrap", s), s = ",";
1229 if (prkdf->usageflags.unwrap ) log_printf ("%sunwrap", s), s = ",";
1230 if (prkdf->usageflags.verify ) log_printf ("%sverify", s), s = ",";
1231 if (prkdf->usageflags.verify_recover)
1232 log_printf ("%sverify_recover", s), s = ",";
1233 if (prkdf->usageflags.derive ) log_printf ("%sderive", s), s = ",";
1234 if (prkdf->usageflags.non_repudiation)
1235 log_printf ("%snon_repudiation", s), s = ",";
1238 /* Put it into the list. */
1239 prkdf->next = prkdflist;
1242 continue; /* Ready. */
1245 log_error ("error parsing PrKDF record (%d): %s - skipped\n",
1246 where, errstr? errstr : gpg_strerror (err));
1249 xfree (prkdf->objid);
1250 xfree (prkdf->authid);
1254 } /* End looping over all records. */
1259 release_prkdflist (prkdflist);
1261 *result = prkdflist;
1266 /* Read and parse the Certificate Directory Files identified by FID.
1267 On success a newlist of CDF object gets stored at RESULT and the
1268 caller is then responsible of releasing this list. On error a
1269 error code is returned and RESULT won't get changed. */
1271 read_ef_cdf (app_t app, unsigned short fid, cdf_object_t *result)
1274 unsigned char *buffer = NULL;
1276 const unsigned char *p;
1277 size_t n, objlen, hdrlen;
1278 int class, tag, constructed, ndef;
1279 cdf_object_t cdflist = NULL;
1283 return gpg_error (GPG_ERR_NO_DATA); /* No certificates. */
1285 err = select_and_read_binary (app->slot, fid, "CDF", &buffer, &buflen);
1292 /* Loop over the records. We stop as soon as we detect a new record
1293 starting with 0x00 or 0xff as these values are commonly used to
1294 pad data blocks and are no valid ASN.1 encoding. */
1295 while (n && *p && *p != 0xff)
1297 const unsigned char *pp;
1300 const char *errstr = NULL;
1301 cdf_object_t cdf = NULL;
1303 const unsigned char *objid;
1306 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1307 &ndef, &objlen, &hdrlen);
1308 if (!err && (objlen > n || tag != TAG_SEQUENCE))
1309 err = gpg_error (GPG_ERR_INV_OBJ);
1312 log_error ("error parsing CDF record: %s\n", gpg_strerror (err));
1320 /* Skip the commonObjectAttributes. */
1322 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1323 &ndef, &objlen, &hdrlen);
1324 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1325 err = gpg_error (GPG_ERR_INV_OBJ);
1331 /* Parse the commonCertificateAttributes. */
1333 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1334 &ndef, &objlen, &hdrlen);
1335 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1336 err = gpg_error (GPG_ERR_INV_OBJ);
1340 const unsigned char *ppp = pp;
1341 size_t nnn = objlen;
1348 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1349 &ndef, &objlen, &hdrlen);
1350 if (!err && (objlen > nnn
1351 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
1352 err = gpg_error (GPG_ERR_INV_OBJ);
1359 /* Parse the certAttribute. */
1361 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1362 &ndef, &objlen, &hdrlen);
1363 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1364 err = gpg_error (GPG_ERR_INV_OBJ);
1370 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1371 &ndef, &objlen, &hdrlen);
1372 if (!err && (objlen > nn
1373 || class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE))
1374 err = gpg_error (GPG_ERR_INV_OBJ);
1379 /* Check that the reference is a Path object. */
1381 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1382 &ndef, &objlen, &hdrlen);
1383 if (!err && objlen > nn)
1384 err = gpg_error (GPG_ERR_INV_OBJ);
1387 if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
1389 errstr = "unsupported reference type";
1394 /* Parse the Path object. */
1396 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1397 &ndef, &objlen, &hdrlen);
1398 if (!err && objlen > nn)
1399 err = gpg_error (GPG_ERR_INV_OBJ);
1403 /* Make sure that the next element is a non zero path and of
1404 even length (FID are two bytes each). */
1405 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
1406 || !objlen || (objlen & 1) )
1408 errstr = "invalid path reference";
1411 /* Create a new CDF list item. */
1412 cdf = xtrycalloc (1, (sizeof *cdf
1413 - sizeof(unsigned short)
1414 + objlen/2 * sizeof(unsigned short)));
1417 err = gpg_error_from_syserror ();
1420 cdf->objidlen = objidlen;
1421 cdf->objid = xtrymalloc (objidlen);
1424 err = gpg_error_from_syserror ();
1428 memcpy (cdf->objid, objid, objidlen);
1430 cdf->pathlen = objlen/2;
1431 for (i=0; i < cdf->pathlen; i++, pp += 2, nn -= 2)
1432 cdf->path[i] = ((pp[0] << 8) | pp[1]);
1436 /* An index and length follows. */
1439 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1440 &ndef, &objlen, &hdrlen);
1441 if (!err && (objlen > nn
1442 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1443 err = gpg_error (GPG_ERR_INV_OBJ);
1447 for (ul=0; objlen; objlen--)
1450 ul |= (*pp++) & 0xff;
1456 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1457 &ndef, &objlen, &hdrlen);
1458 if (!err && (objlen > nn
1459 || class != CLASS_CONTEXT || tag != 0))
1460 err = gpg_error (GPG_ERR_INV_OBJ);
1464 for (ul=0; objlen; objlen--)
1467 ul |= (*pp++) & 0xff;
1473 log_debug ("CDF %04hX: id=", fid);
1474 for (i=0; i < cdf->objidlen; i++)
1475 log_printf ("%02X", cdf->objid[i]);
1476 log_printf (" path=");
1477 for (i=0; i < cdf->pathlen; i++)
1478 log_printf ("%04hX", cdf->path[i]);
1480 log_printf ("[%lu/%lu]", cdf->off, cdf->len);
1483 /* Put it into the list. */
1484 cdf->next = cdflist;
1487 continue; /* Ready. */
1490 log_error ("error parsing CDF record (%d): %s - skipped\n",
1491 where, errstr? errstr : gpg_strerror (err));
1494 } /* End looping over all records. */
1499 release_cdflist (cdflist);
1508 SEQUENCE { -- CommonObjectAttributes
1509 UTF8String 'specific PIN for DS'
1510 BIT STRING 0 unused bits
1513 SEQUENCE { -- CommonAuthenticationObjectAttributes
1518 [1] { -- typeAttributes
1519 SEQUENCE { -- PinAttributes
1520 BIT STRING 0 unused bits
1521 '0000100000110010'B -- local,initialized,needs-padding
1523 ENUMERATED 1 -- ascii-numeric
1524 INTEGER 6 -- minLength
1525 INTEGER 6 -- storedLength
1526 INTEGER 8 -- maxLength
1529 GeneralizedTime 19/04/2002 12:12 GMT -- lastPinChange
1532 3F 00 40 16 -- path to DF of PIN
1539 /* Read and parse an Authentication Object Directory File identified
1540 by FID. On success a newlist of AODF objects gets stored at RESULT
1541 and the caller is responsible of releasing this list. On error a
1542 error code is returned and RESULT won't get changed. */
1544 read_ef_aodf (app_t app, unsigned short fid, aodf_object_t *result)
1547 unsigned char *buffer = NULL;
1549 const unsigned char *p;
1550 size_t n, objlen, hdrlen;
1551 int class, tag, constructed, ndef;
1552 aodf_object_t aodflist = NULL;
1556 return gpg_error (GPG_ERR_NO_DATA); /* No authentication objects. */
1558 err = select_and_read_binary (app->slot, fid, "AODF", &buffer, &buflen);
1565 /* FIXME: This shares a LOT of code with read_ef_prkdf! */
1567 /* Loop over the records. We stop as soon as we detect a new record
1568 starting with 0x00 or 0xff as these values are commonly used to
1569 pad data blocks and are no valid ASN.1 encoding. */
1570 while (n && *p && *p != 0xff)
1572 const unsigned char *pp;
1575 const char *errstr = NULL;
1576 aodf_object_t aodf = NULL;
1580 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1581 &ndef, &objlen, &hdrlen);
1582 if (!err && (objlen > n || tag != TAG_SEQUENCE))
1583 err = gpg_error (GPG_ERR_INV_OBJ);
1586 log_error ("error parsing AODF record: %s\n", gpg_strerror (err));
1594 /* Allocate memory for a new AODF list item. */
1595 aodf = xtrycalloc (1, sizeof *aodf);
1599 /* Parse the commonObjectAttributes. */
1601 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1602 &ndef, &objlen, &hdrlen);
1603 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1604 err = gpg_error (GPG_ERR_INV_OBJ);
1608 const unsigned char *ppp = pp;
1609 size_t nnn = objlen;
1614 /* Search the optional AuthId. We need to skip the optional
1615 Label (UTF8STRING) and the optional CommonObjectFlags
1618 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1619 &ndef, &objlen, &hdrlen);
1620 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1621 err = gpg_error (GPG_ERR_INV_OBJ);
1622 if (gpg_err_code (err) == GPG_ERR_EOF)
1626 if (tag == TAG_UTF8_STRING)
1628 ppp += objlen; /* Skip the Label. */
1632 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1633 &ndef, &objlen, &hdrlen);
1634 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1635 err = gpg_error (GPG_ERR_INV_OBJ);
1636 if (gpg_err_code (err) == GPG_ERR_EOF)
1641 if (tag == TAG_BIT_STRING)
1643 ppp += objlen; /* Skip the CommonObjectFlags. */
1647 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1648 &ndef, &objlen, &hdrlen);
1649 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1650 err = gpg_error (GPG_ERR_INV_OBJ);
1651 if (gpg_err_code (err) == GPG_ERR_EOF)
1656 if (tag == TAG_OCTET_STRING && objlen)
1658 aodf->authidlen = objlen;
1659 aodf->authid = xtrymalloc (objlen);
1662 memcpy (aodf->authid, ppp, objlen);
1668 /* Parse the CommonAuthenticationObjectAttributes. */
1670 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1671 &ndef, &objlen, &hdrlen);
1672 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1673 err = gpg_error (GPG_ERR_INV_OBJ);
1677 const unsigned char *ppp = pp;
1678 size_t nnn = objlen;
1685 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1686 &ndef, &objlen, &hdrlen);
1687 if (!err && (objlen > nnn
1688 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
1689 err = gpg_error (GPG_ERR_INV_OBJ);
1693 aodf->objidlen = objlen;
1694 aodf->objid = xtrymalloc (objlen);
1697 memcpy (aodf->objid, ppp, objlen);
1700 /* Parse the typeAttributes. */
1702 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1703 &ndef, &objlen, &hdrlen);
1704 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1705 err = gpg_error (GPG_ERR_INV_OBJ);
1711 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1712 &ndef, &objlen, &hdrlen);
1713 if (!err && objlen > nn)
1714 err = gpg_error (GPG_ERR_INV_OBJ);
1717 if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
1718 ; /* PinAttributes */
1719 else if (class == CLASS_CONTEXT)
1723 case 0: errstr = "biometric auth types are not supported"; break;
1724 case 1: errstr = "authKey auth types are not supported"; break;
1725 case 2: errstr = "external auth type are not supported"; break;
1726 default: errstr = "unknown privateKeyObject"; break;
1732 err = gpg_error (GPG_ERR_INV_OBJ);
1740 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1741 &ndef, &objlen, &hdrlen);
1742 if (!err && (objlen > nn || !objlen
1743 || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
1744 err = gpg_error (GPG_ERR_INV_OBJ);
1749 unsigned int bits, mask;
1752 unused = *pp++; nn--; objlen--;
1753 if ((!objlen && unused) || unused/8 > objlen)
1755 err = gpg_error (GPG_ERR_ENCODING_PROBLEM);
1758 full = objlen - (unused+7)/8;
1761 for (i=1; unused; i <<= 1, unused--)
1764 /* The first octet */
1768 bits = *pp++; nn--; objlen--;
1777 if ((bits & 0x80)) /* ASN.1 bit 0. */
1778 aodf->pinflags.case_sensitive = 1;
1779 if ((bits & 0x40)) /* ASN.1 bit 1. */
1780 aodf->pinflags.local = 1;
1782 aodf->pinflags.change_disabled = 1;
1784 aodf->pinflags.unblock_disabled = 1;
1786 aodf->pinflags.initialized = 1;
1788 aodf->pinflags.needs_padding = 1;
1790 aodf->pinflags.unblocking_pin = 1;
1792 aodf->pinflags.so_pin = 1;
1793 /* The second octet. */
1797 bits = *pp++; nn--; objlen--;
1806 aodf->pinflags.disable_allowed = 1;
1808 aodf->pinflags.integrity_protected = 1;
1810 aodf->pinflags.confidentiality_protected = 1;
1812 aodf->pinflags.exchange_ref_data = 1;
1813 /* Skip remaining bits. */
1821 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1822 &ndef, &objlen, &hdrlen);
1823 if (!err && (objlen > nn
1824 || class != CLASS_UNIVERSAL || tag != TAG_ENUMERATED))
1825 err = gpg_error (GPG_ERR_INV_OBJ);
1826 if (!err && objlen > sizeof (ul))
1827 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1831 for (ul=0; objlen; objlen--)
1834 ul |= (*pp++) & 0xff;
1842 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1843 &ndef, &objlen, &hdrlen);
1844 if (!err && (objlen > nn
1845 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1846 err = gpg_error (GPG_ERR_INV_OBJ);
1847 if (!err && objlen > sizeof (ul))
1848 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1851 for (ul=0; objlen; objlen--)
1854 ul |= (*pp++) & 0xff;
1857 aodf->min_length = ul;
1862 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1863 &ndef, &objlen, &hdrlen);
1864 if (!err && (objlen > nn
1865 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1866 err = gpg_error (GPG_ERR_INV_OBJ);
1867 if (!err && objlen > sizeof (ul))
1868 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1871 for (ul=0; objlen; objlen--)
1874 ul |= (*pp++) & 0xff;
1877 aodf->stored_length = ul;
1879 /* optional maxLength */
1881 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1882 &ndef, &objlen, &hdrlen);
1883 if (gpg_err_code (err) == GPG_ERR_EOF)
1885 if (!err && objlen > nn)
1886 err = gpg_error (GPG_ERR_INV_OBJ);
1889 if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
1891 if (objlen > sizeof (ul))
1893 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1896 for (ul=0; objlen; objlen--)
1899 ul |= (*pp++) & 0xff;
1902 aodf->max_length = ul;
1903 aodf->max_length_valid = 1;
1906 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1907 &ndef, &objlen, &hdrlen);
1908 if (gpg_err_code (err) == GPG_ERR_EOF)
1910 if (!err && objlen > nn)
1911 err = gpg_error (GPG_ERR_INV_OBJ);
1916 /* Optional pinReference. */
1917 if (class == CLASS_CONTEXT && tag == 0)
1919 if (objlen > sizeof (ul))
1921 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1924 for (ul=0; objlen; objlen--)
1927 ul |= (*pp++) & 0xff;
1930 aodf->pin_reference = ul;
1931 aodf->pin_reference_valid = 1;
1934 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1935 &ndef, &objlen, &hdrlen);
1936 if (gpg_err_code (err) == GPG_ERR_EOF)
1938 if (!err && objlen > nn)
1939 err = gpg_error (GPG_ERR_INV_OBJ);
1944 /* Optional padChar. */
1945 if (class == CLASS_UNIVERSAL && tag == TAG_OCTET_STRING)
1949 errstr = "padChar is not of size(1)";
1952 aodf->pad_char = *pp++; nn--;
1953 aodf->pad_char_valid = 1;
1956 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1957 &ndef, &objlen, &hdrlen);
1958 if (gpg_err_code (err) == GPG_ERR_EOF)
1960 if (!err && objlen > nn)
1961 err = gpg_error (GPG_ERR_INV_OBJ);
1966 /* Skip optional lastPinChange. */
1967 if (class == CLASS_UNIVERSAL && tag == TAG_GENERALIZED_TIME)
1973 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1974 &ndef, &objlen, &hdrlen);
1975 if (gpg_err_code (err) == GPG_ERR_EOF)
1977 if (!err && objlen > nn)
1978 err = gpg_error (GPG_ERR_INV_OBJ);
1983 /* Optional Path object. */
1984 if (class == CLASS_UNIVERSAL || tag == TAG_SEQUENCE)
1986 const unsigned char *ppp = pp;
1987 size_t nnn = objlen;
1993 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1994 &ndef, &objlen, &hdrlen);
1995 if (!err && objlen > nnn)
1996 err = gpg_error (GPG_ERR_INV_OBJ);
2000 /* Make sure that the next element is a non zero FID and of
2001 even length (FID are two bytes each). */
2002 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
2003 || !objlen || (objlen & 1) )
2005 errstr = "invalid path reference";
2009 aodf->pathlen = objlen/2;
2010 aodf->path = xtrymalloc (aodf->pathlen);
2013 for (i=0; i < aodf->pathlen; i++, ppp += 2, nnn -= 2)
2014 aodf->path[i] = ((ppp[0] << 8) | ppp[1]);
2018 /* An index and length follows. */
2021 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
2022 &ndef, &objlen, &hdrlen);
2023 if (!err && (objlen > nnn
2024 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
2025 err = gpg_error (GPG_ERR_INV_OBJ);
2029 for (ul=0; objlen; objlen--)
2032 ul |= (*ppp++) & 0xff;
2038 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
2039 &ndef, &objlen, &hdrlen);
2040 if (!err && (objlen > nnn
2041 || class != CLASS_CONTEXT || tag != 0))
2042 err = gpg_error (GPG_ERR_INV_OBJ);
2046 for (ul=0; objlen; objlen--)
2049 ul |= (*ppp++) & 0xff;
2056 /* Igonore further objects which might be there due to future
2057 extensions of pkcs#15. */
2060 log_debug ("AODF %04hX: id=", fid);
2061 for (i=0; i < aodf->objidlen; i++)
2062 log_printf ("%02X", aodf->objid[i]);
2065 log_printf (" authid=");
2066 for (i=0; i < aodf->authidlen; i++)
2067 log_printf ("%02X", aodf->authid[i]);
2069 log_printf (" flags=");
2071 if (aodf->pinflags.case_sensitive)
2072 log_printf ("%scase_sensitive", s), s = ",";
2073 if (aodf->pinflags.local)
2074 log_printf ("%slocal", s), s = ",";
2075 if (aodf->pinflags.change_disabled)
2076 log_printf ("%schange_disabled", s), s = ",";
2077 if (aodf->pinflags.unblock_disabled)
2078 log_printf ("%sunblock_disabled", s), s = ",";
2079 if (aodf->pinflags.initialized)
2080 log_printf ("%sinitialized", s), s = ",";
2081 if (aodf->pinflags.needs_padding)
2082 log_printf ("%sneeds_padding", s), s = ",";
2083 if (aodf->pinflags.unblocking_pin)
2084 log_printf ("%sunblocking_pin", s), s = ",";
2085 if (aodf->pinflags.so_pin)
2086 log_printf ("%sso_pin", s), s = ",";
2087 if (aodf->pinflags.disable_allowed)
2088 log_printf ("%sdisable_allowed", s), s = ",";
2089 if (aodf->pinflags.integrity_protected)
2090 log_printf ("%sintegrity_protected", s), s = ",";
2091 if (aodf->pinflags.confidentiality_protected)
2092 log_printf ("%sconfidentiality_protected", s), s = ",";
2093 if (aodf->pinflags.exchange_ref_data)
2094 log_printf ("%sexchange_ref_data", s), s = ",";
2097 switch (aodf->pintype)
2099 case PIN_TYPE_BCD: s = "bcd"; break;
2100 case PIN_TYPE_ASCII_NUMERIC: s = "ascii-numeric"; break;
2101 case PIN_TYPE_UTF8: s = "utf8"; break;
2102 case PIN_TYPE_HALF_NIBBLE_BCD: s = "half-nibble-bcd"; break;
2103 case PIN_TYPE_ISO9564_1: s = "iso9564-1"; break;
2105 sprintf (numbuf, "%lu", (unsigned long)aodf->pintype);
2108 log_printf (" type=%s", s);
2110 log_printf (" min=%lu", aodf->min_length);
2111 log_printf (" stored=%lu", aodf->stored_length);
2112 if (aodf->max_length_valid)
2113 log_printf (" max=%lu", aodf->max_length);
2114 if (aodf->pad_char_valid)
2115 log_printf (" pad=0x%02x", aodf->pad_char);
2116 if (aodf->pin_reference_valid)
2117 log_printf (" pinref=0x%02lX", aodf->pin_reference);
2120 log_printf (" path=");
2121 for (i=0; i < aodf->pathlen; i++)
2122 log_printf ("%04hX", aodf->path[i]);
2124 log_printf ("[%lu/%lu]", aodf->off, aodf->len);
2128 /* Put it into the list. */
2129 aodf->next = aodflist;
2132 continue; /* Ready. */
2135 err = gpg_error_from_syserror ();
2136 release_aodf_object (aodf);
2140 log_error ("error parsing AODF record (%d): %s - skipped\n",
2141 where, errstr? errstr : gpg_strerror (err));
2143 release_aodf_object (aodf);
2144 } /* End looping over all records. */
2149 release_aodflist (aodflist);
2159 /* Read and parse the EF(TokenInfo).
2161 TokenInfo ::= SEQUENCE {
2162 version INTEGER {v1(0)} (v1,...),
2163 serialNumber OCTET STRING,
2164 manufacturerID Label OPTIONAL,
2165 label [0] Label OPTIONAL,
2166 tokenflags TokenFlags,
2167 seInfo SEQUENCE OF SecurityEnvironmentInfo OPTIONAL,
2168 recordInfo [1] RecordInfo OPTIONAL,
2169 supportedAlgorithms [2] SEQUENCE OF AlgorithmInfo OPTIONAL,
2171 issuerId [3] Label OPTIONAL,
2172 holderId [4] Label OPTIONAL,
2173 lastUpdate [5] LastUpdate OPTIONAL,
2174 preferredLanguage PrintableString OPTIONAL -- In accordance with
2176 } (CONSTRAINED BY { -- Each AlgorithmInfo.reference value must be unique --})
2178 TokenFlags ::= BIT STRING {
2188 30 31 02 01 00 04 04 05 45 36 9F 0C 0C 44 2D 54 01......E6...D-T
2189 72 75 73 74 20 47 6D 62 48 80 14 4F 66 66 69 63 rust GmbH..Offic
2190 65 20 69 64 65 6E 74 69 74 79 20 63 61 72 64 03 e identity card.
2191 02 00 40 20 63 61 72 64 03 02 00 40 00 00 00 00 ..@ card...@....
2192 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
2196 5 4: OCTET STRING 05 45 36 9F
2197 11 12: UTF8String 'D-Trust GmbH'
2198 25 20: [0] 'Office identity card'
2200 : '00000010'B (bit 1)
2201 : Error: Spurious zero bits in bitstring.
2209 read_ef_tokeninfo (app_t app)
2212 unsigned char *buffer = NULL;
2214 const unsigned char *p;
2215 size_t n, objlen, hdrlen;
2216 int class, tag, constructed, ndef;
2219 err = select_and_read_binary (app->slot, 0x5032, "TokenInfo",
2227 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2228 &ndef, &objlen, &hdrlen);
2229 if (!err && (objlen > n || tag != TAG_SEQUENCE))
2230 err = gpg_error (GPG_ERR_INV_OBJ);
2233 log_error ("error parsing TokenInfo: %s\n", gpg_strerror (err));
2240 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2241 &ndef, &objlen, &hdrlen);
2242 if (!err && (objlen > n || tag != TAG_INTEGER))
2243 err = gpg_error (GPG_ERR_INV_OBJ);
2247 for (ul=0; objlen; objlen--)
2250 ul |= (*p++) & 0xff;
2255 log_error ("invalid version %lu in TokenInfo\n", ul);
2256 err = gpg_error (GPG_ERR_INV_OBJ);
2261 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2262 &ndef, &objlen, &hdrlen);
2263 if (!err && (objlen > n || tag != TAG_OCTET_STRING || !objlen))
2264 err = gpg_error (GPG_ERR_INV_OBJ);
2268 xfree (app->app_local->serialno);
2269 app->app_local->serialno = xtrymalloc (objlen);
2270 if (!app->app_local->serialno)
2272 err = gpg_error_from_syserror ();
2275 memcpy (app->app_local->serialno, p, objlen);
2276 app->app_local->serialnolen = objlen;
2277 log_printhex ("Serialnumber from EF(TokenInfo) is:", p, objlen);
2285 /* Get all the basic information from the pkcs#15 card, check the
2286 structure and initialize our local context. This is used once at
2287 application initialization. */
2289 read_p15_info (app_t app)
2293 if (!read_ef_tokeninfo (app))
2295 /* If we don't have a serial number yet but the TokenInfo provides
2297 if (!app->serialno && app->app_local->serialno)
2299 app->serialno = app->app_local->serialno;
2300 app->serialnolen = app->app_local->serialnolen;
2301 app->app_local->serialno = NULL;
2302 app->app_local->serialnolen = 0;
2303 err = app_munge_serialno (app);
2309 /* Read the ODF so that we know the location of all directory
2311 /* Fixme: We might need to get a non-standard ODF FID from TokenInfo. */
2312 err = read_ef_odf (app, 0x5031);
2316 /* Read certificate information. */
2317 assert (!app->app_local->certificate_info);
2318 assert (!app->app_local->trusted_certificate_info);
2319 assert (!app->app_local->useful_certificate_info);
2320 err = read_ef_cdf (app, app->app_local->odf.certificates,
2321 &app->app_local->certificate_info);
2322 if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
2323 err = read_ef_cdf (app, app->app_local->odf.trusted_certificates,
2324 &app->app_local->trusted_certificate_info);
2325 if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
2326 err = read_ef_cdf (app, app->app_local->odf.useful_certificates,
2327 &app->app_local->useful_certificate_info);
2328 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
2333 /* Read information about private keys. */
2334 assert (!app->app_local->private_key_info);
2335 err = read_ef_prkdf (app, app->app_local->odf.private_keys,
2336 &app->app_local->private_key_info);
2337 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
2342 /* Read information about authentication objects. */
2343 assert (!app->app_local->auth_object_info);
2344 err = read_ef_aodf (app, app->app_local->odf.auth_objects,
2345 &app->app_local->auth_object_info);
2346 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
2354 /* Helper to do_learn_status: Send information about all certificates
2355 listed in CERTINFO back. Use CERTTYPE as type of the
2358 send_certinfo (app_t app, ctrl_t ctrl, const char *certtype,
2359 cdf_object_t certinfo)
2361 for (; certinfo; certinfo = certinfo->next)
2365 buf = xtrymalloc (9 + certinfo->objidlen*2 + 1);
2367 return gpg_error_from_syserror ();
2368 p = stpcpy (buf, "P15");
2369 if (app->app_local->home_df)
2371 snprintf (p, 6, "-%04X",
2372 (unsigned int)(app->app_local->home_df & 0xffff));
2375 p = stpcpy (p, ".");
2376 bin2hex (certinfo->objid, certinfo->objidlen, p);
2378 send_status_info (ctrl, "CERTINFO",
2379 certtype, strlen (certtype),
2388 /* Get the keygrip of the private key object PRKDF. On success the
2389 keygrip gets returned in the caller provided 41 byte buffer
2392 keygripstr_from_prkdf (app_t app, prkdf_object_t prkdf, char *r_gripstr)
2400 /* FIXME: We should check whether a public key directory file and a
2401 matching public key for PRKDF is available. This should make
2402 extraction of the key much easier. My current test card doesn't
2403 have one, so we can only use the fallback solution bu looking for
2404 a matching certificate and extract the key from there. */
2406 /* Look for a matching certificate. A certificate matches if the Id
2407 matches the one of the private key info. */
2408 for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
2409 if (cdf->objidlen == prkdf->objidlen
2410 && !memcmp (cdf->objid, prkdf->objid, prkdf->objidlen))
2413 for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
2414 if (cdf->objidlen == prkdf->objidlen
2415 && !memcmp (cdf->objid, prkdf->objid, prkdf->objidlen))
2418 for (cdf = app->app_local->useful_certificate_info; cdf; cdf = cdf->next)
2419 if (cdf->objidlen == prkdf->objidlen
2420 && !memcmp (cdf->objid, prkdf->objid, prkdf->objidlen))
2423 return gpg_error (GPG_ERR_NOT_FOUND);
2425 err = readcert_by_cdf (app, cdf, &der, &derlen);
2429 err = ksba_cert_new (&cert);
2431 err = ksba_cert_init_from_mem (cert, der, derlen);
2434 err = app_help_get_keygrip_string (cert, r_gripstr);
2435 ksba_cert_release (cert);
2443 /* Helper to do_learn_status: Send information about all known
2444 keypairs back. FIXME: much code duplication from
2447 send_keypairinfo (app_t app, ctrl_t ctrl, prkdf_object_t keyinfo)
2451 for (; keyinfo; keyinfo = keyinfo->next)
2457 buf = xtrymalloc (9 + keyinfo->objidlen*2 + 1);
2459 return gpg_error_from_syserror ();
2460 p = stpcpy (buf, "P15");
2461 if (app->app_local->home_df)
2463 snprintf (p, 6, "-%04X",
2464 (unsigned int)(app->app_local->home_df & 0xffff));
2467 p = stpcpy (p, ".");
2468 bin2hex (keyinfo->objid, keyinfo->objidlen, p);
2470 err = keygripstr_from_prkdf (app, keyinfo, gripstr);
2473 log_error ("can't get keygrip from ");
2474 for (j=0; j < keyinfo->pathlen; j++)
2475 log_printf ("%04hX", keyinfo->path[j]);
2476 log_printf (": %s\n", gpg_strerror (err));
2480 assert (strlen (gripstr) == 40);
2481 send_status_info (ctrl, "KEYPAIRINFO",
2493 /* This is the handler for the LEARN command. */
2495 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
2503 err = send_certinfo (app, ctrl, "100", app->app_local->certificate_info);
2505 err = send_certinfo (app, ctrl, "101",
2506 app->app_local->trusted_certificate_info);
2508 err = send_certinfo (app, ctrl, "102",
2509 app->app_local->useful_certificate_info);
2513 err = send_keypairinfo (app, ctrl, app->app_local->private_key_info);
2519 /* Read a certifciate using the information in CDF and return the
2520 certificate in a newly llocated buffer R_CERT and its length
2523 readcert_by_cdf (app_t app, cdf_object_t cdf,
2524 unsigned char **r_cert, size_t *r_certlen)
2527 unsigned char *buffer = NULL;
2528 const unsigned char *p, *save_p;
2530 int class, tag, constructed, ndef;
2531 size_t totobjlen, objlen, hdrlen;
2538 /* First check whether it has been cached. */
2541 *r_cert = xtrymalloc (cdf->imagelen);
2543 return gpg_error_from_syserror ();
2544 memcpy (*r_cert, cdf->image, cdf->imagelen);
2545 *r_certlen = cdf->imagelen;
2549 /* Read the entire file. fixme: This could be optimized by first
2550 reading the header to figure out how long the certificate
2552 err = select_ef_by_path (app, cdf->path, cdf->pathlen);
2556 err = iso7816_read_binary (app->slot, cdf->off, cdf->len, &buffer, &buflen);
2557 if (!err && (!buflen || *buffer == 0xff))
2558 err = gpg_error (GPG_ERR_NOT_FOUND);
2561 log_error ("error reading certificate with Id ");
2562 for (i=0; i < cdf->objidlen; i++)
2563 log_printf ("%02X", cdf->objid[i]);
2564 log_printf (": %s\n", gpg_strerror (err));
2568 /* Check whether this is really a certificate. */
2571 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2572 &ndef, &objlen, &hdrlen);
2576 if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed)
2578 else if ( class == CLASS_UNIVERSAL && tag == TAG_SET && constructed )
2582 err = gpg_error (GPG_ERR_INV_OBJ);
2585 totobjlen = objlen + hdrlen;
2586 assert (totobjlen <= buflen);
2588 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2589 &ndef, &objlen, &hdrlen);
2594 && class == CLASS_UNIVERSAL && tag == TAG_OBJECT_ID && !constructed)
2596 /* The certificate seems to be contained in a userCertificate
2597 container. Skip this and assume the following sequence is
2601 err = gpg_error (GPG_ERR_INV_OBJ);
2607 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2608 &ndef, &objlen, &hdrlen);
2611 if ( !(class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed) )
2613 err = gpg_error (GPG_ERR_INV_OBJ);
2616 totobjlen = objlen + hdrlen;
2617 assert (save_p + totobjlen <= buffer + buflen);
2618 memmove (buffer, save_p, totobjlen);
2623 *r_certlen = totobjlen;
2625 /* Try to cache it. */
2626 if (!cdf->image && (cdf->image = xtrymalloc (*r_certlen)))
2628 memcpy (cdf->image, *r_cert, *r_certlen);
2629 cdf->imagelen = *r_certlen;
2639 /* Handler for the READCERT command.
2641 Read the certificate with id CERTID (as returned by learn_status in
2642 the CERTINFO status lines) and return it in the freshly allocated
2643 buffer to be stored at R_CERT and its length at R_CERTLEN. A error
2644 code will be returned on failure and R_CERT and R_CERTLEN will be
2647 do_readcert (app_t app, const char *certid,
2648 unsigned char **r_cert, size_t *r_certlen)
2655 err = cdf_object_from_certid (app, certid, &cdf);
2657 err = readcert_by_cdf (app, cdf, r_cert, r_certlen);
2663 /* Implement the GETATTR command. This is similar to the LEARN
2664 command but returns just one value via the status interface. */
2666 do_getattr (app_t app, ctrl_t ctrl, const char *name)
2670 if (!strcmp (name, "$AUTHKEYID"))
2673 prkdf_object_t prkdf;
2675 /* We return the ID of the first private keycapable of
2677 for (prkdf = app->app_local->private_key_info; prkdf;
2678 prkdf = prkdf->next)
2679 if (prkdf->usageflags.sign)
2683 buf = xtrymalloc (9 + prkdf->objidlen*2 + 1);
2685 return gpg_error_from_syserror ();
2686 p = stpcpy (buf, "P15");
2687 if (app->app_local->home_df)
2689 snprintf (p, 6, "-%04X",
2690 (unsigned int)(app->app_local->home_df & 0xffff));
2693 p = stpcpy (p, ".");
2694 bin2hex (prkdf->objid, prkdf->objidlen, p);
2696 send_status_info (ctrl, name, buf, strlen (buf), NULL, 0);
2701 else if (!strcmp (name, "$DISPSERIALNO"))
2703 /* For certain cards we return special IDs. There is no
2704 general rule for it so we need to decide case by case. */
2705 if (app->app_local->card_type == CARD_TYPE_BELPIC)
2707 /* The eID card has a card number printed on the front matter
2708 which seems to be a good indication. */
2709 unsigned char *buffer;
2710 const unsigned char *p;
2712 unsigned short path[] = { 0x3F00, 0xDF01, 0x4031 };
2714 err = select_ef_by_path (app, path, DIM(path) );
2716 err = iso7816_read_binary (app->slot, 0, 0, &buffer, &buflen);
2719 log_error ("error accessing EF(ID): %s\n", gpg_strerror (err));
2723 p = find_tlv (buffer, buflen, 1, &n);
2729 memcpy (tmp+4, p+3, 7);
2731 memcpy (tmp+12, p+10, 2);
2733 send_status_info (ctrl, name, tmp, strlen (tmp), NULL, 0);
2741 return gpg_error (GPG_ERR_INV_NAME);
2747 /* Micardo cards require special treatment. This is a helper for the
2748 crypto functions to manage the security environment. We expect that
2749 the key file has already been selected. FID is the one of the
2752 micardo_mse (app_t app, unsigned short fid)
2756 unsigned short refdata = 0;
2758 unsigned char msebuf[10];
2760 /* Read the KeyD file containing extra information on keys. */
2761 err = iso7816_select_file (app->slot, 0x0013, 0);
2764 log_error ("error reading EF_keyD: %s\n", gpg_strerror (err));
2768 for (recno = 1, se_num = -1; ; recno++)
2770 unsigned char *buffer;
2773 const unsigned char *p, *pp;
2775 err = iso7816_read_record (app->slot, recno, 1, 0, &buffer, &buflen);
2776 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2780 log_error ("error reading EF_keyD record: %s\n",
2781 gpg_strerror (err));
2784 log_printhex ("keyD record:", buffer, buflen);
2785 p = find_tlv (buffer, buflen, 0x83, &n);
2786 if (p && n == 4 && ((p[2]<<8)|p[3]) == fid)
2788 refdata = ((p[0]<<8)|p[1]);
2789 /* Locate the SE DO and the there included sec env number. */
2790 p = find_tlv (buffer, buflen, 0x7b, &n);
2793 pp = find_tlv (p, n, 0x80, &nn);
2806 log_error ("CRT for keyfile %04hX not found\n", fid);
2807 return gpg_error (GPG_ERR_NOT_FOUND);
2811 /* Restore the security environment to SE_NUM if needed */
2814 err = iso7816_manage_security_env (app->slot, 0xf3, se_num, NULL, 0);
2817 log_error ("restoring SE to %d failed: %s\n",
2818 se_num, gpg_strerror (err));
2823 /* Set the DST reference data. */
2827 msebuf[3] = (refdata >> 8);
2828 msebuf[4] = refdata;
2829 err = iso7816_manage_security_env (app->slot, 0x41, 0xb6, msebuf, 5);
2832 log_error ("setting SE to reference file %04hX failed: %s\n",
2833 refdata, gpg_strerror (err));
2841 /* Handler for the PKSIGN command.
2843 Create the signature and return the allocated result in OUTDATA.
2844 If a PIN is required, the PINCB will be used to ask for the PIN;
2845 that callback should return the PIN in an allocated buffer and
2846 store that as the 3rd argument. */
2848 do_sign (app_t app, const char *keyidstr, int hashalgo,
2849 gpg_error_t (*pincb)(void*, const char *, char **),
2851 const void *indata, size_t indatalen,
2852 unsigned char **outdata, size_t *outdatalen )
2854 static unsigned char sha1_prefix[15] = /* Object ID is 1.3.14.3.2.26 */
2855 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
2856 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
2857 static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
2858 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
2859 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
2863 unsigned char data[36]; /* Must be large enough for a SHA-1 digest
2864 + the largest OID prefix above and also
2865 fit the 36 bytes of md5sha1. */
2866 prkdf_object_t prkdf; /* The private key object. */
2867 aodf_object_t aodf; /* The associated authentication object. */
2868 int no_data_padding = 0; /* True if the card want the data without padding.*/
2869 int mse_done = 0; /* Set to true if the MSE has been done. */
2871 if (!keyidstr || !*keyidstr)
2872 return gpg_error (GPG_ERR_INV_VALUE);
2873 if (indatalen != 20 && indatalen != 16 && indatalen != 35 && indatalen != 36)
2874 return gpg_error (GPG_ERR_INV_VALUE);
2876 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
2879 if (!(prkdf->usageflags.sign || prkdf->usageflags.sign_recover
2880 ||prkdf->usageflags.non_repudiation))
2882 log_error ("key %s may not be used for signing\n", keyidstr);
2883 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
2888 log_error ("no authentication object defined for %s\n", keyidstr);
2889 /* fixme: we might want to go ahead and do without PIN
2891 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2894 /* Find the authentication object to this private key object. */
2895 for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
2896 if (aodf->objidlen == prkdf->authidlen
2897 && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
2901 log_error ("authentication object for %s missing\n", keyidstr);
2902 return gpg_error (GPG_ERR_INV_CARD);
2906 log_error ("PIN verification is protected by an "
2907 "additional authentication token\n");
2908 return gpg_error (GPG_ERR_BAD_PIN_METHOD);
2910 if (aodf->pinflags.integrity_protected
2911 || aodf->pinflags.confidentiality_protected)
2913 log_error ("PIN verification requires unsupported protection method\n");
2914 return gpg_error (GPG_ERR_BAD_PIN_METHOD);
2916 if (!aodf->stored_length && aodf->pinflags.needs_padding)
2918 log_error ("PIN verification requires padding but no length known\n");
2919 return gpg_error (GPG_ERR_INV_CARD);
2922 /* Select the key file. Note that this may change the security
2923 environment thus we do it before PIN verification. */
2924 err = select_ef_by_path (app, prkdf->path, prkdf->pathlen);
2927 log_error ("error selecting file for key %s: %s\n",
2928 keyidstr, gpg_strerror (errno));
2933 /* Due to the fact that the non-repudiation signature on a BELPIC
2934 card requires a verify immediately before the DSO we set the
2935 MSE before we do the verification. Other cards might also allow
2936 this but I don't want to break anything, thus we do it only
2937 for the BELPIC card here. */
2938 if (app->app_local->card_type == CARD_TYPE_BELPIC)
2940 unsigned char mse[5];
2942 mse[0] = 4; /* Length of the template. */
2943 mse[1] = 0x80; /* Algorithm reference tag. */
2944 if (hashalgo == MD_USER_TLS_MD5SHA1)
2945 mse[2] = 0x01; /* Let card do pkcs#1 0xFF padding. */
2947 mse[2] = 0x02; /* RSASSA-PKCS1-v1.5 using SHA1. */
2948 mse[3] = 0x84; /* Private key reference tag. */
2949 mse[4] = prkdf->key_reference_valid? prkdf->key_reference : 0x82;
2951 err = iso7816_manage_security_env (app->slot,
2954 no_data_padding = 1;
2959 log_error ("MSE failed: %s\n", gpg_strerror (err));
2964 /* Now that we have all the information available, prepare and run
2965 the PIN verification.*/
2973 if (prkdf->usageflags.non_repudiation
2974 && app->app_local->card_type == CARD_TYPE_BELPIC)
2975 err = pincb (pincb_arg, "PIN (qualified signature!)", &pinvalue);
2977 err = pincb (pincb_arg, "PIN", &pinvalue);
2980 log_info ("PIN callback returned error: %s\n", gpg_strerror (err));
2984 /* We might need to cope with UTF8 things here. Not sure how
2985 min_length etc. are exactly defined, for now we take them as
2986 a plain octet count. */
2988 if (strlen (pinvalue) < aodf->min_length)
2990 log_error ("PIN is too short; minimum length is %lu\n",
2992 err = gpg_error (GPG_ERR_BAD_PIN);
2994 else if (aodf->stored_length && strlen (pinvalue) > aodf->stored_length)
2996 /* This would otherwise truncate the PIN silently. */
2997 log_error ("PIN is too large; maximum length is %lu\n",
2998 aodf->stored_length);
2999 err = gpg_error (GPG_ERR_BAD_PIN);
3001 else if (aodf->max_length_valid && strlen (pinvalue) > aodf->max_length)
3003 log_error ("PIN is too large; maximum length is %lu\n",
3005 err = gpg_error (GPG_ERR_BAD_PIN);
3016 switch (aodf->pintype)
3019 case PIN_TYPE_ASCII_NUMERIC:
3020 for (s=pinvalue; digitp (s); s++)
3024 errstr = "Non-numeric digits found in PIN";
3025 err = gpg_error (GPG_ERR_BAD_PIN);
3030 case PIN_TYPE_HALF_NIBBLE_BCD:
3031 errstr = "PIN type Half-Nibble-BCD is not supported";
3033 case PIN_TYPE_ISO9564_1:
3034 errstr = "PIN type ISO9564-1 is not supported";
3037 errstr = "Unknown PIN type";
3042 log_error ("can't verify PIN: %s\n", errstr);
3044 return err? err : gpg_error (GPG_ERR_BAD_PIN_METHOD);
3048 if (aodf->pintype == PIN_TYPE_BCD )
3053 for (ndigits=0, s=pinvalue; *s; ndigits++, s++)
3055 paddedpin = xtrymalloc (aodf->stored_length+1);
3058 err = gpg_error_from_syserror ();
3064 paddedpin[i++] = 0x20 | (ndigits & 0x0f);
3065 for (s=pinvalue; i < aodf->stored_length && *s && s[1]; s = s+2 )
3066 paddedpin[i++] = (((*s - '0') << 4) | ((s[1] - '0') & 0x0f));
3067 if (i < aodf->stored_length && *s)
3068 paddedpin[i++] = (((*s - '0') << 4)
3069 |((aodf->pad_char_valid?aodf->pad_char:0)&0x0f));
3071 if (aodf->pinflags.needs_padding)
3072 while (i < aodf->stored_length)
3073 paddedpin[i++] = aodf->pad_char_valid? aodf->pad_char : 0;
3076 pinvalue = paddedpin;
3079 else if (aodf->pinflags.needs_padding)
3083 paddedpin = xtrymalloc (aodf->stored_length+1);
3086 err = gpg_error_from_syserror ();
3090 for (i=0, s=pinvalue; i < aodf->stored_length && *s; i++, s++)
3092 /* Not sure what padding char to use if none has been set.
3093 For now we use 0x00; maybe a space would be better. */
3094 for (; i < aodf->stored_length; i++)
3095 paddedpin[i] = aodf->pad_char_valid? aodf->pad_char : 0;
3099 pinvalue = paddedpin;
3102 pinvaluelen = strlen (pinvalue);
3104 err = iso7816_verify (app->slot,
3105 aodf->pin_reference_valid? aodf->pin_reference : 0,
3106 pinvalue, pinvaluelen);
3110 log_error ("PIN verification failed: %s\n", gpg_strerror (err));
3113 log_debug ("PIN verification succeeded\n");
3116 /* Prepare the DER object from INDATA. */
3117 if (indatalen == 36)
3119 /* No ASN.1 container used. */
3120 if (hashalgo != MD_USER_TLS_MD5SHA1)
3121 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3122 memcpy (data, indata, indatalen);
3124 else if (indatalen == 35)
3126 /* Alright, the caller was so kind to send us an already
3127 prepared DER object. Check that it is what we want and that
3128 it matches the hash algorithm. */
3129 if (hashalgo == GCRY_MD_SHA1 && !memcmp (indata, sha1_prefix, 15))
3131 else if (hashalgo == GCRY_MD_RMD160
3132 && !memcmp (indata, rmd160_prefix, 15))
3135 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3136 memcpy (data, indata, indatalen);
3140 /* Need to prepend the prefix. */
3141 if (hashalgo == GCRY_MD_SHA1)
3142 memcpy (data, sha1_prefix, 15);
3143 else if (hashalgo == GCRY_MD_RMD160)
3144 memcpy (data, rmd160_prefix, 15);
3146 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3147 memcpy (data+15, indata, indatalen);
3150 /* Manage security environment needs to be weaked for certain cards. */
3153 else if (app->app_local->card_type == CARD_TYPE_TCOS)
3155 /* TCOS creates signatures always using the local key 0. MSE
3158 else if (app->app_local->card_type == CARD_TYPE_MICARDO)
3160 if (!prkdf->pathlen)
3161 err = gpg_error (GPG_ERR_BUG);
3163 err = micardo_mse (app, prkdf->path[prkdf->pathlen-1]);
3165 else if (prkdf->key_reference_valid)
3167 unsigned char mse[3];
3169 mse[0] = 0x84; /* Select asym. key. */
3171 mse[2] = prkdf->key_reference;
3173 err = iso7816_manage_security_env (app->slot,
3179 log_error ("MSE failed: %s\n", gpg_strerror (err));
3183 if (hashalgo == MD_USER_TLS_MD5SHA1)
3184 err = iso7816_compute_ds (app->slot, 0, data, 36, 0, outdata, outdatalen);
3185 else if (no_data_padding)
3186 err = iso7816_compute_ds (app->slot, 0, data+15, 20, 0,outdata,outdatalen);
3188 err = iso7816_compute_ds (app->slot, 0, data, 35, 0, outdata, outdatalen);
3193 /* Handler for the PKAUTH command.
3195 This is basically the same as the PKSIGN command but we first check
3196 that the requested key is suitable for authentication; that is, it
3197 must match the criteria used for the attribute $AUTHKEYID. See
3198 do_sign for calling conventions; there is no HASHALGO, though. */
3200 do_auth (app_t app, const char *keyidstr,
3201 gpg_error_t (*pincb)(void*, const char *, char **),
3203 const void *indata, size_t indatalen,
3204 unsigned char **outdata, size_t *outdatalen )
3207 prkdf_object_t prkdf;
3210 if (!keyidstr || !*keyidstr)
3211 return gpg_error (GPG_ERR_INV_VALUE);
3213 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
3216 if (!prkdf->usageflags.sign)
3218 log_error ("key %s may not be used for authentication\n", keyidstr);
3219 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
3222 algo = indatalen == 36? MD_USER_TLS_MD5SHA1 : GCRY_MD_SHA1;
3223 return do_sign (app, keyidstr, algo, pincb, pincb_arg,
3224 indata, indatalen, outdata, outdatalen);
3229 /* Assume that EF(DIR) has been selected. Read its content and figure
3230 out the home EF of pkcs#15. Return that home DF or 0 if not found
3231 and the value at the address of BELPIC indicates whether it was
3232 found by the belpic aid. */
3233 static unsigned short
3234 read_home_df (int slot, int *r_belpic)
3237 unsigned char *buffer;
3238 const unsigned char *p, *pp;
3239 size_t buflen, n, nn;
3240 unsigned short result = 0;
3244 err = iso7816_read_binary (slot, 0, 0, &buffer, &buflen);
3247 log_error ("error reading EF{DIR}: %s\n", gpg_strerror (err));
3251 /* FIXME: We need to scan all records. */
3252 p = find_tlv (buffer, buflen, 0x61, &n);
3255 pp = find_tlv (p, n, 0x4f, &nn);
3256 if (pp && ((nn == sizeof pkcs15_aid && !memcmp (pp, pkcs15_aid, nn))
3257 || (*r_belpic = (nn == sizeof pkcs15be_aid
3258 && !memcmp (pp, pkcs15be_aid, nn)))))
3260 pp = find_tlv (p, n, 0x50, &nn);
3261 if (pp) /* fixme: Filter log value? */
3262 log_info ("pkcs#15 application label from EF(DIR) is '%.*s'\n",
3264 pp = find_tlv (p, n, 0x51, &nn);
3265 if (pp && nn == 4 && *pp == 0x3f && !pp[1])
3267 result = ((pp[2] << 8) | pp[3]);
3268 log_info ("pkcs#15 application directory is 0x%04hX\n", result);
3278 Select the PKCS#15 application on the card in SLOT.
3281 app_select_p15 (app_t app)
3283 int slot = app->slot;
3285 unsigned short def_home_df = 0;
3286 card_type_t card_type = CARD_TYPE_UNKNOWN;
3290 rc = iso7816_select_application (slot, pkcs15_aid, sizeof pkcs15_aid, 0);
3292 { /* Not found: Try to locate it from 2F00. We use direct path
3293 selection here because it seems that the Belgian eID card
3294 does only allow for that. Many other cards supports this
3295 selection method too. Note, that we don't use
3296 select_application above for the Belgian card - the call
3297 works but it seems that it did not switch to the correct DF.
3298 Using the 2f02 just works. */
3299 unsigned short path[1] = { 0x2f00 };
3301 rc = iso7816_select_path (app->slot, path, 1);
3305 def_home_df = read_home_df (slot, &is_belpic);
3308 path[0] = def_home_df;
3309 rc = iso7816_select_path (app->slot, path, 1);
3314 { /* Still not found: Try the default DF. */
3315 def_home_df = 0x5015;
3316 rc = iso7816_select_file (slot, def_home_df, 1);
3320 /* Determine the type of the card. The general case is to look
3321 it up from the ATR table. For the Belgian eID card we know
3322 it instantly from the AID. */
3325 card_type = CARD_TYPE_BELPIC;
3333 atr = apdu_get_atr (app->slot, &atrlen);
3335 rc = gpg_error (GPG_ERR_INV_CARD);
3338 for (i=0; card_atr_list[i].atrlen; i++)
3339 if (card_atr_list[i].atrlen == atrlen
3340 && !memcmp (card_atr_list[i].atr, atr, atrlen))
3342 card_type = card_atr_list[i].type;
3351 app->apptype = "P15";
3353 app->app_local = xtrycalloc (1, sizeof *app->app_local);
3354 if (!app->app_local)
3356 rc = gpg_error_from_syserror ();
3360 /* Set the home DF. Note that we currently can't do that if the
3361 selection via application ID worked. This will store 0 there
3362 instead. FIXME: We either need to figure the home_df via the
3363 DIR file or using the return values from the select file
3365 app->app_local->home_df = def_home_df;
3367 /* Store the card type. FIXME: We might want to put this into
3368 the common APP structure. */
3369 app->app_local->card_type = card_type;
3371 /* Store whether we may and should use direct path selection. */
3372 app->app_local->direct_path_selection = direct;
3374 /* Read basic information and thus check whether this is a real
3376 rc = read_p15_info (app);
3380 /* Special serial number munging. We need to check for a German
3381 prototype card right here because we need to access to
3382 EF(TokenInfo). We mark such a serial number by the using a
3383 prefix of FF0100. */
3384 if (app->serialnolen == 12
3385 && !memcmp (app->serialno, "\xD2\x76\0\0\0\0\0\0\0\0\0\0", 12))
3387 /* This is a German card with a silly serial number. Try to get
3388 the serial number from the EF(TokenInfo). . */
3391 /* FIXME: actually get it from EF(TokenInfo). */
3393 p = xtrymalloc (3 + app->serialnolen);
3395 rc = gpg_error (gpg_err_code_from_errno (errno));
3398 memcpy (p, "\xff\x01", 3);
3399 memcpy (p+3, app->serialno, app->serialnolen);
3400 app->serialnolen += 3;
3401 xfree (app->serialno);
3406 app->fnc.deinit = do_deinit;
3407 app->fnc.learn_status = do_learn_status;
3408 app->fnc.readcert = do_readcert;
3409 app->fnc.getattr = do_getattr;
3410 app->fnc.setattr = NULL;
3411 app->fnc.genkey = NULL;
3412 app->fnc.sign = do_sign;
3413 app->fnc.auth = do_auth;
3414 app->fnc.decipher = NULL;
3415 app->fnc.change_pin = NULL;
3416 app->fnc.check_pin = NULL;