1 /* app-p15.c - The pkcs#15 card application.
2 * Copyright (C) 2005 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 /* Information pertaining to the BELPIC developer card samples:
22 Unblock PUK: "222222111111"
23 Reset PIN: "333333111111")
25 e.g. the APDUs 00:20:00:02:08:2C:33:33:33:11:11:11:FF
26 and 00:24:01:01:08:24:12:34:FF:FF:FF:FF:FF
27 should change the PIN into 1234.
41 #include "app-common.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 hierachy. Thus we assume this is directly below the MF. */
280 unsigned short home_df;
282 /* The type of the card. */
283 card_type_t card_type;
285 /* Flag indicating whether we may use direct path selection. */
286 int direct_path_selection;
288 /* Structure with the EFIDs of the objects described in the ODF
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, NULL, NULL);
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, NULL, NULL);
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],
465 !(i+1 == pathlen), NULL, NULL);
468 log_error ("error selecting part %d from path ", i);
469 for (j=0; j < pathlen; j++)
470 log_printf ("%04hX", path[j]);
471 log_printf (": %s\n", gpg_strerror (err));
479 /* Parse a cert Id string (or a key Id string) and return the binary
480 object Id string in a newly allocated buffer stored at R_OBJID and
481 R_OBJIDLEN. On Error NULL will be stored there and an error code
482 returned. On success caller needs to free the buffer at R_OBJID. */
484 parse_certid (app_t app, const char *certid,
485 unsigned char **r_objid, size_t *r_objidlen)
490 unsigned char *objid;
496 if (app->app_local->home_df)
497 snprintf (tmpbuf, sizeof tmpbuf,
498 "P15-%04X.", (unsigned int)(app->app_local->home_df & 0xffff));
500 strcpy (tmpbuf, "P15.");
501 if (strncmp (certid, tmpbuf, strlen (tmpbuf)) )
503 if (!strncmp (certid, "P15.", 4)
504 || (!strncmp (certid, "P15-", 4)
505 && hexdigitp (certid+4)
506 && hexdigitp (certid+5)
507 && hexdigitp (certid+6)
508 && hexdigitp (certid+7)
509 && certid[8] == '.'))
510 return gpg_error (GPG_ERR_NOT_FOUND);
511 return gpg_error (GPG_ERR_INV_ID);
513 certid += strlen (tmpbuf);
515 for (s=certid, objidlen=0; hexdigitp (s); s++, objidlen++)
517 if (*s || !objidlen || (objidlen%2))
518 return gpg_error (GPG_ERR_INV_ID);
520 objid = xtrymalloc (objidlen);
522 return gpg_error_from_syserror ();
523 for (s=certid, i=0; i < objidlen; i++, s+=2)
524 objid[i] = xtoi_2 (s);
526 *r_objidlen = objidlen;
531 /* Find a certificate object by the certificate ID CERTID and store a
532 pointer to it at R_CDF. */
534 cdf_object_from_certid (app_t app, const char *certid, cdf_object_t *r_cdf)
538 unsigned char *objid;
541 err = parse_certid (app, certid, &objid, &objidlen);
545 for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
546 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
549 for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
550 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
553 for (cdf = app->app_local->useful_certificate_info; cdf; cdf = cdf->next)
554 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
558 return gpg_error (GPG_ERR_NOT_FOUND);
564 /* Find a private key object by the key Id string KEYIDSTR and store a
565 pointer to it at R_PRKDF. */
567 prkdf_object_from_keyidstr (app_t app, const char *keyidstr,
568 prkdf_object_t *r_prkdf)
572 unsigned char *objid;
573 prkdf_object_t prkdf;
575 err = parse_certid (app, keyidstr, &objid, &objidlen);
579 for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
580 if (prkdf->objidlen == objidlen && !memcmp (prkdf->objid, objid, objidlen))
584 return gpg_error (GPG_ERR_NOT_FOUND);
592 /* Read and parse the Object Directory File and store away the
593 pointers. ODF_FID shall contain the FID of the ODF.
595 Example of such a file:
597 A0 06 30 04 04 02 60 34 = Private Keys
598 A4 06 30 04 04 02 60 35 = Certificates
599 A5 06 30 04 04 02 60 36 = TrustedCertificates
600 A7 06 30 04 04 02 60 37 = DataObjects
601 A8 06 30 04 04 02 60 38 = AuthObjects
603 These are all PathOrObjects using the path CHOICE element. The
604 paths are octet strings of length 2. Using this Path CHOICE
605 element is recommended, so we only implement that for now.
608 read_ef_odf (app_t app, unsigned short odf_fid)
611 unsigned char *buffer, *p;
613 unsigned short value;
616 err = select_and_read_binary (app->slot, odf_fid, "ODF", &buffer, &buflen);
622 log_error ("error: ODF too short\n");
624 return gpg_error (GPG_ERR_INV_OBJ);
627 while (buflen && *p && *p != 0xff)
630 && (p[0] & 0xf0) == 0xA0
631 && !memcmp (p+1, "\x06\x30\x04\x04\x02", 5) )
635 else if ( buflen >= 12
636 && (p[0] & 0xf0) == 0xA0
637 && !memcmp (p+1, "\x0a\x30\x08\x04\x06\x3F\x00", 7)
638 && app->app_local->home_df == ((p[8]<<8)|p[9]) )
640 /* We only allow a full path if all files are at the same
641 level and below the home directory. The extend this we
642 would need to make use of new data type capable of
643 keeping a full path. */
648 log_error ("ODF format is not supported by us\n");
650 return gpg_error (GPG_ERR_INV_OBJ);
652 switch ((p[0] & 0x0f))
654 case 0: value = app->app_local->odf.private_keys; break;
655 case 1: value = app->app_local->odf.public_keys; break;
656 case 2: value = app->app_local->odf.trusted_public_keys; break;
657 case 3: value = app->app_local->odf.secret_keys; break;
658 case 4: value = app->app_local->odf.certificates; break;
659 case 5: value = app->app_local->odf.trusted_certificates; break;
660 case 6: value = app->app_local->odf.useful_certificates; break;
661 case 7: value = app->app_local->odf.data_objects; break;
662 case 8: value = app->app_local->odf.auth_objects; break;
663 default: value = 0; break;
667 log_error ("duplicate object type %d in ODF ignored\n",(p[0]&0x0f));
670 value = ((p[offset] << 8) | p[offset+1]);
671 switch ((p[0] & 0x0f))
673 case 0: app->app_local->odf.private_keys = value; break;
674 case 1: app->app_local->odf.public_keys = value; break;
675 case 2: app->app_local->odf.trusted_public_keys = value; break;
676 case 3: app->app_local->odf.secret_keys = value; break;
677 case 4: app->app_local->odf.certificates = value; break;
678 case 5: app->app_local->odf.trusted_certificates = value; break;
679 case 6: app->app_local->odf.useful_certificates = value; break;
680 case 7: app->app_local->odf.data_objects = value; break;
681 case 8: app->app_local->odf.auth_objects = value; break;
683 log_error ("unknown object type %d in ODF ignored\n", (p[0]&0x0f));
694 log_info ("warning: %u bytes of garbage detected at end of ODF\n",
695 (unsigned int)buflen);
702 /* Parse the BIT STRING with the keyUsageFlags from the
703 CommonKeyAttributes. */
705 parse_keyusage_flags (const unsigned char *der, size_t derlen,
706 keyusage_flags_t *usageflags)
708 unsigned int bits, mask;
711 memset (usageflags, 0, sizeof *usageflags);
713 return gpg_error (GPG_ERR_INV_OBJ);
715 unused = *der++; derlen--;
716 if ((!derlen && unused) || unused/8 > derlen)
717 return gpg_error (GPG_ERR_ENCODING_PROBLEM);
718 full = derlen - (unused+7)/8;
721 for (i=1; unused; i <<= 1, unused--)
727 bits = *der++; derlen--;
738 if ((bits & 0x80)) usageflags->encrypt = 1;
739 if ((bits & 0x40)) usageflags->decrypt = 1;
740 if ((bits & 0x20)) usageflags->sign = 1;
741 if ((bits & 0x10)) usageflags->sign_recover = 1;
742 if ((bits & 0x08)) usageflags->wrap = 1;
743 if ((bits & 0x04)) usageflags->unwrap = 1;
744 if ((bits & 0x02)) usageflags->verify = 1;
745 if ((bits & 0x01)) usageflags->verify_recover = 1;
750 bits = *der++; derlen--;
761 if ((bits & 0x80)) usageflags->derive = 1;
762 if ((bits & 0x40)) usageflags->non_repudiation = 1;
767 /* Read and parse the Private Key Directory Files. */
771 30 33 30 11 0C 08 53 4B 2E 43 48 2E 44 53 03 02 030...SK.CH.DS..
772 06 80 04 01 07 30 0C 04 01 01 03 03 06 00 40 02 .....0........@.
773 02 00 50 A1 10 30 0E 30 08 04 06 3F 00 40 16 00 ..P..0.0...?.@..
774 50 02 02 04 00 30 33 30 11 0C 08 53 4B 2E 43 48 P....030...SK.CH
775 2E 4B 45 03 02 06 80 04 01 0A 30 0C 04 01 0C 03 .KE.......0.....
776 03 06 44 00 02 02 00 52 A1 10 30 0E 30 08 04 06 ..D....R..0.0...
777 3F 00 40 16 00 52 02 02 04 00 30 34 30 12 0C 09 ?.@..R....040...
778 53 4B 2E 43 48 2E 41 55 54 03 02 06 80 04 01 0A SK.CH.AUT.......
779 30 0C 04 01 0D 03 03 06 20 00 02 02 00 51 A1 10 0....... ....Q..
780 30 0E 30 08 04 06 3F 00 40 16 00 51 02 02 04 00 0.0...?.@..Q....
781 30 37 30 15 0C 0C 53 4B 2E 43 48 2E 44 53 2D 53 070...SK.CH.DS-S
782 50 58 03 02 06 80 04 01 0A 30 0C 04 01 02 03 03 PX.......0......
783 06 20 00 02 02 00 53 A1 10 30 0E 30 08 04 06 3F . ....S..0.0...?
784 00 40 16 00 53 02 02 04 00 00 00 00 00 00 00 00 .@..S...........
785 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
786 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
789 2 30 17: SEQUENCE { -- commonObjectAttributes
790 4 0C 8: UTF8String 'SK.CH.DS'
791 14 03 2: BIT STRING 6 unused bits
793 18 04 1: OCTET STRING --authid
796 21 30 12: SEQUENCE { -- commonKeyAttributes
797 23 04 1: OCTET STRING
799 26 03 3: BIT STRING 6 unused bits
800 : '1000000000'B (bit 9)
801 31 02 2: INTEGER 80 -- keyReference (optional)
803 35 A1 16: [1] { -- keyAttributes
804 37 30 14: SEQUENCE { -- privateRSAKeyAttributes
805 39 30 8: SEQUENCE { -- objectValue
806 41 04 6: OCTET STRING --path
809 49 02 2: INTEGER 1024 -- modulus
817 read_ef_prkdf (app_t app, unsigned short fid, prkdf_object_t *result)
820 unsigned char *buffer = NULL;
822 const unsigned char *p;
823 size_t n, objlen, hdrlen;
824 int class, tag, constructed, ndef;
825 prkdf_object_t prkdflist = NULL;
829 return gpg_error (GPG_ERR_NO_DATA); /* No private keys. */
831 err = select_and_read_binary (app->slot, fid, "PrKDF", &buffer, &buflen);
838 /* FIXME: This shares a LOT of code with read_ef_cdf! */
840 /* Loop over the records. We stop as soon as we detect a new record
841 starting with 0x00 or 0xff as these values are commonly used to
842 pad data blocks and are no valid ASN.1 encoding. */
843 while (n && *p && *p != 0xff)
845 const unsigned char *pp;
848 const char *errstr = NULL;
849 prkdf_object_t prkdf = NULL;
851 const unsigned char *objid;
853 const unsigned char *authid = NULL;
854 size_t authidlen = 0;
855 keyusage_flags_t usageflags;
856 unsigned long key_reference = 0;
857 int key_reference_valid = 0;
860 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
861 &ndef, &objlen, &hdrlen);
862 if (!err && (objlen > n || tag != TAG_SEQUENCE))
863 err = gpg_error (GPG_ERR_INV_OBJ);
866 log_error ("error parsing PrKDF record: %s\n", gpg_strerror (err));
874 /* Parse the commonObjectAttributes. */
876 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
877 &ndef, &objlen, &hdrlen);
878 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
879 err = gpg_error (GPG_ERR_INV_OBJ);
883 const unsigned char *ppp = pp;
889 /* Search the optional AuthId. We need to skip the optional
890 Label (UTF8STRING) and the optional CommonObjectFlags
893 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
894 &ndef, &objlen, &hdrlen);
895 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
896 err = gpg_error (GPG_ERR_INV_OBJ);
897 if (gpg_err_code (err) == GPG_ERR_EOF)
901 if (tag == TAG_UTF8_STRING)
903 ppp += objlen; /* Skip the Label. */
907 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
908 &ndef, &objlen, &hdrlen);
909 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
910 err = gpg_error (GPG_ERR_INV_OBJ);
911 if (gpg_err_code (err) == GPG_ERR_EOF)
916 if (tag == TAG_BIT_STRING)
918 ppp += objlen; /* Skip the CommonObjectFlags. */
922 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
923 &ndef, &objlen, &hdrlen);
924 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
925 err = gpg_error (GPG_ERR_INV_OBJ);
926 if (gpg_err_code (err) == GPG_ERR_EOF)
931 if (tag == TAG_OCTET_STRING && objlen)
940 /* Parse the commonKeyAttributes. */
942 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
943 &ndef, &objlen, &hdrlen);
944 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
945 err = gpg_error (GPG_ERR_INV_OBJ);
949 const unsigned char *ppp = pp;
957 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
958 &ndef, &objlen, &hdrlen);
959 if (!err && (objlen > nnn
960 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
961 err = gpg_error (GPG_ERR_INV_OBJ);
969 /* Get the KeyUsageFlags. */
971 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
972 &ndef, &objlen, &hdrlen);
973 if (!err && (objlen > nnn
974 || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
975 err = gpg_error (GPG_ERR_INV_OBJ);
978 err = parse_keyusage_flags (ppp, objlen, &usageflags);
984 /* Find the keyReference */
986 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
987 &ndef, &objlen, &hdrlen);
988 if (gpg_err_code (err) == GPG_ERR_EOF)
990 if (!err && objlen > nnn)
991 err = gpg_error (GPG_ERR_INV_OBJ);
994 if (class == CLASS_UNIVERSAL && tag == TAG_BOOLEAN)
996 /* Skip the native element. */
1000 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1001 &ndef, &objlen, &hdrlen);
1002 if (gpg_err_code (err) == GPG_ERR_EOF)
1004 if (!err && objlen > nnn)
1005 err = gpg_error (GPG_ERR_INV_OBJ);
1009 if (class == CLASS_UNIVERSAL && tag == TAG_BIT_STRING)
1011 /* Skip the accessFlags. */
1015 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1016 &ndef, &objlen, &hdrlen);
1017 if (gpg_err_code (err) == GPG_ERR_EOF)
1019 if (!err && objlen > nnn)
1020 err = gpg_error (GPG_ERR_INV_OBJ);
1024 if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
1026 /* Yep, this is the keyReference. */
1027 for (ul=0; objlen; objlen--)
1030 ul |= (*ppp++) & 0xff;
1034 key_reference_valid = 1;
1042 /* Skip subClassAttributes. */
1044 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1045 &ndef, &objlen, &hdrlen);
1046 if (!err && objlen > nn)
1047 err = gpg_error (GPG_ERR_INV_OBJ);
1050 if (class == CLASS_CONTEXT && tag == 0)
1056 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1057 &ndef, &objlen, &hdrlen);
1059 /* Parse the keyAttributes. */
1060 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1061 err = gpg_error (GPG_ERR_INV_OBJ);
1067 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1068 &ndef, &objlen, &hdrlen);
1069 if (!err && objlen > nn)
1070 err = gpg_error (GPG_ERR_INV_OBJ);
1073 if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
1075 else if (class == CLASS_CONTEXT)
1079 case 0: errstr = "EC key objects are not supported"; break;
1080 case 1: errstr = "DH key objects are not supported"; break;
1081 case 2: errstr = "DSA key objects are not supported"; break;
1082 case 3: errstr = "KEA key objects are not supported"; break;
1083 default: errstr = "unknown privateKeyObject"; break;
1089 err = gpg_error (GPG_ERR_INV_OBJ);
1095 /* Check that the reference is a Path object. */
1097 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1098 &ndef, &objlen, &hdrlen);
1099 if (!err && objlen > nn)
1100 err = gpg_error (GPG_ERR_INV_OBJ);
1103 if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
1105 errstr = "unsupported reference type";
1110 /* Parse the Path object. */
1112 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1113 &ndef, &objlen, &hdrlen);
1114 if (!err && objlen > nn)
1115 err = gpg_error (GPG_ERR_INV_OBJ);
1119 /* Make sure that the next element is a non zero path and of
1120 even length (FID are two bytes each). */
1121 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
1122 || !objlen || (objlen & 1) )
1124 errstr = "invalid path reference";
1127 /* Create a new PrKDF list item. */
1128 prkdf = xtrycalloc (1, (sizeof *prkdf
1129 - sizeof(unsigned short)
1130 + objlen/2 * sizeof(unsigned short)));
1133 err = gpg_error_from_syserror ();
1136 prkdf->objidlen = objidlen;
1137 prkdf->objid = xtrymalloc (objidlen);
1140 err = gpg_error_from_syserror ();
1144 memcpy (prkdf->objid, objid, objidlen);
1147 prkdf->authidlen = authidlen;
1148 prkdf->authid = xtrymalloc (authidlen);
1151 err = gpg_error_from_syserror ();
1152 xfree (prkdf->objid);
1156 memcpy (prkdf->authid, authid, authidlen);
1159 prkdf->pathlen = objlen/2;
1160 for (i=0; i < prkdf->pathlen; i++, pp += 2, nn -= 2)
1161 prkdf->path[i] = ((pp[0] << 8) | pp[1]);
1163 prkdf->usageflags = usageflags;
1164 prkdf->key_reference = key_reference;
1165 prkdf->key_reference_valid = key_reference_valid;
1169 /* An index and length follows. */
1170 prkdf->have_off = 1;
1172 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1173 &ndef, &objlen, &hdrlen);
1174 if (!err && (objlen > nn
1175 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1176 err = gpg_error (GPG_ERR_INV_OBJ);
1180 for (ul=0; objlen; objlen--)
1183 ul |= (*pp++) & 0xff;
1189 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1190 &ndef, &objlen, &hdrlen);
1191 if (!err && (objlen > nn
1192 || class != CLASS_CONTEXT || tag != 0))
1193 err = gpg_error (GPG_ERR_INV_OBJ);
1197 for (ul=0; objlen; objlen--)
1200 ul |= (*pp++) & 0xff;
1207 log_debug ("PrKDF %04hX: id=", fid);
1208 for (i=0; i < prkdf->objidlen; i++)
1209 log_printf ("%02X", prkdf->objid[i]);
1210 log_printf (" path=");
1211 for (i=0; i < prkdf->pathlen; i++)
1212 log_printf ("%04hX", prkdf->path[i]);
1213 if (prkdf->have_off)
1214 log_printf ("[%lu/%lu]", prkdf->off, prkdf->len);
1217 log_printf (" authid=");
1218 for (i=0; i < prkdf->authidlen; i++)
1219 log_printf ("%02X", prkdf->authid[i]);
1221 if (prkdf->key_reference_valid)
1222 log_printf (" keyref=0x%02lX", prkdf->key_reference);
1223 log_printf (" usage=");
1225 if (prkdf->usageflags.encrypt) log_printf ("%sencrypt", s), s = ",";
1226 if (prkdf->usageflags.decrypt) log_printf ("%sdecrypt", s), s = ",";
1227 if (prkdf->usageflags.sign ) log_printf ("%ssign", s), s = ",";
1228 if (prkdf->usageflags.sign_recover)
1229 log_printf ("%ssign_recover", s), s = ",";
1230 if (prkdf->usageflags.wrap ) log_printf ("%swrap", s), s = ",";
1231 if (prkdf->usageflags.unwrap ) log_printf ("%sunwrap", s), s = ",";
1232 if (prkdf->usageflags.verify ) log_printf ("%sverify", s), s = ",";
1233 if (prkdf->usageflags.verify_recover)
1234 log_printf ("%sverify_recover", s), s = ",";
1235 if (prkdf->usageflags.derive ) log_printf ("%sderive", s), s = ",";
1236 if (prkdf->usageflags.non_repudiation)
1237 log_printf ("%snon_repudiation", s), s = ",";
1240 /* Put it into the list. */
1241 prkdf->next = prkdflist;
1244 continue; /* Ready. */
1247 log_error ("error parsing PrKDF record (%d): %s - skipped\n",
1248 where, errstr? errstr : gpg_strerror (err));
1251 xfree (prkdf->objid);
1252 xfree (prkdf->authid);
1256 } /* End looping over all records. */
1261 release_prkdflist (prkdflist);
1263 *result = prkdflist;
1268 /* Read and parse the Certificate Directory Files identified by FID.
1269 On success a newlist of CDF object gets stored at RESULT and the
1270 caller is then responsible of releasing this list. On error a
1271 error code is returned and RESULT won't get changed. */
1273 read_ef_cdf (app_t app, unsigned short fid, cdf_object_t *result)
1276 unsigned char *buffer = NULL;
1278 const unsigned char *p;
1279 size_t n, objlen, hdrlen;
1280 int class, tag, constructed, ndef;
1281 cdf_object_t cdflist = NULL;
1285 return gpg_error (GPG_ERR_NO_DATA); /* No certificates. */
1287 err = select_and_read_binary (app->slot, fid, "CDF", &buffer, &buflen);
1294 /* Loop over the records. We stop as soon as we detect a new record
1295 starting with 0x00 or 0xff as these values are commonly used to
1296 pad data blocks and are no valid ASN.1 encoding. */
1297 while (n && *p && *p != 0xff)
1299 const unsigned char *pp;
1302 const char *errstr = NULL;
1303 cdf_object_t cdf = NULL;
1305 const unsigned char *objid;
1308 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1309 &ndef, &objlen, &hdrlen);
1310 if (!err && (objlen > n || tag != TAG_SEQUENCE))
1311 err = gpg_error (GPG_ERR_INV_OBJ);
1314 log_error ("error parsing CDF record: %s\n", gpg_strerror (err));
1322 /* Skip the commonObjectAttributes. */
1324 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1325 &ndef, &objlen, &hdrlen);
1326 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1327 err = gpg_error (GPG_ERR_INV_OBJ);
1333 /* Parse the commonCertificateAttributes. */
1335 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1336 &ndef, &objlen, &hdrlen);
1337 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1338 err = gpg_error (GPG_ERR_INV_OBJ);
1342 const unsigned char *ppp = pp;
1343 size_t nnn = objlen;
1350 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1351 &ndef, &objlen, &hdrlen);
1352 if (!err && (objlen > nnn
1353 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
1354 err = gpg_error (GPG_ERR_INV_OBJ);
1361 /* Parse the certAttribute. */
1363 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1364 &ndef, &objlen, &hdrlen);
1365 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1366 err = gpg_error (GPG_ERR_INV_OBJ);
1372 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1373 &ndef, &objlen, &hdrlen);
1374 if (!err && (objlen > nn
1375 || class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE))
1376 err = gpg_error (GPG_ERR_INV_OBJ);
1381 /* Check that the reference is a Path object. */
1383 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1384 &ndef, &objlen, &hdrlen);
1385 if (!err && objlen > nn)
1386 err = gpg_error (GPG_ERR_INV_OBJ);
1389 if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
1391 errstr = "unsupported reference type";
1396 /* Parse the Path object. */
1398 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1399 &ndef, &objlen, &hdrlen);
1400 if (!err && objlen > nn)
1401 err = gpg_error (GPG_ERR_INV_OBJ);
1405 /* Make sure that the next element is a non zero path and of
1406 even length (FID are two bytes each). */
1407 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
1408 || !objlen || (objlen & 1) )
1410 errstr = "invalid path reference";
1413 /* Create a new CDF list item. */
1414 cdf = xtrycalloc (1, (sizeof *cdf
1415 - sizeof(unsigned short)
1416 + objlen/2 * sizeof(unsigned short)));
1419 err = gpg_error_from_syserror ();
1422 cdf->objidlen = objidlen;
1423 cdf->objid = xtrymalloc (objidlen);
1426 err = gpg_error_from_syserror ();
1430 memcpy (cdf->objid, objid, objidlen);
1432 cdf->pathlen = objlen/2;
1433 for (i=0; i < cdf->pathlen; i++, pp += 2, nn -= 2)
1434 cdf->path[i] = ((pp[0] << 8) | pp[1]);
1438 /* An index and length follows. */
1441 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1442 &ndef, &objlen, &hdrlen);
1443 if (!err && (objlen > nn
1444 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1445 err = gpg_error (GPG_ERR_INV_OBJ);
1449 for (ul=0; objlen; objlen--)
1452 ul |= (*pp++) & 0xff;
1458 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1459 &ndef, &objlen, &hdrlen);
1460 if (!err && (objlen > nn
1461 || class != CLASS_CONTEXT || tag != 0))
1462 err = gpg_error (GPG_ERR_INV_OBJ);
1466 for (ul=0; objlen; objlen--)
1469 ul |= (*pp++) & 0xff;
1475 log_debug ("CDF %04hX: id=", fid);
1476 for (i=0; i < cdf->objidlen; i++)
1477 log_printf ("%02X", cdf->objid[i]);
1478 log_printf (" path=");
1479 for (i=0; i < cdf->pathlen; i++)
1480 log_printf ("%04hX", cdf->path[i]);
1482 log_printf ("[%lu/%lu]", cdf->off, cdf->len);
1485 /* Put it into the list. */
1486 cdf->next = cdflist;
1489 continue; /* Ready. */
1492 log_error ("error parsing CDF record (%d): %s - skipped\n",
1493 where, errstr? errstr : gpg_strerror (err));
1496 } /* End looping over all records. */
1501 release_cdflist (cdflist);
1510 SEQUENCE { -- CommonObjectAttributes
1511 UTF8String 'specific PIN for DS'
1512 BIT STRING 0 unused bits
1515 SEQUENCE { -- CommonAuthenticationObjectAttributes
1520 [1] { -- typeAttributes
1521 SEQUENCE { -- PinAttributes
1522 BIT STRING 0 unused bits
1523 '0000100000110010'B -- local,initialized,needs-padding
1525 ENUMERATED 1 -- ascii-numeric
1526 INTEGER 6 -- minLength
1527 INTEGER 6 -- storedLength
1528 INTEGER 8 -- maxLength
1531 GeneralizedTime 19/04/2002 12:12 GMT -- lastPinChange
1534 3F 00 40 16 -- path to DF of PIN
1541 /* Read and parse an Authentication Object Directory File identified
1542 by FID. On success a newlist of AODF objects gets stored at RESULT
1543 and the caller is responsible of releasing this list. On error a
1544 error code is returned and RESULT won't get changed. */
1546 read_ef_aodf (app_t app, unsigned short fid, aodf_object_t *result)
1549 unsigned char *buffer = NULL;
1551 const unsigned char *p;
1552 size_t n, objlen, hdrlen;
1553 int class, tag, constructed, ndef;
1554 aodf_object_t aodflist = NULL;
1558 return gpg_error (GPG_ERR_NO_DATA); /* No authentication objects. */
1560 err = select_and_read_binary (app->slot, fid, "AODF", &buffer, &buflen);
1567 /* FIXME: This shares a LOT of code with read_ef_prkdf! */
1569 /* Loop over the records. We stop as soon as we detect a new record
1570 starting with 0x00 or 0xff as these values are commonly used to
1571 pad data blocks and are no valid ASN.1 encoding. */
1572 while (n && *p && *p != 0xff)
1574 const unsigned char *pp;
1577 const char *errstr = NULL;
1578 aodf_object_t aodf = NULL;
1582 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1583 &ndef, &objlen, &hdrlen);
1584 if (!err && (objlen > n || tag != TAG_SEQUENCE))
1585 err = gpg_error (GPG_ERR_INV_OBJ);
1588 log_error ("error parsing AODF record: %s\n", gpg_strerror (err));
1596 /* Allocate memory for a new AODF list item. */
1597 aodf = xtrycalloc (1, sizeof *aodf);
1601 /* Parse the commonObjectAttributes. */
1603 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1604 &ndef, &objlen, &hdrlen);
1605 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1606 err = gpg_error (GPG_ERR_INV_OBJ);
1610 const unsigned char *ppp = pp;
1611 size_t nnn = objlen;
1616 /* Search the optional AuthId. We need to skip the optional
1617 Label (UTF8STRING) and the optional CommonObjectFlags
1620 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1621 &ndef, &objlen, &hdrlen);
1622 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1623 err = gpg_error (GPG_ERR_INV_OBJ);
1624 if (gpg_err_code (err) == GPG_ERR_EOF)
1628 if (tag == TAG_UTF8_STRING)
1630 ppp += objlen; /* Skip the Label. */
1634 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1635 &ndef, &objlen, &hdrlen);
1636 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1637 err = gpg_error (GPG_ERR_INV_OBJ);
1638 if (gpg_err_code (err) == GPG_ERR_EOF)
1643 if (tag == TAG_BIT_STRING)
1645 ppp += objlen; /* Skip the CommonObjectFlags. */
1649 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1650 &ndef, &objlen, &hdrlen);
1651 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1652 err = gpg_error (GPG_ERR_INV_OBJ);
1653 if (gpg_err_code (err) == GPG_ERR_EOF)
1658 if (tag == TAG_OCTET_STRING && objlen)
1660 aodf->authidlen = objlen;
1661 aodf->authid = xtrymalloc (objlen);
1664 memcpy (aodf->authid, ppp, objlen);
1670 /* Parse the CommonAuthenticationObjectAttributes. */
1672 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1673 &ndef, &objlen, &hdrlen);
1674 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1675 err = gpg_error (GPG_ERR_INV_OBJ);
1679 const unsigned char *ppp = pp;
1680 size_t nnn = objlen;
1687 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1688 &ndef, &objlen, &hdrlen);
1689 if (!err && (objlen > nnn
1690 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
1691 err = gpg_error (GPG_ERR_INV_OBJ);
1695 aodf->objidlen = objlen;
1696 aodf->objid = xtrymalloc (objlen);
1699 memcpy (aodf->objid, ppp, objlen);
1702 /* Parse the typeAttributes. */
1704 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1705 &ndef, &objlen, &hdrlen);
1706 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1707 err = gpg_error (GPG_ERR_INV_OBJ);
1713 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1714 &ndef, &objlen, &hdrlen);
1715 if (!err && objlen > nn)
1716 err = gpg_error (GPG_ERR_INV_OBJ);
1719 if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
1720 ; /* PinAttributes */
1721 else if (class == CLASS_CONTEXT)
1725 case 0: errstr = "biometric auth types are not supported"; break;
1726 case 1: errstr = "authKey auth types are not supported"; break;
1727 case 2: errstr = "external auth type are not supported"; break;
1728 default: errstr = "unknown privateKeyObject"; break;
1734 err = gpg_error (GPG_ERR_INV_OBJ);
1742 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1743 &ndef, &objlen, &hdrlen);
1744 if (!err && (objlen > nn || !objlen
1745 || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
1746 err = gpg_error (GPG_ERR_INV_OBJ);
1751 unsigned int bits, mask;
1754 unused = *pp++; nn--; objlen--;
1755 if ((!objlen && unused) || unused/8 > objlen)
1757 err = gpg_error (GPG_ERR_ENCODING_PROBLEM);
1760 full = objlen - (unused+7)/8;
1763 for (i=1; unused; i <<= 1, unused--)
1766 /* The first octet */
1770 bits = *pp++; nn--; objlen--;
1779 if ((bits & 0x80)) /* ASN.1 bit 0. */
1780 aodf->pinflags.case_sensitive = 1;
1781 if ((bits & 0x40)) /* ASN.1 bit 1. */
1782 aodf->pinflags.local = 1;
1784 aodf->pinflags.change_disabled = 1;
1786 aodf->pinflags.unblock_disabled = 1;
1788 aodf->pinflags.initialized = 1;
1790 aodf->pinflags.needs_padding = 1;
1792 aodf->pinflags.unblocking_pin = 1;
1794 aodf->pinflags.so_pin = 1;
1795 /* The second octet. */
1799 bits = *pp++; nn--; objlen--;
1809 aodf->pinflags.disable_allowed = 1;
1811 aodf->pinflags.integrity_protected = 1;
1813 aodf->pinflags.confidentiality_protected = 1;
1815 aodf->pinflags.exchange_ref_data = 1;
1816 /* Skip remaining bits. */
1824 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1825 &ndef, &objlen, &hdrlen);
1826 if (!err && (objlen > nn
1827 || class != CLASS_UNIVERSAL || tag != TAG_ENUMERATED))
1828 err = gpg_error (GPG_ERR_INV_OBJ);
1829 if (!err && (objlen > sizeof (pin_type_t) || objlen > sizeof (ul)))
1830 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1834 for (ul=0; objlen; objlen--)
1837 ul |= (*pp++) & 0xff;
1845 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1846 &ndef, &objlen, &hdrlen);
1847 if (!err && (objlen > nn
1848 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1849 err = gpg_error (GPG_ERR_INV_OBJ);
1850 if (!err && objlen > sizeof (ul))
1851 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1854 for (ul=0; objlen; objlen--)
1857 ul |= (*pp++) & 0xff;
1860 aodf->min_length = ul;
1865 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1866 &ndef, &objlen, &hdrlen);
1867 if (!err && (objlen > nn
1868 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1869 err = gpg_error (GPG_ERR_INV_OBJ);
1870 if (!err && objlen > sizeof (ul))
1871 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1874 for (ul=0; objlen; objlen--)
1877 ul |= (*pp++) & 0xff;
1880 aodf->stored_length = ul;
1882 /* optional maxLength */
1884 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1885 &ndef, &objlen, &hdrlen);
1886 if (gpg_err_code (err) == GPG_ERR_EOF)
1888 if (!err && objlen > nn)
1889 err = gpg_error (GPG_ERR_INV_OBJ);
1892 if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
1894 if (objlen > sizeof (ul))
1896 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1899 for (ul=0; objlen; objlen--)
1902 ul |= (*pp++) & 0xff;
1905 aodf->max_length = ul;
1906 aodf->max_length_valid = 1;
1909 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1910 &ndef, &objlen, &hdrlen);
1911 if (gpg_err_code (err) == GPG_ERR_EOF)
1913 if (!err && objlen > nn)
1914 err = gpg_error (GPG_ERR_INV_OBJ);
1919 /* Optional pinReference. */
1920 if (class == CLASS_CONTEXT && tag == 0)
1922 if (objlen > sizeof (ul))
1924 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1927 for (ul=0; objlen; objlen--)
1930 ul |= (*pp++) & 0xff;
1933 aodf->pin_reference = ul;
1934 aodf->pin_reference_valid = 1;
1937 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1938 &ndef, &objlen, &hdrlen);
1939 if (gpg_err_code (err) == GPG_ERR_EOF)
1941 if (!err && objlen > nn)
1942 err = gpg_error (GPG_ERR_INV_OBJ);
1947 /* Optional padChar. */
1948 if (class == CLASS_UNIVERSAL && tag == TAG_OCTET_STRING)
1952 errstr = "padChar is not of size(1)";
1955 aodf->pad_char = *pp++; nn--;
1956 aodf->pad_char_valid = 1;
1959 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1960 &ndef, &objlen, &hdrlen);
1961 if (gpg_err_code (err) == GPG_ERR_EOF)
1963 if (!err && objlen > nn)
1964 err = gpg_error (GPG_ERR_INV_OBJ);
1969 /* Skip optional lastPinChange. */
1970 if (class == CLASS_UNIVERSAL && tag == TAG_GENERALIZED_TIME)
1976 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1977 &ndef, &objlen, &hdrlen);
1978 if (gpg_err_code (err) == GPG_ERR_EOF)
1980 if (!err && objlen > nn)
1981 err = gpg_error (GPG_ERR_INV_OBJ);
1986 /* Optional Path object. */
1987 if (class == CLASS_UNIVERSAL || tag == TAG_SEQUENCE)
1989 const unsigned char *ppp = pp;
1990 size_t nnn = objlen;
1996 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1997 &ndef, &objlen, &hdrlen);
1998 if (!err && objlen > nnn)
1999 err = gpg_error (GPG_ERR_INV_OBJ);
2003 /* Make sure that the next element is a non zero FID and of
2004 even length (FID are two bytes each). */
2005 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
2006 || !objlen || (objlen & 1) )
2008 errstr = "invalid path reference";
2012 aodf->pathlen = objlen/2;
2013 aodf->path = xtrymalloc (aodf->pathlen);
2016 for (i=0; i < aodf->pathlen; i++, ppp += 2, nnn -= 2)
2017 aodf->path[i] = ((ppp[0] << 8) | ppp[1]);
2021 /* An index and length follows. */
2024 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
2025 &ndef, &objlen, &hdrlen);
2026 if (!err && (objlen > nnn
2027 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
2028 err = gpg_error (GPG_ERR_INV_OBJ);
2032 for (ul=0; objlen; objlen--)
2035 ul |= (*ppp++) & 0xff;
2041 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
2042 &ndef, &objlen, &hdrlen);
2043 if (!err && (objlen > nnn
2044 || class != CLASS_CONTEXT || tag != 0))
2045 err = gpg_error (GPG_ERR_INV_OBJ);
2049 for (ul=0; objlen; objlen--)
2052 ul |= (*ppp++) & 0xff;
2059 /* Igonore further objects which might be there due to future
2060 extensions of pkcs#15. */
2063 log_debug ("AODF %04hX: id=", fid);
2064 for (i=0; i < aodf->objidlen; i++)
2065 log_printf ("%02X", aodf->objid[i]);
2068 log_printf (" authid=");
2069 for (i=0; i < aodf->authidlen; i++)
2070 log_printf ("%02X", aodf->authid[i]);
2072 log_printf (" flags=");
2074 if (aodf->pinflags.case_sensitive)
2075 log_printf ("%scase_sensitive", s), s = ",";
2076 if (aodf->pinflags.local)
2077 log_printf ("%slocal", s), s = ",";
2078 if (aodf->pinflags.change_disabled)
2079 log_printf ("%schange_disabled", s), s = ",";
2080 if (aodf->pinflags.unblock_disabled)
2081 log_printf ("%sunblock_disabled", s), s = ",";
2082 if (aodf->pinflags.initialized)
2083 log_printf ("%sinitialized", s), s = ",";
2084 if (aodf->pinflags.needs_padding)
2085 log_printf ("%sneeds_padding", s), s = ",";
2086 if (aodf->pinflags.unblocking_pin)
2087 log_printf ("%sunblocking_pin", s), s = ",";
2088 if (aodf->pinflags.so_pin)
2089 log_printf ("%sso_pin", s), s = ",";
2090 if (aodf->pinflags.disable_allowed)
2091 log_printf ("%sdisable_allowed", s), s = ",";
2092 if (aodf->pinflags.integrity_protected)
2093 log_printf ("%sintegrity_protected", s), s = ",";
2094 if (aodf->pinflags.confidentiality_protected)
2095 log_printf ("%sconfidentiality_protected", s), s = ",";
2096 if (aodf->pinflags.exchange_ref_data)
2097 log_printf ("%sexchange_ref_data", s), s = ",";
2100 switch (aodf->pintype)
2102 case PIN_TYPE_BCD: s = "bcd"; break;
2103 case PIN_TYPE_ASCII_NUMERIC: s = "ascii-numeric"; break;
2104 case PIN_TYPE_UTF8: s = "utf8"; break;
2105 case PIN_TYPE_HALF_NIBBLE_BCD: s = "half-nibble-bcd"; break;
2106 case PIN_TYPE_ISO9564_1: s = "iso9564-1"; break;
2108 sprintf (numbuf, "%lu", (unsigned long)aodf->pintype);
2111 log_printf (" type=%s", s);
2113 log_printf (" min=%lu", aodf->min_length);
2114 log_printf (" stored=%lu", aodf->stored_length);
2115 if (aodf->max_length_valid)
2116 log_printf (" max=%lu", aodf->max_length);
2117 if (aodf->pad_char_valid)
2118 log_printf (" pad=0x%02x", aodf->pad_char);
2119 if (aodf->pin_reference_valid)
2120 log_printf (" pinref=0x%02lX", aodf->pin_reference);
2123 log_printf (" path=");
2124 for (i=0; i < aodf->pathlen; i++)
2125 log_printf ("%04hX", aodf->path[i]);
2127 log_printf ("[%lu/%lu]", aodf->off, aodf->len);
2131 /* Put it into the list. */
2132 aodf->next = aodflist;
2135 continue; /* Ready. */
2138 err = gpg_error_from_syserror ();
2139 release_aodf_object (aodf);
2143 log_error ("error parsing AODF record (%d): %s - skipped\n",
2144 where, errstr? errstr : gpg_strerror (err));
2146 release_aodf_object (aodf);
2147 } /* End looping over all records. */
2152 release_aodflist (aodflist);
2162 /* Read and parse the EF(TokenInfo).
2164 TokenInfo ::= SEQUENCE {
2165 version INTEGER {v1(0)} (v1,...),
2166 serialNumber OCTET STRING,
2167 manufacturerID Label OPTIONAL,
2168 label [0] Label OPTIONAL,
2169 tokenflags TokenFlags,
2170 seInfo SEQUENCE OF SecurityEnvironmentInfo OPTIONAL,
2171 recordInfo [1] RecordInfo OPTIONAL,
2172 supportedAlgorithms [2] SEQUENCE OF AlgorithmInfo OPTIONAL,
2174 issuerId [3] Label OPTIONAL,
2175 holderId [4] Label OPTIONAL,
2176 lastUpdate [5] LastUpdate OPTIONAL,
2177 preferredLanguage PrintableString OPTIONAL -- In accordance with
2179 } (CONSTRAINED BY { -- Each AlgorithmInfo.reference value must be unique --})
2181 TokenFlags ::= BIT STRING {
2191 30 31 02 01 00 04 04 05 45 36 9F 0C 0C 44 2D 54 01......E6...D-T
2192 72 75 73 74 20 47 6D 62 48 80 14 4F 66 66 69 63 rust GmbH..Offic
2193 65 20 69 64 65 6E 74 69 74 79 20 63 61 72 64 03 e identity card.
2194 02 00 40 20 63 61 72 64 03 02 00 40 00 00 00 00 ..@ card...@....
2195 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
2199 5 4: OCTET STRING 05 45 36 9F
2200 11 12: UTF8String 'D-Trust GmbH'
2201 25 20: [0] 'Office identity card'
2203 : '00000010'B (bit 1)
2204 : Error: Spurious zero bits in bitstring.
2212 read_ef_tokeninfo (app_t app)
2215 unsigned char *buffer = NULL;
2217 const unsigned char *p;
2218 size_t n, objlen, hdrlen;
2219 int class, tag, constructed, ndef;
2222 err = select_and_read_binary (app->slot, 0x5032, "TokenInfo",
2230 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2231 &ndef, &objlen, &hdrlen);
2232 if (!err && (objlen > n || tag != TAG_SEQUENCE))
2233 err = gpg_error (GPG_ERR_INV_OBJ);
2236 log_error ("error parsing TokenInfo: %s\n", gpg_strerror (err));
2243 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2244 &ndef, &objlen, &hdrlen);
2245 if (!err && (objlen > n || tag != TAG_INTEGER))
2246 err = gpg_error (GPG_ERR_INV_OBJ);
2250 for (ul=0; objlen; objlen--)
2253 ul |= (*p++) & 0xff;
2258 log_error ("invalid version %lu in TokenInfo\n", ul);
2259 err = gpg_error (GPG_ERR_INV_OBJ);
2264 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2265 &ndef, &objlen, &hdrlen);
2266 if (!err && (objlen > n || tag != TAG_OCTET_STRING || !objlen))
2267 err = gpg_error (GPG_ERR_INV_OBJ);
2271 xfree (app->app_local->serialno);
2272 app->app_local->serialno = xtrymalloc (objlen);
2273 if (!app->app_local->serialno)
2275 err = gpg_error_from_syserror ();
2278 memcpy (app->app_local->serialno, p, objlen);
2279 app->app_local->serialnolen = objlen;
2280 log_printhex ("Serialnumber from EF(TokenInfo) is:", p, objlen);
2288 /* Get all the basic information from the pkcs#15 card, check the
2289 structure and initialize our local context. This is used once at
2290 application initialization. */
2292 read_p15_info (app_t app)
2296 if (!read_ef_tokeninfo (app))
2298 /* If we don't have a serial number yet but the TokenInfo provides
2300 if (!app->serialno && app->app_local->serialno)
2302 app->serialno = app->app_local->serialno;
2303 app->serialnolen = app->app_local->serialnolen;
2304 app->app_local->serialno = NULL;
2305 app->app_local->serialnolen = 0;
2306 err = app_munge_serialno (app);
2312 /* Read the ODF so that we know the location of all directory
2314 /* Fixme: We might need to get a non-standard ODF FID from TokenInfo. */
2315 err = read_ef_odf (app, 0x5031);
2319 /* Read certificate information. */
2320 assert (!app->app_local->certificate_info);
2321 assert (!app->app_local->trusted_certificate_info);
2322 assert (!app->app_local->useful_certificate_info);
2323 err = read_ef_cdf (app, app->app_local->odf.certificates,
2324 &app->app_local->certificate_info);
2325 if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
2326 err = read_ef_cdf (app, app->app_local->odf.trusted_certificates,
2327 &app->app_local->trusted_certificate_info);
2328 if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
2329 err = read_ef_cdf (app, app->app_local->odf.useful_certificates,
2330 &app->app_local->useful_certificate_info);
2331 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
2336 /* Read information about private keys. */
2337 assert (!app->app_local->private_key_info);
2338 err = read_ef_prkdf (app, app->app_local->odf.private_keys,
2339 &app->app_local->private_key_info);
2340 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
2345 /* Read information about authentication objects. */
2346 assert (!app->app_local->auth_object_info);
2347 err = read_ef_aodf (app, app->app_local->odf.auth_objects,
2348 &app->app_local->auth_object_info);
2349 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
2357 /* Helper to do_learn_status: Send information about all certificates
2358 listed in CERTINFO back. Use CERTTYPE as type of the
2361 send_certinfo (app_t app, ctrl_t ctrl, const char *certtype,
2362 cdf_object_t certinfo)
2364 for (; certinfo; certinfo = certinfo->next)
2368 buf = xtrymalloc (9 + certinfo->objidlen*2 + 1);
2370 return gpg_error_from_syserror ();
2371 p = stpcpy (buf, "P15");
2372 if (app->app_local->home_df)
2374 snprintf (p, 6, "-%04X",
2375 (unsigned int)(app->app_local->home_df & 0xffff));
2378 p = stpcpy (p, ".");
2379 bin2hex (certinfo->objid, certinfo->objidlen, p);
2381 send_status_info (ctrl, "CERTINFO",
2382 certtype, strlen (certtype),
2391 /* Get the keygrip of the private key object PRKDF. On success the
2392 keygrip gets returned in the caller provided 41 byte buffer
2395 keygripstr_from_prkdf (app_t app, prkdf_object_t prkdf, char *r_gripstr)
2403 /* FIXME: We should check whether a public key directory file and a
2404 matching public key for PRKDF is available. This should make
2405 extraction of the key much easier. My current test card doesn't
2406 have one, so we can only use the fallback solution bu looking for
2407 a matching certificate and extract the key from there. */
2409 /* Look for a matching certificate. A certificate matches if the Id
2410 matches the one of the private key info. */
2411 for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
2412 if (cdf->objidlen == prkdf->objidlen
2413 && !memcmp (cdf->objid, prkdf->objid, prkdf->objidlen))
2416 for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
2417 if (cdf->objidlen == prkdf->objidlen
2418 && !memcmp (cdf->objid, prkdf->objid, prkdf->objidlen))
2421 for (cdf = app->app_local->useful_certificate_info; cdf; cdf = cdf->next)
2422 if (cdf->objidlen == prkdf->objidlen
2423 && !memcmp (cdf->objid, prkdf->objid, prkdf->objidlen))
2426 return gpg_error (GPG_ERR_NOT_FOUND);
2428 err = readcert_by_cdf (app, cdf, &der, &derlen);
2432 err = ksba_cert_new (&cert);
2434 err = ksba_cert_init_from_mem (cert, der, derlen);
2437 err = app_help_get_keygrip_string (cert, r_gripstr);
2438 ksba_cert_release (cert);
2446 /* Helper to do_learn_status: Send information about all known
2447 keypairs back. FIXME: much code duplication from
2450 send_keypairinfo (app_t app, ctrl_t ctrl, prkdf_object_t keyinfo)
2454 for (; keyinfo; keyinfo = keyinfo->next)
2460 buf = xtrymalloc (9 + keyinfo->objidlen*2 + 1);
2462 return gpg_error_from_syserror ();
2463 p = stpcpy (buf, "P15");
2464 if (app->app_local->home_df)
2466 snprintf (p, 6, "-%04hX",
2467 (unsigned int)(app->app_local->home_df & 0xffff));
2470 p = stpcpy (p, ".");
2471 bin2hex (keyinfo->objid, keyinfo->objidlen, p);
2473 err = keygripstr_from_prkdf (app, keyinfo, gripstr);
2476 log_error ("can't get keygrip from ");
2477 for (j=0; j < keyinfo->pathlen; j++)
2478 log_printf ("%04hX", keyinfo->path[j]);
2479 log_printf (": %s\n", gpg_strerror (err));
2483 assert (strlen (gripstr) == 40);
2484 send_status_info (ctrl, "KEYPAIRINFO",
2496 /* This is the handler for the LEARN command. */
2498 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
2506 err = send_certinfo (app, ctrl, "100", app->app_local->certificate_info);
2508 err = send_certinfo (app, ctrl, "101",
2509 app->app_local->trusted_certificate_info);
2511 err = send_certinfo (app, ctrl, "102",
2512 app->app_local->useful_certificate_info);
2516 err = send_keypairinfo (app, ctrl, app->app_local->private_key_info);
2522 /* Read a certifciate using the information in CDF and return the
2523 certificate in a newly llocated buffer R_CERT and its length
2526 readcert_by_cdf (app_t app, cdf_object_t cdf,
2527 unsigned char **r_cert, size_t *r_certlen)
2530 unsigned char *buffer = NULL;
2531 const unsigned char *p, *save_p;
2533 int class, tag, constructed, ndef;
2534 size_t totobjlen, objlen, hdrlen;
2541 /* First check whether it has been cached. */
2544 *r_cert = xtrymalloc (cdf->imagelen);
2546 return gpg_error_from_syserror ();
2547 memcpy (*r_cert, cdf->image, cdf->imagelen);
2548 *r_certlen = cdf->imagelen;
2552 /* Read the entire file. fixme: This could be optimized by first
2553 reading the header to figure out how long the certificate
2555 err = select_ef_by_path (app, cdf->path, cdf->pathlen);
2559 err = iso7816_read_binary (app->slot, cdf->off, cdf->len, &buffer, &buflen);
2560 if (!err && (!buflen || *buffer == 0xff))
2561 err = gpg_error (GPG_ERR_NOT_FOUND);
2564 log_error ("error reading certificate with Id ");
2565 for (i=0; i < cdf->objidlen; i++)
2566 log_printf ("%02X", cdf->objid[i]);
2567 log_printf (": %s\n", gpg_strerror (err));
2571 /* Check whether this is really a certificate. */
2574 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2575 &ndef, &objlen, &hdrlen);
2579 if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed)
2581 else if ( class == CLASS_UNIVERSAL && tag == TAG_SET && constructed )
2585 err = gpg_error (GPG_ERR_INV_OBJ);
2588 totobjlen = objlen + hdrlen;
2589 assert (totobjlen <= buflen);
2591 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2592 &ndef, &objlen, &hdrlen);
2597 && class == CLASS_UNIVERSAL && tag == TAG_OBJECT_ID && !constructed)
2599 /* The certificate seems to be contained in a userCertificate
2600 container. Skip this and assume the following sequence is
2604 err = gpg_error (GPG_ERR_INV_OBJ);
2610 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2611 &ndef, &objlen, &hdrlen);
2614 if ( !(class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed) )
2616 err = gpg_error (GPG_ERR_INV_OBJ);
2619 totobjlen = objlen + hdrlen;
2620 assert (save_p + totobjlen <= buffer + buflen);
2621 memmove (buffer, save_p, totobjlen);
2626 *r_certlen = totobjlen;
2628 /* Try to cache it. */
2629 if (!cdf->image && (cdf->image = xtrymalloc (*r_certlen)))
2631 memcpy (cdf->image, *r_cert, *r_certlen);
2632 cdf->imagelen = *r_certlen;
2642 /* Handler for the READCERT command.
2644 Read the certificate with id CERTID (as returned by learn_status in
2645 the CERTINFO status lines) and return it in the freshly allocated
2646 buffer to be stored at R_CERT and its length at R_CERTLEN. A error
2647 code will be returned on failure and R_CERT and R_CERTLEN will be
2650 do_readcert (app_t app, const char *certid,
2651 unsigned char **r_cert, size_t *r_certlen)
2658 err = cdf_object_from_certid (app, certid, &cdf);
2660 err = readcert_by_cdf (app, cdf, r_cert, r_certlen);
2666 /* Implement the GETATTR command. This is similar to the LEARN
2667 command but returns just one value via the status interface. */
2669 do_getattr (app_t app, ctrl_t ctrl, const char *name)
2673 if (!strcmp (name, "$AUTHKEYID"))
2676 prkdf_object_t prkdf;
2678 /* We return the ID of the first private keycapable of
2680 for (prkdf = app->app_local->private_key_info; prkdf;
2681 prkdf = prkdf->next)
2682 if (prkdf->usageflags.sign)
2686 buf = xtrymalloc (9 + prkdf->objidlen*2 + 1);
2688 return gpg_error_from_syserror ();
2689 p = stpcpy (buf, "P15");
2690 if (app->app_local->home_df)
2692 snprintf (p, 6, "-%04hX",
2693 (unsigned int)(app->app_local->home_df & 0xffff));
2696 p = stpcpy (p, ".");
2697 bin2hex (prkdf->objid, prkdf->objidlen, p);
2699 send_status_info (ctrl, name, buf, strlen (buf), NULL, 0);
2704 else if (!strcmp (name, "$DISPSERIALNO"))
2706 /* For certain cards we return special IDs. There is no
2707 general rule for it so we need to decide case by case. */
2708 if (app->app_local->card_type == CARD_TYPE_BELPIC)
2710 /* The eID card has a card number printed on the front matter
2711 which seems to be a good indication. */
2712 unsigned char *buffer;
2713 const unsigned char *p;
2715 unsigned short path[] = { 0x3F00, 0xDF01, 0x4031 };
2717 err = select_ef_by_path (app, path, DIM(path) );
2719 err = iso7816_read_binary (app->slot, 0, 0, &buffer, &buflen);
2722 log_error ("error accessing EF(ID): %s\n", gpg_strerror (err));
2726 p = find_tlv (buffer, buflen, 1, &n);
2732 memcpy (tmp+4, p+3, 7);
2734 memcpy (tmp+12, p+10, 2);
2736 send_status_info (ctrl, name, tmp, strlen (tmp), NULL, 0);
2744 return gpg_error (GPG_ERR_INV_NAME);
2750 /* Micardo cards require special treatment. This is a helper for the
2751 crypto functions to manage the security environment. We expect that
2752 the key file has already been selected. FID is the one of the
2755 micardo_mse (app_t app, unsigned short fid)
2759 unsigned short refdata = 0;
2761 unsigned char msebuf[10];
2763 /* Read the KeyD file containing extra information on keys. */
2764 err = iso7816_select_file (app->slot, 0x0013, 0, NULL, NULL);
2767 log_error ("error reading EF_keyD: %s\n", gpg_strerror (err));
2771 for (recno = 1, se_num = -1; ; recno++)
2773 unsigned char *buffer;
2776 const unsigned char *p, *pp;
2778 err = iso7816_read_record (app->slot, recno, 1, 0, &buffer, &buflen);
2779 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2783 log_error ("error reading EF_keyD record: %s\n",
2784 gpg_strerror (err));
2787 log_printhex ("keyD record:", buffer, buflen);
2788 p = find_tlv (buffer, buflen, 0x83, &n);
2789 if (p && n == 4 && ((p[2]<<8)|p[3]) == fid)
2791 refdata = ((p[0]<<8)|p[1]);
2792 /* Locate the SE DO and the there included sec env number. */
2793 p = find_tlv (buffer, buflen, 0x7b, &n);
2796 pp = find_tlv (p, n, 0x80, &nn);
2809 log_error ("CRT for keyfile %04hX not found\n", fid);
2810 return gpg_error (GPG_ERR_NOT_FOUND);
2814 /* Restore the security environment to SE_NUM if needed */
2817 err = iso7816_manage_security_env (app->slot, 0xf3, se_num, NULL, 0);
2820 log_error ("restoring SE to %d failed: %s\n",
2821 se_num, gpg_strerror (err));
2826 /* Set the DST reference data. */
2830 msebuf[3] = (refdata >> 8);
2831 msebuf[4] = refdata;
2832 err = iso7816_manage_security_env (app->slot, 0x41, 0xb6, msebuf, 5);
2835 log_error ("setting SE to reference file %04hX failed: %s\n",
2836 refdata, gpg_strerror (err));
2844 /* Handler for the PKSIGN command.
2846 Create the signature and return the allocated result in OUTDATA.
2847 If a PIN is required, the PINCB will be used to ask for the PIN;
2848 that callback should return the PIN in an allocated buffer and
2849 store that as the 3rd argument. */
2851 do_sign (app_t app, const char *keyidstr, int hashalgo,
2852 gpg_error_t (*pincb)(void*, const char *, char **),
2854 const void *indata, size_t indatalen,
2855 unsigned char **outdata, size_t *outdatalen )
2857 static unsigned char sha1_prefix[15] = /* Object ID is 1.3.14.3.2.26 */
2858 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
2859 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
2860 static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
2861 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
2862 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
2866 unsigned char data[36]; /* Must be large enough for a SHA-1 digest
2867 + the largest OID prefix above and also
2868 fit the 36 bytes of md5sha1. */
2869 prkdf_object_t prkdf; /* The private key object. */
2870 aodf_object_t aodf; /* The associated authentication object. */
2871 int no_data_padding = 0; /* True if the card want the data without padding.*/
2872 int mse_done = 0; /* Set to true if the MSE has been done. */
2874 if (!keyidstr || !*keyidstr)
2875 return gpg_error (GPG_ERR_INV_VALUE);
2876 if (indatalen != 20 && indatalen != 16 && indatalen != 35 && indatalen != 36)
2877 return gpg_error (GPG_ERR_INV_VALUE);
2879 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
2882 if (!(prkdf->usageflags.sign || prkdf->usageflags.sign_recover
2883 ||prkdf->usageflags.non_repudiation))
2885 log_error ("key %s may not be used for signing\n", keyidstr);
2886 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
2891 log_error ("no authentication object defined for %s\n", keyidstr);
2892 /* fixme: we might want to go ahead and do without PIN
2894 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
2897 /* Find the authentication object to this private key object. */
2898 for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
2899 if (aodf->objidlen == prkdf->authidlen
2900 && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
2904 log_error ("authentication object for %s missing\n", keyidstr);
2905 return gpg_error (GPG_ERR_INV_CARD);
2909 log_error ("PIN verification is protected by an "
2910 "additional authentication token\n");
2911 return gpg_error (GPG_ERR_BAD_PIN_METHOD);
2913 if (aodf->pinflags.integrity_protected
2914 || aodf->pinflags.confidentiality_protected)
2916 log_error ("PIN verification requires unsupported protection method\n");
2917 return gpg_error (GPG_ERR_BAD_PIN_METHOD);
2919 if (!aodf->stored_length && aodf->pinflags.needs_padding)
2921 log_error ("PIN verification requires padding but no length known\n");
2922 return gpg_error (GPG_ERR_INV_CARD);
2925 /* Select the key file. Note that this may change the security
2926 environment thus we do it before PIN verification. */
2927 err = select_ef_by_path (app, prkdf->path, prkdf->pathlen);
2930 log_error ("error selecting file for key %s: %s\n",
2931 keyidstr, gpg_strerror (errno));
2936 /* Due to the fact that the non-repudiation signature on a BELPIC
2937 card requires a verify immediately before the DSO we set the
2938 MSE before we do the verification. Other cards might allow to do
2939 this also but I don't want to break anything, thus we do it only
2940 for the BELPIC card here. */
2941 if (app->app_local->card_type == CARD_TYPE_BELPIC)
2943 unsigned char mse[5];
2945 mse[0] = 4; /* Length of the template. */
2946 mse[1] = 0x80; /* Algorithm reference tag. */
2947 if (hashalgo == MD_USER_TLS_MD5SHA1)
2948 mse[2] = 0x01; /* Let card do pkcs#1 0xFF padding. */
2950 mse[2] = 0x02; /* RSASSA-PKCS1-v1.5 using SHA1. */
2951 mse[3] = 0x84; /* Private key reference tag. */
2952 mse[4] = prkdf->key_reference_valid? prkdf->key_reference : 0x82;
2954 err = iso7816_manage_security_env (app->slot,
2957 no_data_padding = 1;
2962 log_error ("MSE failed: %s\n", gpg_strerror (err));
2967 /* Now that we have all the information available, prepare and run
2968 the PIN verification.*/
2976 if (prkdf->usageflags.non_repudiation
2977 && app->app_local->card_type == CARD_TYPE_BELPIC)
2978 err = pincb (pincb_arg, "PIN (qualified signature!)", &pinvalue);
2980 err = pincb (pincb_arg, "PIN", &pinvalue);
2983 log_info ("PIN callback returned error: %s\n", gpg_strerror (err));
2987 /* We might need to cope with UTF8 things here. Not sure how
2988 min_length etc. are exactly defined, for now we take them as
2989 a plain octet count. */
2991 if (strlen (pinvalue) < aodf->min_length)
2993 log_error ("PIN is too short; minimum length is %lu\n",
2995 err = gpg_error (GPG_ERR_BAD_PIN);
2997 else if (aodf->stored_length && strlen (pinvalue) > aodf->stored_length)
2999 /* This would otherwise truncate the PIN silently. */
3000 log_error ("PIN is too large; maximum length is %lu\n",
3001 aodf->stored_length);
3002 err = gpg_error (GPG_ERR_BAD_PIN);
3004 else if (aodf->max_length_valid && strlen (pinvalue) > aodf->max_length)
3006 log_error ("PIN is too large; maximum length is %lu\n",
3008 err = gpg_error (GPG_ERR_BAD_PIN);
3019 switch (aodf->pintype)
3022 case PIN_TYPE_ASCII_NUMERIC:
3023 for (s=pinvalue; digitp (s); s++)
3027 errstr = "Non-numeric digits found in PIN";
3028 err = gpg_error (GPG_ERR_BAD_PIN);
3033 case PIN_TYPE_HALF_NIBBLE_BCD:
3034 errstr = "PIN type Half-Nibble-BCD is not supported";
3036 case PIN_TYPE_ISO9564_1:
3037 errstr = "PIN type ISO9564-1 is not supported";
3040 errstr = "Unknown PIN type";
3045 log_error ("can't verify PIN: %s\n", errstr);
3047 return err? err : gpg_error (GPG_ERR_BAD_PIN_METHOD);
3051 if (aodf->pintype == PIN_TYPE_BCD )
3056 for (ndigits=0, s=pinvalue; *s; ndigits++, s++)
3058 paddedpin = xtrymalloc (aodf->stored_length+1);
3061 err = gpg_error_from_syserror ();
3067 paddedpin[i++] = 0x20 | (ndigits & 0x0f);
3068 for (s=pinvalue; i < aodf->stored_length && *s && s[1]; s = s+2 )
3069 paddedpin[i++] = (((*s - '0') << 4) | ((s[1] - '0') & 0x0f));
3070 if (i < aodf->stored_length && *s)
3071 paddedpin[i++] = (((*s - '0') << 4)
3072 |((aodf->pad_char_valid?aodf->pad_char:0)&0x0f));
3074 if (aodf->pinflags.needs_padding)
3075 while (i < aodf->stored_length)
3076 paddedpin[i++] = aodf->pad_char_valid? aodf->pad_char : 0;
3079 pinvalue = paddedpin;
3082 else if (aodf->pinflags.needs_padding)
3086 paddedpin = xtrymalloc (aodf->stored_length+1);
3089 err = gpg_error_from_syserror ();
3093 for (i=0, s=pinvalue; i < aodf->stored_length && *s; i++, s++)
3095 /* Not sure what padding char to use if none has been set.
3096 For now we use 0x00; maybe a space would be better. */
3097 for (; i < aodf->stored_length; i++)
3098 paddedpin[i] = aodf->pad_char_valid? aodf->pad_char : 0;
3102 pinvalue = paddedpin;
3105 pinvaluelen = strlen (pinvalue);
3107 err = iso7816_verify (app->slot,
3108 aodf->pin_reference_valid? aodf->pin_reference : 0,
3109 pinvalue, pinvaluelen);
3113 log_error ("PIN verification failed: %s\n", gpg_strerror (err));
3116 log_debug ("PIN verification succeeded\n");
3119 /* Prepare the DER object from INDATA. */
3120 if (indatalen == 36)
3122 /* No ASN.1 container used. */
3123 if (hashalgo != MD_USER_TLS_MD5SHA1)
3124 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3125 memcpy (data, indata, indatalen);
3127 else if (indatalen == 35)
3129 /* Alright, the caller was so kind to send us an already
3130 prepared DER object. Check that it is what we want and that
3131 it matches the hash algorithm. */
3132 if (hashalgo == GCRY_MD_SHA1 && !memcmp (indata, sha1_prefix, 15))
3134 else if (hashalgo == GCRY_MD_RMD160
3135 && !memcmp (indata, rmd160_prefix, 15))
3138 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3139 memcpy (data, indata, indatalen);
3143 /* Need to prepend the prefix. */
3144 if (hashalgo == GCRY_MD_SHA1)
3145 memcpy (data, sha1_prefix, 15);
3146 else if (hashalgo == GCRY_MD_RMD160)
3147 memcpy (data, rmd160_prefix, 15);
3149 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3150 memcpy (data+15, indata, indatalen);
3153 /* Manage security environment needs to be weaked for certain cards. */
3156 else if (app->app_local->card_type == CARD_TYPE_TCOS)
3158 /* TCOS creates signatures always using the local key 0. MSE
3161 else if (app->app_local->card_type == CARD_TYPE_MICARDO)
3163 if (!prkdf->pathlen)
3164 err = gpg_error (GPG_ERR_BUG);
3166 err = micardo_mse (app, prkdf->path[prkdf->pathlen-1]);
3168 else if (prkdf->key_reference_valid)
3170 unsigned char mse[3];
3172 mse[0] = 0x84; /* Select asym. key. */
3174 mse[2] = prkdf->key_reference;
3176 err = iso7816_manage_security_env (app->slot,
3182 log_error ("MSE failed: %s\n", gpg_strerror (err));
3186 if (hashalgo == MD_USER_TLS_MD5SHA1)
3187 err = iso7816_compute_ds (app->slot, 0, data, 36, 0, outdata, outdatalen);
3188 else if (no_data_padding)
3189 err = iso7816_compute_ds (app->slot, 0, data+15, 20, 0,outdata,outdatalen);
3191 err = iso7816_compute_ds (app->slot, 0, data, 35, 0, outdata, outdatalen);
3196 /* Handler for the PKAUTH command.
3198 This is basically the same as the PKSIGN command but we first check
3199 that the requested key is suitable for authentication; that is, it
3200 must match the criteria used for the attribute $AUTHKEYID. See
3201 do_sign for calling conventions; there is no HASHALGO, though. */
3203 do_auth (app_t app, const char *keyidstr,
3204 gpg_error_t (*pincb)(void*, const char *, char **),
3206 const void *indata, size_t indatalen,
3207 unsigned char **outdata, size_t *outdatalen )
3210 prkdf_object_t prkdf;
3213 if (!keyidstr || !*keyidstr)
3214 return gpg_error (GPG_ERR_INV_VALUE);
3216 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
3219 if (!prkdf->usageflags.sign)
3221 log_error ("key %s may not be used for authentication\n", keyidstr);
3222 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
3225 algo = indatalen == 36? MD_USER_TLS_MD5SHA1 : GCRY_MD_SHA1;
3226 return do_sign (app, keyidstr, algo, pincb, pincb_arg,
3227 indata, indatalen, outdata, outdatalen);
3232 /* Assume that EF(DIR) has been selected. Read its content and figure
3233 out the home EF of pkcs#15. Return that home DF or 0 if not found
3234 and the value at the address of BELPIC indicates whether it was
3235 found by the belpic aid. */
3236 static unsigned short
3237 read_home_df (int slot, int *r_belpic)
3240 unsigned char *buffer;
3241 const unsigned char *p, *pp;
3242 size_t buflen, n, nn;
3243 unsigned short result = 0;
3247 err = iso7816_read_binary (slot, 0, 0, &buffer, &buflen);
3250 log_error ("error reading EF{DIR}: %s\n", gpg_strerror (err));
3254 /* FIXME: We need to scan all records. */
3255 p = find_tlv (buffer, buflen, 0x61, &n);
3258 pp = find_tlv (p, n, 0x4f, &nn);
3259 if (pp && ((nn == sizeof pkcs15_aid && !memcmp (pp, pkcs15_aid, nn))
3260 || (*r_belpic = (nn == sizeof pkcs15be_aid
3261 && !memcmp (pp, pkcs15be_aid, nn)))))
3263 pp = find_tlv (p, n, 0x50, &nn);
3264 if (pp) /* fixme: Filter log value? */
3265 log_info ("pkcs#15 application label from EF(DIR) is '%.*s'\n",
3267 pp = find_tlv (p, n, 0x51, &nn);
3268 if (pp && nn == 4 && *pp == 0x3f && !pp[1])
3270 result = ((pp[2] << 8) | pp[3]);
3271 log_info ("pkcs#15 application directory is 0x%04hX\n", result);
3281 Select the PKCS#15 application on the card in SLOT.
3284 app_select_p15 (app_t app)
3286 int slot = app->slot;
3288 unsigned short def_home_df = 0;
3289 card_type_t card_type = CARD_TYPE_UNKNOWN;
3293 rc = iso7816_select_application (slot, pkcs15_aid, sizeof pkcs15_aid, 0);
3295 { /* Not found: Try to locate it from 2F00. We use direct path
3296 selection here because it seems that the Belgian eID card
3297 does only allow for that. Many other cards supports this
3298 selection method too. Note, that we don't use
3299 select_application above for the Belgian card - the call
3300 works but it seems that it did not switch to the correct DF.
3301 Using the 2f02 just works. */
3302 unsigned short path[1] = { 0x2f00 };
3304 rc = iso7816_select_path (app->slot, path, 1, NULL, NULL);
3308 def_home_df = read_home_df (slot, &is_belpic);
3311 path[0] = def_home_df;
3312 rc = iso7816_select_path (app->slot, path, 1, NULL, NULL);
3317 { /* Still not found: Try the default DF. */
3318 def_home_df = 0x5015;
3319 rc = iso7816_select_file (slot, def_home_df, 1, NULL, NULL);
3323 /* Determine the type of the card. The general case is to look
3324 it up from the ATR table. For the Belgian eID card we know
3325 it instantly from the AID. */
3328 card_type = CARD_TYPE_BELPIC;
3336 atr = apdu_get_atr (app->slot, &atrlen);
3338 rc = gpg_error (GPG_ERR_INV_CARD);
3341 for (i=0; card_atr_list[i].atrlen; i++)
3342 if (card_atr_list[i].atrlen == atrlen
3343 && !memcmp (card_atr_list[i].atr, atr, atrlen))
3345 card_type = card_atr_list[i].type;
3354 app->apptype = "P15";
3356 app->app_local = xtrycalloc (1, sizeof *app->app_local);
3357 if (!app->app_local)
3359 rc = gpg_error_from_syserror ();
3363 /* Set the home DF. Note that we currently can't do that if the
3364 selection via application ID worked. This will store 0 there
3365 instead. FIXME: We either need to figure the home_df via the
3366 DIR file or using the return values from the select file
3368 app->app_local->home_df = def_home_df;
3370 /* Store the card type. FIXME: We might want to put this into
3371 the common APP structure. */
3372 app->app_local->card_type = card_type;
3374 /* Store whether we may and should use direct path selection. */
3375 app->app_local->direct_path_selection = direct;
3377 /* Read basic information and thus check whether this is a real
3379 rc = read_p15_info (app);
3383 /* Special serial number munging. We need to check for a German
3384 prototype card right here because we need to access to
3385 EF(TokenInfo). We mark such a serial number by the using a
3386 prefix of FF0100. */
3387 if (app->serialnolen == 12
3388 && !memcmp (app->serialno, "\xD2\x76\0\0\0\0\0\0\0\0\0\0", 12))
3390 /* This is a German card with a silly serial number. Try to get
3391 the serial number from the EF(TokenInfo). . */
3394 /* FIXME: actually get it from EF(TokenInfo). */
3396 p = xtrymalloc (3 + app->serialnolen);
3398 rc = gpg_error (gpg_err_code_from_errno (errno));
3401 memcpy (p, "\xff\x01", 3);
3402 memcpy (p+3, app->serialno, app->serialnolen);
3403 app->serialnolen += 3;
3404 xfree (app->serialno);
3409 app->fnc.deinit = do_deinit;
3410 app->fnc.learn_status = do_learn_status;
3411 app->fnc.readcert = do_readcert;
3412 app->fnc.getattr = do_getattr;
3413 app->fnc.setattr = NULL;
3414 app->fnc.genkey = NULL;
3415 app->fnc.sign = do_sign;
3416 app->fnc.auth = do_auth;
3417 app->fnc.decipher = NULL;
3418 app->fnc.change_pin = NULL;
3419 app->fnc.check_pin = NULL;