1 /* app-p15.c - The pkcs#15 card application.
2 * Copyright (C) 2005 Free Software Foundation, Inc.
3 * Copyright (C) 2020 g10 Code GmbH
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <https://www.gnu.org/licenses/>.
19 * SPDX-License-Identifier: GPL-3.0-or-later
22 /* Information pertaining to the BELPIC developer card samples:
24 Unblock PUK: "222222111111"
25 Reset PIN: "333333111111")
27 e.g. the APDUs 00:20:00:02:08:2C:33:33:33:11:11:11:FF
28 and 00:24:01:01:08:24:12:34:FF:FF:FF:FF:FF
29 should change the PIN into 1234.
43 #include "app-common.h"
44 #include "../common/i18n.h"
45 #include "../common/tlv.h"
46 #include "apdu.h" /* fixme: we should move the card detection to a
49 /* Types of cards we know and which needs special treatment. */
56 CARD_TYPE_BELPIC /* Belgian eID card specs. */
60 /* The OS of card as specified by card_type_t is not always
61 * sufficient. Thus we also distinguish the actual product build upon
66 CARD_PRODUCT_DTRUST /* D-Trust GmbH (bundesdruckerei.de) */
71 /* A list card types with ATRs noticed with these cards. */
72 #define X(a) ((unsigned char const *)(a))
76 unsigned char const *atr;
79 { 19, X("\x3B\xBA\x13\x00\x81\x31\x86\x5D\x00\x64\x05\x0A\x02\x01\x31\x80"
81 CARD_TYPE_TCOS }, /* SLE44 */
82 { 19, X("\x3B\xBA\x14\x00\x81\x31\x86\x5D\x00\x64\x05\x14\x02\x02\x31\x80"
84 CARD_TYPE_TCOS }, /* SLE66S */
85 { 19, X("\x3B\xBA\x96\x00\x81\x31\x86\x5D\x00\x64\x05\x60\x02\x03\x31\x80"
87 CARD_TYPE_TCOS }, /* SLE66P */
88 { 27, X("\x3B\xFF\x94\x00\xFF\x80\xB1\xFE\x45\x1F\x03\x00\x68\xD2\x76\x00"
89 "\x00\x28\xFF\x05\x1E\x31\x80\x00\x90\x00\x23"),
90 CARD_TYPE_MICARDO }, /* German BMI card */
91 { 19, X("\x3B\x6F\x00\xFF\x00\x68\xD2\x76\x00\x00\x28\xFF\x05\x1E\x31\x80"
93 CARD_TYPE_MICARDO }, /* German BMI card (ATR due to reader problem) */
94 { 26, X("\x3B\xFE\x94\x00\xFF\x80\xB1\xFA\x45\x1F\x03\x45\x73\x74\x45\x49"
95 "\x44\x20\x76\x65\x72\x20\x31\x2E\x30\x43"),
96 CARD_TYPE_MICARDO }, /* EstEID (Estonian Big Brother card) */
97 { 11, X("\x3b\xd2\x18\x00\x81\x31\xfe\x58\xc9\x01\x14"),
98 CARD_TYPE_CARDOS_50 }, /* CardOS 5.0 */
104 /* The AID of PKCS15. */
105 static char const pkcs15_aid[] = { 0xA0, 0, 0, 0, 0x63,
106 0x50, 0x4B, 0x43, 0x53, 0x2D, 0x31, 0x35 };
108 /* The Belgian eID variant - they didn't understood why a shared AID
109 is useful for a standard. Oh well. */
110 static char const pkcs15be_aid[] = { 0xA0, 0, 0, 0x01, 0x77,
111 0x50, 0x4B, 0x43, 0x53, 0x2D, 0x31, 0x35 };
114 /* The PIN types as defined in pkcs#15 v1.1 */
118 PIN_TYPE_ASCII_NUMERIC = 1,
120 PIN_TYPE_HALF_NIBBLE_BCD = 3,
121 PIN_TYPE_ISO9564_1 = 4
125 /* A bit array with for the key usage flags from the
126 commonKeyAttributes. */
127 struct keyusage_flags_s
129 unsigned int encrypt: 1;
130 unsigned int decrypt: 1;
131 unsigned int sign: 1;
132 unsigned int sign_recover: 1;
133 unsigned int wrap: 1;
134 unsigned int unwrap: 1;
135 unsigned int verify: 1;
136 unsigned int verify_recover: 1;
137 unsigned int derive: 1;
138 unsigned int non_repudiation: 1;
140 typedef struct keyusage_flags_s keyusage_flags_t;
144 /* This is an object to store information about a Certificate
145 Directory File (CDF) in a format suitable for further processing by
146 us. To keep memory management, simple we use a linked list of
147 items; i.e. one such object represents one certificate and the list
151 /* Link to next item when used in a linked list. */
152 struct cdf_object_s *next;
154 /* Flags to indicate whether fields are valid. */
155 unsigned int have_off:1;
157 /* Length and allocated buffer with the Id of this object.
158 * This field is used for X.509 in PKCS#11 to make it easier to
159 * match a private key with a certificate. */
161 unsigned char *objid;
163 /* To avoid reading a certificate more than once, we cache it in an
164 allocated memory IMAGE of IMAGELEN. */
166 unsigned char *image;
168 /* The offset and length of the object. They are only valid if
169 HAVE_OFF is true and set to 0 if HAVE_OFF is false. */
170 unsigned long off, len;
172 /* The length of the path as given in the CDF and the path itself.
173 path[0] is the top DF (usually 0x3f00). The path will never be
176 unsigned short path[1];
178 typedef struct cdf_object_s *cdf_object_t;
181 /* This is an object to store information about a Private Key
182 Directory File (PrKDF) in a format suitable for further processing
183 by us. To keep memory management, simple we use a linked list of
184 items; i.e. one such object represents one certificate and the list
186 struct prkdf_object_s
188 /* Link to next item when used in a linked list. */
189 struct prkdf_object_s *next;
191 /* Flags to indicate whether fields are valid. */
192 unsigned int keygrip_valid:1;
193 unsigned int key_reference_valid:1;
194 unsigned int have_off:1;
196 /* Flag indicating that the corresponding PIN has already been
198 unsigned int pin_verified:1;
200 /* The key's usage flags. */
201 keyusage_flags_t usageflags;
203 /* The keygrip of the key. This is used as a cache. */
204 char keygrip[2*KEYGRIP_LEN+1];
206 /* The Gcrypt algo identifier for the key. It is valid if the
207 * keygrip is also valid. */
210 /* The length of the key in bits (e.g. for RSA the length of the
211 * modulus). It is valid if the keygrip is also valid. */
212 unsigned int keynbits;
214 /* Malloced CN from the Subject-DN of the corresponding certificate
215 * or NULL if not known. */
218 /* Malloced SerialNumber from the Subject-DN of the corresponding
219 * certificate or NULL if not known. */
222 /* Length and allocated buffer with the Id of this object. */
224 unsigned char *objid;
226 /* Length and allocated buffer with the authId of this object or
227 NULL if no authID is known. */
229 unsigned char *authid;
231 /* The keyReference and a flag telling whether it is valid. */
232 unsigned long key_reference;
234 /* The offset and length of the object. They are only valid if
235 * HAVE_OFF is true otherwise they are set to 0. */
236 unsigned long off, len;
238 /* The length of the path as given in the PrKDF and the path itself.
239 path[0] is the top DF (usually 0x3f00). */
241 unsigned short path[1];
243 typedef struct prkdf_object_s *prkdf_object_t;
246 /* This is an object to store information about a Authentication
247 Object Directory File (AODF) in a format suitable for further
248 processing by us. To keep memory management, simple we use a linked
249 list of items; i.e. one such object represents one authentication
250 object and the list the entire AOKDF. */
253 /* Link to next item when used in a linked list. */
254 struct aodf_object_s *next;
256 /* Flags to indicate whether fields are valid. */
257 unsigned int have_off:1;
259 /* Length and allocated buffer with the Id of this object. */
261 unsigned char *objid;
263 /* Length and allocated buffer with the authId of this object or
264 NULL if no authID is known. */
266 unsigned char *authid;
268 /* The file ID of this AODF. */
274 unsigned int case_sensitive: 1;
275 unsigned int local: 1;
276 unsigned int change_disabled: 1;
277 unsigned int unblock_disabled: 1;
278 unsigned int initialized: 1;
279 unsigned int needs_padding: 1;
280 unsigned int unblocking_pin: 1;
281 unsigned int so_pin: 1;
282 unsigned int disable_allowed: 1;
283 unsigned int integrity_protected: 1;
284 unsigned int confidentiality_protected: 1;
285 unsigned int exchange_ref_data: 1;
291 /* The minimum length of a PIN. */
292 unsigned long min_length;
294 /* The stored length of a PIN. */
295 unsigned long stored_length;
297 /* The maximum length of a PIN and a flag telling whether it is valid. */
298 unsigned long max_length;
299 int max_length_valid;
301 /* The pinReference and a flag telling whether it is valid. */
302 unsigned long pin_reference;
303 int pin_reference_valid;
305 /* The padChar and a flag telling whether it is valid. */
309 /* The offset and length of the object. They are only valid if
310 HAVE_OFF is true and set to 0 if HAVE_OFF is false. */
311 unsigned long off, len;
313 /* The length of the path as given in the Aodf and the path itself.
314 path[0] is the top DF (usually 0x3f00). PATH is optional and thus
315 may be NULL. Malloced.*/
317 unsigned short *path;
319 typedef struct aodf_object_s *aodf_object_t;
322 /* Context local to this application. */
325 /* The home DF. Note, that we don't yet support a multilevel
326 hierarchy. Thus we assume this is directly below the MF. */
327 unsigned short home_df;
329 /* The type of the card's OS. */
330 card_type_t card_type;
332 /* The vendor's product. */
333 card_product_t card_product;
335 /* Flag indicating whether we may use direct path selection. */
336 int direct_path_selection;
338 /* Structure with the EFIDs of the objects described in the ODF
342 unsigned short private_keys;
343 unsigned short public_keys;
344 unsigned short trusted_public_keys;
345 unsigned short secret_keys;
346 unsigned short certificates;
347 unsigned short trusted_certificates;
348 unsigned short useful_certificates;
349 unsigned short data_objects;
350 unsigned short auth_objects;
353 /* The PKCS#15 serialnumber from EF(TokeiNFo) or NULL. Malloced. */
354 unsigned char *serialno;
357 /* The manufacturerID from the TokenInfo EF. Malloced. */
358 char *manufacturer_id;
360 /* Information on all certificates. */
361 cdf_object_t certificate_info;
362 /* Information on all trusted certificates. */
363 cdf_object_t trusted_certificate_info;
364 /* Information on all useful certificates. */
365 cdf_object_t useful_certificate_info;
367 /* Information on all private keys. */
368 prkdf_object_t private_key_info;
370 /* Information on all authentication objects. */
371 aodf_object_t auth_object_info;
376 /*** Local prototypes. ***/
377 static gpg_error_t keygrip_from_prkdf (app_t app, prkdf_object_t prkdf);
378 static gpg_error_t readcert_by_cdf (app_t app, cdf_object_t cdf,
379 unsigned char **r_cert, size_t *r_certlen);
380 static char *get_dispserialno (app_t app, prkdf_object_t prkdf);
381 static gpg_error_t do_getattr (app_t app, ctrl_t ctrl, const char *name);
385 /* Release the CDF object A */
387 release_cdflist (cdf_object_t a)
391 cdf_object_t tmp = a->next;
399 /* Release the PrKDF object A. */
401 release_prkdflist (prkdf_object_t a)
405 prkdf_object_t tmp = a->next;
406 xfree (a->common_name);
407 xfree (a->serial_number);
415 /* Release just one aodf object. */
417 release_aodf_object (aodf_object_t a)
428 /* Release the AODF list A. */
430 release_aodflist (aodf_object_t a)
434 aodf_object_t tmp = a->next;
435 release_aodf_object (a);
441 /* Release all local resources. */
443 do_deinit (app_t app)
445 if (app && app->app_local)
447 release_cdflist (app->app_local->certificate_info);
448 release_cdflist (app->app_local->trusted_certificate_info);
449 release_cdflist (app->app_local->useful_certificate_info);
450 release_prkdflist (app->app_local->private_key_info);
451 release_aodflist (app->app_local->auth_object_info);
452 xfree (app->app_local->manufacturer_id);
453 xfree (app->app_local->serialno);
454 xfree (app->app_local);
455 app->app_local = NULL;
461 /* Do a select and a read for the file with EFID. EFID_DESC is a
462 desctription of the EF to be used with error messages. On success
463 BUFFER and BUFLEN contain the entire content of the EF. The caller
464 must free BUFFER only on success. */
466 select_and_read_binary (int slot, unsigned short efid, const char *efid_desc,
467 unsigned char **buffer, size_t *buflen)
471 err = iso7816_select_file (slot, efid, 0);
474 log_error ("p15: error selecting %s (0x%04X): %s\n",
475 efid_desc, efid, gpg_strerror (err));
478 err = iso7816_read_binary (slot, 0, 0, buffer, buflen);
481 log_error ("p15: error reading %s (0x%04X): %s\n",
482 efid_desc, efid, gpg_strerror (err));
489 /* This function calls select file to read a file using a complete
490 path which may or may not start at the master file (MF). */
492 select_ef_by_path (app_t app, const unsigned short *path, size_t pathlen)
498 return gpg_error (GPG_ERR_INV_VALUE);
500 if (pathlen && *path != 0x3f00 )
501 log_error ("p15: warning: relative path selection not yet implemented\n");
503 if (app->app_local->direct_path_selection)
505 err = iso7816_select_path (app->slot, path+1, pathlen-1);
508 log_error ("p15: error selecting path ");
509 for (j=0; j < pathlen; j++)
510 log_printf ("%04hX", path[j]);
511 log_printf (": %s\n", gpg_strerror (err));
517 /* FIXME: Need code to remember the last PATH so that we can decide
518 what select commands to send in case the path does not start off
519 with 3F00. We might also want to use direct path selection if
520 supported by the card. */
521 for (i=0; i < pathlen; i++)
523 err = iso7816_select_file (app->slot, path[i], !(i+1 == pathlen));
526 log_error ("p15: error selecting part %d from path ", i);
527 for (j=0; j < pathlen; j++)
528 log_printf ("%04hX", path[j]);
529 log_printf (": %s\n", gpg_strerror (err));
537 /* Parse a cert Id string (or a key Id string) and return the binary
538 object Id string in a newly allocated buffer stored at R_OBJID and
539 R_OBJIDLEN. On Error NULL will be stored there and an error code
540 returned. On success caller needs to free the buffer at R_OBJID. */
542 parse_certid (app_t app, const char *certid,
543 unsigned char **r_objid, size_t *r_objidlen)
548 unsigned char *objid;
554 if (certid[0] != 'P' && strlen (certid) == 40) /* This is a keygrip. */
556 prkdf_object_t prkdf;
558 for (prkdf = app->app_local->private_key_info;
559 prkdf; prkdf = prkdf->next)
560 if (!keygrip_from_prkdf (app, prkdf)
561 && !strcmp (certid, prkdf->keygrip))
563 if (!prkdf || !prkdf->objidlen || !prkdf->objid)
564 return gpg_error (GPG_ERR_NOT_FOUND);
565 objidlen = prkdf->objidlen;
566 objid = xtrymalloc (objidlen);
568 return gpg_error_from_syserror ();
569 memcpy (objid, prkdf->objid, prkdf->objidlen);
571 else /* This is a usual keyref. */
573 if (app->app_local->home_df)
574 snprintf (tmpbuf, sizeof tmpbuf, "P15-%04X.",
575 (unsigned int)(app->app_local->home_df & 0xffff));
577 strcpy (tmpbuf, "P15.");
578 if (strncmp (certid, tmpbuf, strlen (tmpbuf)) )
580 if (!strncmp (certid, "P15.", 4)
581 || (!strncmp (certid, "P15-", 4)
582 && hexdigitp (certid+4)
583 && hexdigitp (certid+5)
584 && hexdigitp (certid+6)
585 && hexdigitp (certid+7)
586 && certid[8] == '.'))
587 return gpg_error (GPG_ERR_NOT_FOUND);
588 return gpg_error (GPG_ERR_INV_ID);
590 certid += strlen (tmpbuf);
591 for (s=certid, objidlen=0; hexdigitp (s); s++, objidlen++)
593 if (*s || !objidlen || (objidlen%2))
594 return gpg_error (GPG_ERR_INV_ID);
596 objid = xtrymalloc (objidlen);
598 return gpg_error_from_syserror ();
599 for (s=certid, i=0; i < objidlen; i++, s+=2)
600 objid[i] = xtoi_2 (s);
604 *r_objidlen = objidlen;
609 /* Find a certificate object by the certificate ID CERTID and store a
610 pointer to it at R_CDF. */
612 cdf_object_from_certid (app_t app, const char *certid, cdf_object_t *r_cdf)
616 unsigned char *objid;
619 err = parse_certid (app, certid, &objid, &objidlen);
623 for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
624 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
627 for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
628 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
631 for (cdf = app->app_local->useful_certificate_info; cdf; cdf = cdf->next)
632 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
636 return gpg_error (GPG_ERR_NOT_FOUND);
642 /* Find a private key object by the key Id string KEYIDSTR and store a
643 pointer to it at R_PRKDF. */
645 prkdf_object_from_keyidstr (app_t app, const char *keyidstr,
646 prkdf_object_t *r_prkdf)
650 unsigned char *objid;
651 prkdf_object_t prkdf;
653 err = parse_certid (app, keyidstr, &objid, &objidlen);
657 for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
658 if (prkdf->objidlen == objidlen && !memcmp (prkdf->objid, objid, objidlen))
662 return gpg_error (GPG_ERR_NOT_FOUND);
670 /* Read and parse the Object Directory File and store away the
671 pointers. ODF_FID shall contain the FID of the ODF.
673 Example of such a file:
675 A0 06 30 04 04 02 60 34 = Private Keys
676 A4 06 30 04 04 02 60 35 = Certificates
677 A5 06 30 04 04 02 60 36 = Trusted Certificates
678 A7 06 30 04 04 02 60 37 = Data Objects
679 A8 06 30 04 04 02 60 38 = Auth Objects
681 These are all PathOrObjects using the path CHOICE element. The
682 paths are octet strings of length 2. Using this Path CHOICE
683 element is recommended, so we only implement that for now.
686 read_ef_odf (app_t app, unsigned short odf_fid)
689 unsigned char *buffer, *p;
691 unsigned short value;
693 unsigned short home_df = 0;
695 err = select_and_read_binary (app->slot, odf_fid, "ODF", &buffer, &buflen);
701 log_error ("p15: error: ODF too short\n");
703 return gpg_error (GPG_ERR_INV_OBJ);
706 home_df = app->app_local->home_df;
708 while (buflen && *p && *p != 0xff)
711 && (p[0] & 0xf0) == 0xA0
712 && !memcmp (p+1, "\x06\x30\x04\x04\x02", 5) )
716 else if ( buflen >= 12
717 && (p[0] & 0xf0) == 0xA0
718 && !memcmp (p+1, "\x0a\x30\x08\x04\x06\x3F\x00", 7)
719 && (!home_df || home_df == ((p[8]<<8)|p[9])) )
721 /* If we do not know the home DF, we take it from the first
722 * ODF object. Here are sample values:
723 * a0 0a 30 08 0406 3f00 5015 4401
724 * a1 0a 30 08 0406 3f00 5015 4411
725 * a4 0a 30 08 0406 3f00 5015 4441
726 * a5 0a 30 08 0406 3f00 5015 4451
727 * a8 0a 30 08 0406 3f00 5015 4481
731 home_df = ((p[8]<<8)|p[9]);
732 app->app_local->home_df = home_df;
733 log_info ("p15: application directory detected as 0x%04hX\n",
735 /* We assume that direct path selection is possible. */
736 app->app_local->direct_path_selection = 1;
739 /* We only allow a full path if all files are at the same
740 level and below the home directory. To extend this we
741 would need to make use of new data type capable of
742 keeping a full path. */
747 log_printhex (p, buflen, "p15: ODF format not supported:");
749 return gpg_error (GPG_ERR_INV_OBJ);
751 switch ((p[0] & 0x0f))
753 case 0: value = app->app_local->odf.private_keys; break;
754 case 1: value = app->app_local->odf.public_keys; break;
755 case 2: value = app->app_local->odf.trusted_public_keys; break;
756 case 3: value = app->app_local->odf.secret_keys; break;
757 case 4: value = app->app_local->odf.certificates; break;
758 case 5: value = app->app_local->odf.trusted_certificates; break;
759 case 6: value = app->app_local->odf.useful_certificates; break;
760 case 7: value = app->app_local->odf.data_objects; break;
761 case 8: value = app->app_local->odf.auth_objects; break;
762 default: value = 0; break;
766 log_error ("p15: duplicate object type %d in ODF ignored\n",
770 value = ((p[offset] << 8) | p[offset+1]);
771 switch ((p[0] & 0x0f))
773 case 0: app->app_local->odf.private_keys = value; break;
774 case 1: app->app_local->odf.public_keys = value; break;
775 case 2: app->app_local->odf.trusted_public_keys = value; break;
776 case 3: app->app_local->odf.secret_keys = value; break;
777 case 4: app->app_local->odf.certificates = value; break;
778 case 5: app->app_local->odf.trusted_certificates = value; break;
779 case 6: app->app_local->odf.useful_certificates = value; break;
780 case 7: app->app_local->odf.data_objects = value; break;
781 case 8: app->app_local->odf.auth_objects = value; break;
783 log_error ("p15: unknown object type %d in ODF ignored\n",
796 /* Print a warning if non-null garbage is left over. */
797 for (n=0; n < buflen && !p[n]; n++)
801 log_info ("p15: warning: garbage detected at end of ODF: ");
802 log_printhex (p, buflen, "");
811 /* Parse the BIT STRING with the keyUsageFlags from the
812 CommonKeyAttributes. */
814 parse_keyusage_flags (const unsigned char *der, size_t derlen,
815 keyusage_flags_t *usageflags)
817 unsigned int bits, mask;
820 memset (usageflags, 0, sizeof *usageflags);
822 return gpg_error (GPG_ERR_INV_OBJ);
824 unused = *der++; derlen--;
825 if ((!derlen && unused) || unused/8 > derlen)
826 return gpg_error (GPG_ERR_ENCODING_PROBLEM);
827 full = derlen - (unused+7)/8;
830 for (i=1; unused; i <<= 1, unused--)
836 bits = *der++; derlen--;
847 if ((bits & 0x80)) usageflags->encrypt = 1;
848 if ((bits & 0x40)) usageflags->decrypt = 1;
849 if ((bits & 0x20)) usageflags->sign = 1;
850 if ((bits & 0x10)) usageflags->sign_recover = 1;
851 if ((bits & 0x08)) usageflags->wrap = 1;
852 if ((bits & 0x04)) usageflags->unwrap = 1;
853 if ((bits & 0x02)) usageflags->verify = 1;
854 if ((bits & 0x01)) usageflags->verify_recover = 1;
859 bits = *der++; derlen--;
869 if ((bits & 0x80)) usageflags->derive = 1;
870 if ((bits & 0x40)) usageflags->non_repudiation = 1;
875 /* Read and parse the Private Key Directory Files. */
879 30 33 30 11 0C 08 53 4B 2E 43 48 2E 44 53 03 02 030...SK.CH.DS..
880 06 80 04 01 07 30 0C 04 01 01 03 03 06 00 40 02 .....0........@.
881 02 00 50 A1 10 30 0E 30 08 04 06 3F 00 40 16 00 ..P..0.0...?.@..
882 50 02 02 04 00 30 33 30 11 0C 08 53 4B 2E 43 48 P....030...SK.CH
883 2E 4B 45 03 02 06 80 04 01 0A 30 0C 04 01 0C 03 .KE.......0.....
884 03 06 44 00 02 02 00 52 A1 10 30 0E 30 08 04 06 ..D....R..0.0...
885 3F 00 40 16 00 52 02 02 04 00 30 34 30 12 0C 09 ?.@..R....040...
886 53 4B 2E 43 48 2E 41 55 54 03 02 06 80 04 01 0A SK.CH.AUT.......
887 30 0C 04 01 0D 03 03 06 20 00 02 02 00 51 A1 10 0....... ....Q..
888 30 0E 30 08 04 06 3F 00 40 16 00 51 02 02 04 00 0.0...?.@..Q....
889 30 37 30 15 0C 0C 53 4B 2E 43 48 2E 44 53 2D 53 070...SK.CH.DS-S
890 50 58 03 02 06 80 04 01 0A 30 0C 04 01 02 03 03 PX.......0......
891 06 20 00 02 02 00 53 A1 10 30 0E 30 08 04 06 3F . ....S..0.0...?
892 00 40 16 00 53 02 02 04 00 00 00 00 00 00 00 00 .@..S...........
893 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
894 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
897 2 30 17: SEQUENCE { -- commonObjectAttributes
898 4 0C 8: UTF8String 'SK.CH.DS'
899 14 03 2: BIT STRING 6 unused bits
901 18 04 1: OCTET STRING --authid
904 21 30 12: SEQUENCE { -- commonKeyAttributes
905 23 04 1: OCTET STRING
907 26 03 3: BIT STRING 6 unused bits
908 : '1000000000'B (bit 9)
909 31 02 2: INTEGER 80 -- keyReference (optional)
911 35 A1 16: [1] { -- keyAttributes
912 37 30 14: SEQUENCE { -- privateRSAKeyAttributes
913 39 30 8: SEQUENCE { -- objectValue
914 41 04 6: OCTET STRING --path
917 49 02 2: INTEGER 1024 -- modulus
925 read_ef_prkdf (app_t app, unsigned short fid, prkdf_object_t *result)
928 unsigned char *buffer = NULL;
930 const unsigned char *p;
931 size_t n, objlen, hdrlen;
932 int class, tag, constructed, ndef;
933 prkdf_object_t prkdflist = NULL;
937 return gpg_error (GPG_ERR_NO_DATA); /* No private keys. */
939 err = select_and_read_binary (app->slot, fid, "PrKDF", &buffer, &buflen);
946 /* FIXME: This shares a LOT of code with read_ef_cdf! */
948 /* Loop over the records. We stop as soon as we detect a new record
949 starting with 0x00 or 0xff as these values are commonly used to
950 pad data blocks and are no valid ASN.1 encoding. */
951 while (n && *p && *p != 0xff)
953 const unsigned char *pp;
956 const char *errstr = NULL;
957 prkdf_object_t prkdf = NULL;
959 const unsigned char *objid;
961 const unsigned char *authid = NULL;
962 size_t authidlen = 0;
963 keyusage_flags_t usageflags;
964 unsigned long key_reference = 0;
965 int key_reference_valid = 0;
968 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
969 &ndef, &objlen, &hdrlen);
970 if (!err && (objlen > n || tag != TAG_SEQUENCE))
971 err = gpg_error (GPG_ERR_INV_OBJ);
974 log_error ("p15: error parsing PrKDF record: %s\n",
983 /* Parse the commonObjectAttributes. */
985 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
986 &ndef, &objlen, &hdrlen);
987 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
988 err = gpg_error (GPG_ERR_INV_OBJ);
992 const unsigned char *ppp = pp;
998 /* Search the optional AuthId. We need to skip the optional
999 Label (UTF8STRING) and the optional CommonObjectFlags
1002 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1003 &ndef, &objlen, &hdrlen);
1004 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1005 err = gpg_error (GPG_ERR_INV_OBJ);
1006 if (gpg_err_code (err) == GPG_ERR_EOF)
1010 if (tag == TAG_UTF8_STRING)
1012 ppp += objlen; /* Skip the Label. */
1016 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1017 &ndef, &objlen, &hdrlen);
1018 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1019 err = gpg_error (GPG_ERR_INV_OBJ);
1020 if (gpg_err_code (err) == GPG_ERR_EOF)
1025 if (tag == TAG_BIT_STRING)
1027 ppp += objlen; /* Skip the CommonObjectFlags. */
1031 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1032 &ndef, &objlen, &hdrlen);
1033 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1034 err = gpg_error (GPG_ERR_INV_OBJ);
1035 if (gpg_err_code (err) == GPG_ERR_EOF)
1040 if (tag == TAG_OCTET_STRING && objlen)
1049 /* Parse the commonKeyAttributes. */
1051 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1052 &ndef, &objlen, &hdrlen);
1053 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1054 err = gpg_error (GPG_ERR_INV_OBJ);
1058 const unsigned char *ppp = pp;
1059 size_t nnn = objlen;
1066 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1067 &ndef, &objlen, &hdrlen);
1068 if (!err && (objlen > nnn
1069 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
1070 err = gpg_error (GPG_ERR_INV_OBJ);
1078 /* Get the KeyUsageFlags. */
1080 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1081 &ndef, &objlen, &hdrlen);
1082 if (!err && (objlen > nnn
1083 || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
1084 err = gpg_error (GPG_ERR_INV_OBJ);
1087 err = parse_keyusage_flags (ppp, objlen, &usageflags);
1093 /* Find the keyReference */
1095 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1096 &ndef, &objlen, &hdrlen);
1097 if (gpg_err_code (err) == GPG_ERR_EOF)
1099 if (!err && objlen > nnn)
1100 err = gpg_error (GPG_ERR_INV_OBJ);
1103 if (class == CLASS_UNIVERSAL && tag == TAG_BOOLEAN)
1105 /* Skip the native element. */
1109 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1110 &ndef, &objlen, &hdrlen);
1111 if (gpg_err_code (err) == GPG_ERR_EOF)
1113 if (!err && objlen > nnn)
1114 err = gpg_error (GPG_ERR_INV_OBJ);
1118 if (class == CLASS_UNIVERSAL && tag == TAG_BIT_STRING)
1120 /* Skip the accessFlags. */
1124 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1125 &ndef, &objlen, &hdrlen);
1126 if (gpg_err_code (err) == GPG_ERR_EOF)
1128 if (!err && objlen > nnn)
1129 err = gpg_error (GPG_ERR_INV_OBJ);
1133 if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
1135 /* Yep, this is the keyReference. */
1136 for (ul=0; objlen; objlen--)
1139 ul |= (*ppp++) & 0xff;
1143 key_reference_valid = 1;
1151 /* Skip subClassAttributes. */
1153 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1154 &ndef, &objlen, &hdrlen);
1155 if (!err && objlen > nn)
1156 err = gpg_error (GPG_ERR_INV_OBJ);
1159 if (class == CLASS_CONTEXT && tag == 0)
1165 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1166 &ndef, &objlen, &hdrlen);
1168 /* Parse the keyAttributes. */
1169 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1170 err = gpg_error (GPG_ERR_INV_OBJ);
1176 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1177 &ndef, &objlen, &hdrlen);
1178 if (!err && objlen > nn)
1179 err = gpg_error (GPG_ERR_INV_OBJ);
1182 if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
1184 else if (class == CLASS_CONTEXT)
1188 case 0: errstr = "EC key objects are not supported"; break;
1189 case 1: errstr = "DH key objects are not supported"; break;
1190 case 2: errstr = "DSA key objects are not supported"; break;
1191 case 3: errstr = "KEA key objects are not supported"; break;
1192 default: errstr = "unknown privateKeyObject"; break;
1198 err = gpg_error (GPG_ERR_INV_OBJ);
1204 /* Check that the reference is a Path object. */
1206 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1207 &ndef, &objlen, &hdrlen);
1208 if (!err && objlen > nn)
1209 err = gpg_error (GPG_ERR_INV_OBJ);
1212 if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
1214 errstr = "unsupported reference type";
1219 /* Parse the Path object. */
1221 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1222 &ndef, &objlen, &hdrlen);
1223 if (!err && objlen > nn)
1224 err = gpg_error (GPG_ERR_INV_OBJ);
1228 /* Make sure that the next element is a non zero path and of
1229 even length (FID are two bytes each). */
1230 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
1231 || !objlen || (objlen & 1) )
1233 errstr = "invalid path reference";
1236 /* Create a new PrKDF list item. */
1237 prkdf = xtrycalloc (1, (sizeof *prkdf
1238 - sizeof(unsigned short)
1239 + objlen/2 * sizeof(unsigned short)));
1242 err = gpg_error_from_syserror ();
1245 prkdf->objidlen = objidlen;
1246 prkdf->objid = xtrymalloc (objidlen);
1249 err = gpg_error_from_syserror ();
1253 memcpy (prkdf->objid, objid, objidlen);
1256 prkdf->authidlen = authidlen;
1257 prkdf->authid = xtrymalloc (authidlen);
1260 err = gpg_error_from_syserror ();
1261 xfree (prkdf->objid);
1265 memcpy (prkdf->authid, authid, authidlen);
1268 prkdf->pathlen = objlen/2;
1269 for (i=0; i < prkdf->pathlen; i++, pp += 2, nn -= 2)
1270 prkdf->path[i] = ((pp[0] << 8) | pp[1]);
1272 prkdf->usageflags = usageflags;
1273 prkdf->key_reference = key_reference;
1274 prkdf->key_reference_valid = key_reference_valid;
1278 /* An index and length follows. */
1279 prkdf->have_off = 1;
1281 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1282 &ndef, &objlen, &hdrlen);
1283 if (!err && (objlen > nn
1284 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1285 err = gpg_error (GPG_ERR_INV_OBJ);
1289 for (ul=0; objlen; objlen--)
1292 ul |= (*pp++) & 0xff;
1298 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1299 &ndef, &objlen, &hdrlen);
1300 if (!err && (objlen > nn
1301 || class != CLASS_CONTEXT || tag != 0))
1302 err = gpg_error (GPG_ERR_INV_OBJ);
1306 for (ul=0; objlen; objlen--)
1309 ul |= (*pp++) & 0xff;
1318 log_info ("p15: PrKDF %04hX: id=", fid);
1319 for (i=0; i < prkdf->objidlen; i++)
1320 log_printf ("%02X", prkdf->objid[i]);
1321 log_printf (" path=");
1322 for (i=0; i < prkdf->pathlen; i++)
1323 log_printf ("%s%04hX", i?"/":"",prkdf->path[i]);
1324 if (prkdf->have_off)
1325 log_printf ("[%lu/%lu]", prkdf->off, prkdf->len);
1328 log_printf (" authid=");
1329 for (i=0; i < prkdf->authidlen; i++)
1330 log_printf ("%02X", prkdf->authid[i]);
1332 if (prkdf->key_reference_valid)
1333 log_printf (" keyref=0x%02lX", prkdf->key_reference);
1334 log_info ("p15: usage=");
1336 if (prkdf->usageflags.encrypt) log_printf ("%sencrypt", s), s = ",";
1337 if (prkdf->usageflags.decrypt) log_printf ("%sdecrypt", s), s = ",";
1338 if (prkdf->usageflags.sign ) log_printf ("%ssign", s), s = ",";
1339 if (prkdf->usageflags.sign_recover)
1340 log_printf ("%ssign_recover", s), s = ",";
1341 if (prkdf->usageflags.wrap ) log_printf ("%swrap", s), s = ",";
1342 if (prkdf->usageflags.unwrap ) log_printf ("%sunwrap", s), s = ",";
1343 if (prkdf->usageflags.verify ) log_printf ("%sverify", s), s = ",";
1344 if (prkdf->usageflags.verify_recover)
1345 log_printf ("%sverify_recover", s), s = ",";
1346 if (prkdf->usageflags.derive ) log_printf ("%sderive", s), s = ",";
1347 if (prkdf->usageflags.non_repudiation)
1348 log_printf ("%snon_repudiation", s), s = ",";
1352 /* Put it into the list. */
1353 prkdf->next = prkdflist;
1356 continue; /* Ready. */
1359 log_error ("p15: error parsing PrKDF record (%d): %s - skipped\n",
1360 where, errstr? errstr : gpg_strerror (err));
1363 xfree (prkdf->objid);
1364 xfree (prkdf->authid);
1368 } /* End looping over all records. */
1373 release_prkdflist (prkdflist);
1375 *result = prkdflist;
1380 /* Read and parse the Certificate Directory Files identified by FID.
1381 On success a newlist of CDF object gets stored at RESULT and the
1382 caller is then responsible of releasing this list. On error a
1383 error code is returned and RESULT won't get changed. */
1385 read_ef_cdf (app_t app, unsigned short fid, cdf_object_t *result)
1388 unsigned char *buffer = NULL;
1390 const unsigned char *p;
1391 size_t n, objlen, hdrlen;
1392 int class, tag, constructed, ndef;
1393 cdf_object_t cdflist = NULL;
1397 return gpg_error (GPG_ERR_NO_DATA); /* No certificates. */
1399 err = select_and_read_binary (app->slot, fid, "CDF", &buffer, &buflen);
1406 /* Loop over the records. We stop as soon as we detect a new record
1407 starting with 0x00 or 0xff as these values are commonly used to
1408 pad data blocks and are no valid ASN.1 encoding. */
1409 while (n && *p && *p != 0xff)
1411 const unsigned char *pp;
1414 const char *errstr = NULL;
1415 cdf_object_t cdf = NULL;
1417 const unsigned char *objid;
1420 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1421 &ndef, &objlen, &hdrlen);
1422 if (!err && (objlen > n || tag != TAG_SEQUENCE))
1423 err = gpg_error (GPG_ERR_INV_OBJ);
1426 log_error ("p15: error parsing CDF record: %s\n", gpg_strerror (err));
1434 /* Skip the commonObjectAttributes. */
1436 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1437 &ndef, &objlen, &hdrlen);
1438 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1439 err = gpg_error (GPG_ERR_INV_OBJ);
1445 /* Parse the commonCertificateAttributes. */
1447 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1448 &ndef, &objlen, &hdrlen);
1449 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1450 err = gpg_error (GPG_ERR_INV_OBJ);
1454 const unsigned char *ppp = pp;
1455 size_t nnn = objlen;
1462 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1463 &ndef, &objlen, &hdrlen);
1464 if (!err && (objlen > nnn
1465 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
1466 err = gpg_error (GPG_ERR_INV_OBJ);
1473 /* Parse the certAttribute. */
1475 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1476 &ndef, &objlen, &hdrlen);
1477 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1478 err = gpg_error (GPG_ERR_INV_OBJ);
1484 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1485 &ndef, &objlen, &hdrlen);
1486 if (!err && (objlen > nn
1487 || class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE))
1488 err = gpg_error (GPG_ERR_INV_OBJ);
1493 /* Check that the reference is a Path object. */
1495 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1496 &ndef, &objlen, &hdrlen);
1497 if (!err && objlen > nn)
1498 err = gpg_error (GPG_ERR_INV_OBJ);
1501 if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
1503 errstr = "unsupported reference type";
1508 /* Parse the Path object. */
1510 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1511 &ndef, &objlen, &hdrlen);
1512 if (!err && objlen > nn)
1513 err = gpg_error (GPG_ERR_INV_OBJ);
1517 /* Make sure that the next element is a non zero path and of
1518 even length (FID are two bytes each). */
1519 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
1520 || !objlen || (objlen & 1) )
1522 errstr = "invalid path reference";
1525 /* Create a new CDF list item. */
1526 cdf = xtrycalloc (1, (sizeof *cdf
1527 - sizeof(unsigned short)
1528 + objlen/2 * sizeof(unsigned short)));
1531 err = gpg_error_from_syserror ();
1534 cdf->objidlen = objidlen;
1535 cdf->objid = xtrymalloc (objidlen);
1538 err = gpg_error_from_syserror ();
1542 memcpy (cdf->objid, objid, objidlen);
1544 cdf->pathlen = objlen/2;
1545 for (i=0; i < cdf->pathlen; i++, pp += 2, nn -= 2)
1546 cdf->path[i] = ((pp[0] << 8) | pp[1]);
1550 /* An index and length follows. */
1553 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1554 &ndef, &objlen, &hdrlen);
1555 if (!err && (objlen > nn
1556 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1557 err = gpg_error (GPG_ERR_INV_OBJ);
1561 for (ul=0; objlen; objlen--)
1564 ul |= (*pp++) & 0xff;
1570 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1571 &ndef, &objlen, &hdrlen);
1572 if (!err && (objlen > nn
1573 || class != CLASS_CONTEXT || tag != 0))
1574 err = gpg_error (GPG_ERR_INV_OBJ);
1578 for (ul=0; objlen; objlen--)
1581 ul |= (*pp++) & 0xff;
1589 log_info ("p15: CDF %04hX: id=", fid);
1590 for (i=0; i < cdf->objidlen; i++)
1591 log_printf ("%02X", cdf->objid[i]);
1592 log_printf (" path=");
1593 for (i=0; i < cdf->pathlen; i++)
1594 log_printf ("%s%04hX", i?"/":"", cdf->path[i]);
1596 log_printf ("[%lu/%lu]", cdf->off, cdf->len);
1600 /* Put it into the list. */
1601 cdf->next = cdflist;
1604 continue; /* Ready. */
1607 log_error ("p15: error parsing CDF record (%d): %s - skipped\n",
1608 where, errstr? errstr : gpg_strerror (err));
1611 } /* End looping over all records. */
1616 release_cdflist (cdflist);
1625 SEQUENCE { -- CommonObjectAttributes
1626 UTF8String 'specific PIN for DS'
1627 BIT STRING 0 unused bits
1630 SEQUENCE { -- CommonAuthenticationObjectAttributes
1635 [1] { -- typeAttributes
1636 SEQUENCE { -- PinAttributes
1637 BIT STRING 0 unused bits
1638 '0000100000110010'B -- local,initialized,needs-padding
1640 ENUMERATED 1 -- ascii-numeric
1641 INTEGER 6 -- minLength
1642 INTEGER 6 -- storedLength
1643 INTEGER 8 -- maxLength
1646 GeneralizedTime 19/04/2002 12:12 GMT -- lastPinChange
1649 3F 00 40 16 -- path to DF of PIN
1656 /* Read and parse an Authentication Object Directory File identified
1657 by FID. On success a newlist of AODF objects gets stored at RESULT
1658 and the caller is responsible of releasing this list. On error a
1659 error code is returned and RESULT won't get changed. */
1661 read_ef_aodf (app_t app, unsigned short fid, aodf_object_t *result)
1664 unsigned char *buffer = NULL;
1666 const unsigned char *p;
1667 size_t n, objlen, hdrlen;
1668 int class, tag, constructed, ndef;
1669 aodf_object_t aodflist = NULL;
1673 return gpg_error (GPG_ERR_NO_DATA); /* No authentication objects. */
1675 err = select_and_read_binary (app->slot, fid, "AODF", &buffer, &buflen);
1682 /* FIXME: This shares a LOT of code with read_ef_prkdf! */
1684 /* Loop over the records. We stop as soon as we detect a new record
1685 starting with 0x00 or 0xff as these values are commonly used to
1686 pad data blocks and are no valid ASN.1 encoding. */
1687 while (n && *p && *p != 0xff)
1689 const unsigned char *pp;
1692 const char *errstr = NULL;
1693 aodf_object_t aodf = NULL;
1697 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1698 &ndef, &objlen, &hdrlen);
1699 if (!err && (objlen > n || tag != TAG_SEQUENCE))
1700 err = gpg_error (GPG_ERR_INV_OBJ);
1703 log_error ("p15: error parsing AODF record: %s\n",
1704 gpg_strerror (err));
1712 /* Allocate memory for a new AODF list item. */
1713 aodf = xtrycalloc (1, sizeof *aodf);
1718 /* Parse the commonObjectAttributes. */
1720 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1721 &ndef, &objlen, &hdrlen);
1722 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1723 err = gpg_error (GPG_ERR_INV_OBJ);
1727 const unsigned char *ppp = pp;
1728 size_t nnn = objlen;
1733 /* Search the optional AuthId. We need to skip the optional
1734 Label (UTF8STRING) and the optional CommonObjectFlags
1737 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1738 &ndef, &objlen, &hdrlen);
1739 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1740 err = gpg_error (GPG_ERR_INV_OBJ);
1741 if (gpg_err_code (err) == GPG_ERR_EOF)
1745 if (tag == TAG_UTF8_STRING)
1747 ppp += objlen; /* Skip the Label. */
1751 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1752 &ndef, &objlen, &hdrlen);
1753 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1754 err = gpg_error (GPG_ERR_INV_OBJ);
1755 if (gpg_err_code (err) == GPG_ERR_EOF)
1760 if (tag == TAG_BIT_STRING)
1762 ppp += objlen; /* Skip the CommonObjectFlags. */
1766 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1767 &ndef, &objlen, &hdrlen);
1768 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1769 err = gpg_error (GPG_ERR_INV_OBJ);
1770 if (gpg_err_code (err) == GPG_ERR_EOF)
1775 if (tag == TAG_OCTET_STRING && objlen)
1777 aodf->authidlen = objlen;
1778 aodf->authid = xtrymalloc (objlen);
1781 memcpy (aodf->authid, ppp, objlen);
1787 /* Parse the CommonAuthenticationObjectAttributes. */
1789 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1790 &ndef, &objlen, &hdrlen);
1791 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
1792 err = gpg_error (GPG_ERR_INV_OBJ);
1796 const unsigned char *ppp = pp;
1797 size_t nnn = objlen;
1804 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1805 &ndef, &objlen, &hdrlen);
1806 if (!err && (objlen > nnn
1807 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
1808 err = gpg_error (GPG_ERR_INV_OBJ);
1812 aodf->objidlen = objlen;
1813 aodf->objid = xtrymalloc (objlen);
1816 memcpy (aodf->objid, ppp, objlen);
1819 /* Parse the typeAttributes. */
1821 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1822 &ndef, &objlen, &hdrlen);
1823 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1824 err = gpg_error (GPG_ERR_INV_OBJ);
1830 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1831 &ndef, &objlen, &hdrlen);
1832 if (!err && objlen > nn)
1833 err = gpg_error (GPG_ERR_INV_OBJ);
1836 if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
1837 ; /* PinAttributes */
1838 else if (class == CLASS_CONTEXT)
1842 case 0: errstr = "biometric auth types are not supported"; break;
1843 case 1: errstr = "authKey auth types are not supported"; break;
1844 case 2: errstr = "external auth type are not supported"; break;
1845 default: errstr = "unknown privateKeyObject"; break;
1851 err = gpg_error (GPG_ERR_INV_OBJ);
1859 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1860 &ndef, &objlen, &hdrlen);
1861 if (!err && (objlen > nn || !objlen
1862 || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
1863 err = gpg_error (GPG_ERR_INV_OBJ);
1868 unsigned int bits, mask;
1871 unused = *pp++; nn--; objlen--;
1872 if ((!objlen && unused) || unused/8 > objlen)
1874 err = gpg_error (GPG_ERR_ENCODING_PROBLEM);
1877 full = objlen - (unused+7)/8;
1880 for (i=1; unused; i <<= 1, unused--)
1883 /* The first octet */
1887 bits = *pp++; nn--; objlen--;
1896 if ((bits & 0x80)) /* ASN.1 bit 0. */
1897 aodf->pinflags.case_sensitive = 1;
1898 if ((bits & 0x40)) /* ASN.1 bit 1. */
1899 aodf->pinflags.local = 1;
1901 aodf->pinflags.change_disabled = 1;
1903 aodf->pinflags.unblock_disabled = 1;
1905 aodf->pinflags.initialized = 1;
1907 aodf->pinflags.needs_padding = 1;
1909 aodf->pinflags.unblocking_pin = 1;
1911 aodf->pinflags.so_pin = 1;
1912 /* The second octet. */
1916 bits = *pp++; nn--; objlen--;
1925 aodf->pinflags.disable_allowed = 1;
1927 aodf->pinflags.integrity_protected = 1;
1929 aodf->pinflags.confidentiality_protected = 1;
1931 aodf->pinflags.exchange_ref_data = 1;
1932 /* Skip remaining bits. */
1940 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1941 &ndef, &objlen, &hdrlen);
1942 if (!err && (objlen > nn
1943 || class != CLASS_UNIVERSAL || tag != TAG_ENUMERATED))
1944 err = gpg_error (GPG_ERR_INV_OBJ);
1945 if (!err && objlen > sizeof (ul))
1946 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1950 for (ul=0; objlen; objlen--)
1953 ul |= (*pp++) & 0xff;
1961 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1962 &ndef, &objlen, &hdrlen);
1963 if (!err && (objlen > nn
1964 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1965 err = gpg_error (GPG_ERR_INV_OBJ);
1966 if (!err && objlen > sizeof (ul))
1967 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1970 for (ul=0; objlen; objlen--)
1973 ul |= (*pp++) & 0xff;
1976 aodf->min_length = ul;
1981 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1982 &ndef, &objlen, &hdrlen);
1983 if (!err && (objlen > nn
1984 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1985 err = gpg_error (GPG_ERR_INV_OBJ);
1986 if (!err && objlen > sizeof (ul))
1987 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
1990 for (ul=0; objlen; objlen--)
1993 ul |= (*pp++) & 0xff;
1996 aodf->stored_length = ul;
1998 /* optional maxLength */
2000 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2001 &ndef, &objlen, &hdrlen);
2002 if (gpg_err_code (err) == GPG_ERR_EOF)
2004 if (!err && objlen > nn)
2005 err = gpg_error (GPG_ERR_INV_OBJ);
2008 if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
2010 if (objlen > sizeof (ul))
2012 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
2015 for (ul=0; objlen; objlen--)
2018 ul |= (*pp++) & 0xff;
2021 aodf->max_length = ul;
2022 aodf->max_length_valid = 1;
2025 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2026 &ndef, &objlen, &hdrlen);
2027 if (gpg_err_code (err) == GPG_ERR_EOF)
2029 if (!err && objlen > nn)
2030 err = gpg_error (GPG_ERR_INV_OBJ);
2035 /* Optional pinReference. */
2036 if (class == CLASS_CONTEXT && tag == 0)
2038 if (objlen > sizeof (ul))
2040 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
2043 for (ul=0; objlen; objlen--)
2046 ul |= (*pp++) & 0xff;
2049 aodf->pin_reference = ul;
2050 aodf->pin_reference_valid = 1;
2053 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2054 &ndef, &objlen, &hdrlen);
2055 if (gpg_err_code (err) == GPG_ERR_EOF)
2057 if (!err && objlen > nn)
2058 err = gpg_error (GPG_ERR_INV_OBJ);
2063 /* Optional padChar. */
2064 if (class == CLASS_UNIVERSAL && tag == TAG_OCTET_STRING)
2068 errstr = "padChar is not of size(1)";
2071 aodf->pad_char = *pp++; nn--;
2072 aodf->pad_char_valid = 1;
2075 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2076 &ndef, &objlen, &hdrlen);
2077 if (gpg_err_code (err) == GPG_ERR_EOF)
2079 if (!err && objlen > nn)
2080 err = gpg_error (GPG_ERR_INV_OBJ);
2085 /* Skip optional lastPinChange. */
2086 if (class == CLASS_UNIVERSAL && tag == TAG_GENERALIZED_TIME)
2092 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2093 &ndef, &objlen, &hdrlen);
2094 if (gpg_err_code (err) == GPG_ERR_EOF)
2096 if (!err && objlen > nn)
2097 err = gpg_error (GPG_ERR_INV_OBJ);
2102 /* Optional Path object. */
2103 if (class == CLASS_UNIVERSAL || tag == TAG_SEQUENCE)
2105 const unsigned char *ppp = pp;
2106 size_t nnn = objlen;
2112 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
2113 &ndef, &objlen, &hdrlen);
2114 if (!err && objlen > nnn)
2115 err = gpg_error (GPG_ERR_INV_OBJ);
2119 /* Make sure that the next element is a non zero FID and of
2120 even length (FID are two bytes each). */
2121 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
2122 || !objlen || (objlen & 1) )
2124 errstr = "invalid path reference";
2128 aodf->pathlen = objlen/2;
2129 aodf->path = xtrymalloc (aodf->pathlen);
2132 for (i=0; i < aodf->pathlen; i++, ppp += 2, nnn -= 2)
2133 aodf->path[i] = ((ppp[0] << 8) | ppp[1]);
2137 /* An index and length follows. */
2140 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
2141 &ndef, &objlen, &hdrlen);
2142 if (!err && (objlen > nnn
2143 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
2144 err = gpg_error (GPG_ERR_INV_OBJ);
2148 for (ul=0; objlen; objlen--)
2151 ul |= (*ppp++) & 0xff;
2157 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
2158 &ndef, &objlen, &hdrlen);
2159 if (!err && (objlen > nnn
2160 || class != CLASS_CONTEXT || tag != 0))
2161 err = gpg_error (GPG_ERR_INV_OBJ);
2165 for (ul=0; objlen; objlen--)
2168 ul |= (*ppp++) & 0xff;
2175 /* Igonore further objects which might be there due to future
2176 extensions of pkcs#15. */
2181 log_info ("p15: AODF %04hX: id=", fid);
2182 for (i=0; i < aodf->objidlen; i++)
2183 log_printf ("%02X", aodf->objid[i]);
2186 log_printf (" authid=");
2187 for (i=0; i < aodf->authidlen; i++)
2188 log_printf ("%02X", aodf->authid[i]);
2190 if (aodf->pin_reference_valid)
2191 log_printf (" pinref=0x%02lX", aodf->pin_reference);
2194 log_printf (" path=");
2195 for (i=0; i < aodf->pathlen; i++)
2196 log_printf ("%s%04hX", i?"/":"",aodf->path[i]);
2198 log_printf ("[%lu/%lu]", aodf->off, aodf->len);
2200 log_printf (" min=%lu", aodf->min_length);
2201 log_printf (" stored=%lu", aodf->stored_length);
2202 if (aodf->max_length_valid)
2203 log_printf (" max=%lu", aodf->max_length);
2204 if (aodf->pad_char_valid)
2205 log_printf (" pad=0x%02x", aodf->pad_char);
2207 log_info ("p15: flags=");
2209 if (aodf->pinflags.case_sensitive)
2210 log_printf ("%scase_sensitive", s), s = ",";
2211 if (aodf->pinflags.local)
2212 log_printf ("%slocal", s), s = ",";
2213 if (aodf->pinflags.change_disabled)
2214 log_printf ("%schange_disabled", s), s = ",";
2215 if (aodf->pinflags.unblock_disabled)
2216 log_printf ("%sunblock_disabled", s), s = ",";
2217 if (aodf->pinflags.initialized)
2218 log_printf ("%sinitialized", s), s = ",";
2219 if (aodf->pinflags.needs_padding)
2220 log_printf ("%sneeds_padding", s), s = ",";
2221 if (aodf->pinflags.unblocking_pin)
2222 log_printf ("%sunblocking_pin", s), s = ",";
2223 if (aodf->pinflags.so_pin)
2224 log_printf ("%sso_pin", s), s = ",";
2225 if (aodf->pinflags.disable_allowed)
2226 log_printf ("%sdisable_allowed", s), s = ",";
2227 if (aodf->pinflags.integrity_protected)
2228 log_printf ("%sintegrity_protected", s), s = ",";
2229 if (aodf->pinflags.confidentiality_protected)
2230 log_printf ("%sconfidentiality_protected", s), s = ",";
2231 if (aodf->pinflags.exchange_ref_data)
2232 log_printf ("%sexchange_ref_data", s), s = ",";
2235 switch (aodf->pintype)
2237 case PIN_TYPE_BCD: s = "bcd"; break;
2238 case PIN_TYPE_ASCII_NUMERIC: s = "ascii-numeric"; break;
2239 case PIN_TYPE_UTF8: s = "utf8"; break;
2240 case PIN_TYPE_HALF_NIBBLE_BCD: s = "half-nibble-bcd"; break;
2241 case PIN_TYPE_ISO9564_1: s = "iso9564-1"; break;
2243 sprintf (numbuf, "%lu", (unsigned long)aodf->pintype);
2246 log_printf (" type=%s", s);
2251 /* Put it into the list. */
2252 aodf->next = aodflist;
2255 continue; /* Ready. */
2258 err = gpg_error_from_syserror ();
2259 release_aodf_object (aodf);
2263 log_error ("p15: error parsing AODF record (%d): %s - skipped\n",
2264 where, errstr? errstr : gpg_strerror (err));
2266 release_aodf_object (aodf);
2267 } /* End looping over all records. */
2272 release_aodflist (aodflist);
2279 /* Print the BIT STRING with the tokenflags from the TokenInfo. */
2281 print_tokeninfo_tokenflags (const unsigned char *der, size_t derlen)
2283 unsigned int bits, mask;
2284 int i, unused, full;
2289 log_printf (" [invalid object]");
2293 unused = *der++; derlen--;
2294 if ((!derlen && unused) || unused/8 > derlen)
2296 log_printf (" [wrong encoding]");
2299 full = derlen - (unused+7)/8;
2302 for (i=1; unused; i <<= 1, unused--)
2308 bits = *der++; derlen--;
2319 if ((bits & 0x80)) log_printf (" readonly");
2320 if ((bits & 0x40)) log_printf (" loginRequired");
2321 if ((bits & 0x20)) log_printf (" prnGeneration");
2322 if ((bits & 0x10)) log_printf (" eidCompliant");
2323 if ((bits & 0x08)) other = 1;
2324 if ((bits & 0x04)) other = 1;
2325 if ((bits & 0x02)) other = 1;
2326 if ((bits & 0x01)) other = 1;
2333 log_printf (" [unknown]");
2338 /* Read and parse the EF(TokenInfo).
2340 TokenInfo ::= SEQUENCE {
2341 version INTEGER {v1(0)} (v1,...),
2342 serialNumber OCTET STRING,
2343 manufacturerID Label OPTIONAL,
2344 label [0] Label OPTIONAL,
2345 tokenflags TokenFlags,
2346 seInfo SEQUENCE OF SecurityEnvironmentInfo OPTIONAL,
2347 recordInfo [1] RecordInfo OPTIONAL,
2348 supportedAlgorithms [2] SEQUENCE OF AlgorithmInfo OPTIONAL,
2350 issuerId [3] Label OPTIONAL,
2351 holderId [4] Label OPTIONAL,
2352 lastUpdate [5] LastUpdate OPTIONAL,
2353 preferredLanguage PrintableString OPTIONAL -- In accordance with
2355 } (CONSTRAINED BY { -- Each AlgorithmInfo.reference value must be unique --})
2357 TokenFlags ::= BIT STRING {
2367 30 31 02 01 00 04 04 05 45 36 9F 0C 0C 44 2D 54 01......E6...D-T
2368 72 75 73 74 20 47 6D 62 48 80 14 4F 66 66 69 63 rust GmbH..Offic
2369 65 20 69 64 65 6E 74 69 74 79 20 63 61 72 64 03 e identity card.
2370 02 00 40 20 63 61 72 64 03 02 00 40 00 00 00 00 ..@ card...@....
2371 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
2375 5 4: OCTET STRING 05 45 36 9F
2376 11 12: UTF8String 'D-Trust GmbH'
2377 25 20: [0] 'Office identity card'
2379 : '00000010'B (bit 1)
2380 : Error: Spurious zero bits in bitstring.
2388 read_ef_tokeninfo (app_t app)
2391 unsigned char *buffer = NULL;
2393 const unsigned char *p;
2394 size_t n, objlen, hdrlen;
2395 int class, tag, constructed, ndef;
2398 xfree (app->app_local->manufacturer_id);
2399 app->app_local->manufacturer_id = NULL;
2400 app->app_local->card_product = CARD_PRODUCT_UNKNOWN;
2402 err = select_and_read_binary (app->slot, 0x5032, "TokenInfo",
2410 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2411 &ndef, &objlen, &hdrlen);
2412 if (!err && (objlen > n || tag != TAG_SEQUENCE))
2413 err = gpg_error (GPG_ERR_INV_OBJ);
2416 log_error ("p15: error parsing TokenInfo: %s\n", gpg_strerror (err));
2423 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2424 &ndef, &objlen, &hdrlen);
2425 if (!err && (objlen > n || tag != TAG_INTEGER))
2426 err = gpg_error (GPG_ERR_INV_OBJ);
2430 for (ul=0; objlen; objlen--)
2433 ul |= (*p++) & 0xff;
2438 log_error ("p15: invalid version %lu in TokenInfo\n", ul);
2439 err = gpg_error (GPG_ERR_INV_OBJ);
2444 log_info ("p15: TokenInfo:\n");
2446 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2447 &ndef, &objlen, &hdrlen);
2448 if (!err && (objlen > n || tag != TAG_OCTET_STRING || !objlen))
2449 err = gpg_error (GPG_ERR_INV_OBJ);
2453 xfree (app->app_local->serialno);
2454 app->app_local->serialno = xtrymalloc (objlen);
2455 if (!app->app_local->serialno)
2457 err = gpg_error_from_syserror ();
2460 memcpy (app->app_local->serialno, p, objlen);
2461 app->app_local->serialnolen = objlen;
2464 /* (We use a separate log_info to avoid the "DBG:" prefix.) */
2465 log_info ("p15: serialNumber .: ");
2466 log_printhex (p, objlen, "");
2471 /* Is there an optional manufacturerID? */
2472 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2473 &ndef, &objlen, &hdrlen);
2474 if (!err && (objlen > n || !objlen))
2475 err = gpg_error (GPG_ERR_INV_OBJ);
2478 if (class == CLASS_UNIVERSAL && tag == TAG_UTF8_STRING)
2481 log_info ("p15: manufacturerID: %.*s\n", (int)objlen, p);
2482 app->app_local->manufacturer_id = percent_data_escape (0, NULL,
2487 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2488 &ndef, &objlen, &hdrlen);
2489 if (!err && (objlen > n || !objlen))
2490 err = gpg_error (GPG_ERR_INV_OBJ);
2494 if (class == CLASS_CONTEXT && tag == 0)
2497 log_info ("p15: label ........: %.*s\n", (int)objlen, p);
2498 if (objlen > 15 && !memcmp (p, "D-TRUST Card V3", 15)
2499 && app->app_local->card_type == CARD_TYPE_CARDOS_50)
2500 app->app_local->card_product = CARD_PRODUCT_DTRUST;
2505 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2506 &ndef, &objlen, &hdrlen);
2507 if (!err && (objlen > n || !objlen))
2508 err = gpg_error (GPG_ERR_INV_OBJ);
2512 /* The next is the mandatory tokenflags object. */
2513 if (class == CLASS_UNIVERSAL && tag == TAG_BIT_STRING)
2517 log_info ("p15: tokenflags ...:");
2518 print_tokeninfo_tokenflags (p, objlen);
2531 /* Get all the basic information from the pkcs#15 card, check the
2532 structure and initialize our local context. This is used once at
2533 application initialization. */
2535 read_p15_info (app_t app)
2539 if (!read_ef_tokeninfo (app))
2541 /* If we don't have a serial number yet but the TokenInfo provides
2543 if (!app->serialno && app->app_local->serialno)
2545 app->serialno = app->app_local->serialno;
2546 app->serialnolen = app->app_local->serialnolen;
2547 app->app_local->serialno = NULL;
2548 app->app_local->serialnolen = 0;
2549 err = app_munge_serialno (app);
2555 /* Read the ODF so that we know the location of all directory
2557 /* Fixme: We might need to get a non-standard ODF FID from TokenInfo. */
2558 err = read_ef_odf (app, 0x5031);
2562 /* Read certificate information. */
2563 assert (!app->app_local->certificate_info);
2564 assert (!app->app_local->trusted_certificate_info);
2565 assert (!app->app_local->useful_certificate_info);
2566 err = read_ef_cdf (app, app->app_local->odf.certificates,
2567 &app->app_local->certificate_info);
2568 if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
2569 err = read_ef_cdf (app, app->app_local->odf.trusted_certificates,
2570 &app->app_local->trusted_certificate_info);
2571 if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
2572 err = read_ef_cdf (app, app->app_local->odf.useful_certificates,
2573 &app->app_local->useful_certificate_info);
2574 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
2579 /* Read information about private keys. */
2580 assert (!app->app_local->private_key_info);
2581 err = read_ef_prkdf (app, app->app_local->odf.private_keys,
2582 &app->app_local->private_key_info);
2583 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
2588 /* Read information about authentication objects. */
2589 assert (!app->app_local->auth_object_info);
2590 err = read_ef_aodf (app, app->app_local->odf.auth_objects,
2591 &app->app_local->auth_object_info);
2592 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
2600 /* Helper to do_learn_status: Send information about all certificates
2601 listed in CERTINFO back. Use CERTTYPE as type of the
2604 send_certinfo (app_t app, ctrl_t ctrl, const char *certtype,
2605 cdf_object_t certinfo)
2607 for (; certinfo; certinfo = certinfo->next)
2611 buf = xtrymalloc (9 + certinfo->objidlen*2 + 1);
2613 return gpg_error_from_syserror ();
2614 p = stpcpy (buf, "P15");
2615 if (app->app_local->home_df)
2617 snprintf (p, 6, "-%04X",
2618 (unsigned int)(app->app_local->home_df & 0xffff));
2621 p = stpcpy (p, ".");
2622 bin2hex (certinfo->objid, certinfo->objidlen, p);
2624 send_status_info (ctrl, "CERTINFO",
2625 certtype, strlen (certtype),
2634 /* Get the keygrip of the private key object PRKDF. On success the
2635 * keygrip, the algo and the length are stored in the KEYGRIP,
2636 * KEYALGO, and KEYNBITS fields of the PRKDF object. */
2638 keygrip_from_prkdf (app_t app, prkdf_object_t prkdf)
2645 gcry_sexp_t s_pkey = NULL;
2647 /* Easy if we got a cached version. */
2648 if (prkdf->keygrip_valid)
2651 xfree (prkdf->common_name);
2652 prkdf->common_name = NULL;
2653 xfree (prkdf->serial_number);
2654 prkdf->serial_number = NULL;
2656 /* FIXME: We should check whether a public key directory file and a
2657 matching public key for PRKDF is available. This should make
2658 extraction of the key much easier. My current test card doesn't
2659 have one, so we can only use the fallback solution by looking for
2660 a matching certificate and extract the key from there. */
2662 /* Look for a matching certificate. A certificate matches if the Id
2663 matches the one of the private key info. */
2664 for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
2665 if (cdf->objidlen == prkdf->objidlen
2666 && !memcmp (cdf->objid, prkdf->objid, prkdf->objidlen))
2669 for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
2670 if (cdf->objidlen == prkdf->objidlen
2671 && !memcmp (cdf->objid, prkdf->objid, prkdf->objidlen))
2674 for (cdf = app->app_local->useful_certificate_info; cdf; cdf = cdf->next)
2675 if (cdf->objidlen == prkdf->objidlen
2676 && !memcmp (cdf->objid, prkdf->objid, prkdf->objidlen))
2680 err = gpg_error (GPG_ERR_NOT_FOUND);
2684 err = readcert_by_cdf (app, cdf, &der, &derlen);
2688 err = ksba_cert_new (&cert);
2690 err = ksba_cert_init_from_mem (cert, der, derlen);
2693 err = app_help_get_keygrip_string (cert, prkdf->keygrip, &s_pkey);
2696 /* Try to get the CN and the SerialNumber from the certificate;
2697 * we use a very simple approach here which should work in many
2698 * cases. Eventually we should add a rfc-2253 parser into
2699 * libksba to make it easier to parse such a string.
2701 * First example string:
2702 * "CN=Otto Schily,O=Miniluv,C=DE"
2703 * Second example string:
2704 * "2.5.4.5=#445452323030303236333531,2.5.4.4=#4B6F6368,"
2705 * "2.5.4.42=#5765726E6572,CN=Werner Koch,OU=For testing"
2706 * " purposes only!,O=Testorganisation,C=DE"
2708 char *dn = ksba_cert_get_subject (cert, 0);
2711 char *p, *pend, *buf;
2713 p = strstr (dn, "CN=");
2714 if (p && (p==dn || p[-1] == ','))
2717 if (!(pend = strchr (p, ',')))
2718 pend = p + strlen (p);
2719 if (pend && pend > p
2720 && (prkdf->common_name = xtrymalloc ((pend - p) + 1)))
2722 memcpy (prkdf->common_name, p, pend-p);
2723 prkdf->common_name[pend-p] = 0;
2726 p = strstr (dn, "2.5.4.5=#"); /* OID of the SerialNumber */
2727 if (p && (p==dn || p[-1] == ','))
2730 if (!(pend = strchr (p, ',')))
2731 pend = p + strlen (p);
2732 if (pend && pend > p
2733 && (buf = xtrymalloc ((pend - p) + 1)))
2735 memcpy (buf, p, pend-p);
2737 if (!hex2str (buf, buf, strlen (buf)+1, NULL))
2738 xfree (buf); /* Invalid hex encoding. */
2740 prkdf->serial_number = buf;
2747 ksba_cert_release (cert);
2751 prkdf->keyalgo = get_pk_algo_from_key (s_pkey);
2752 if (!prkdf->keyalgo)
2754 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
2758 prkdf->keynbits = gcry_pk_get_nbits (s_pkey);
2759 if (!prkdf->keynbits)
2761 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
2765 prkdf->keygrip_valid = 1; /* Yeah, got everything. */
2768 gcry_sexp_release (s_pkey);
2773 /* Return a malloced keyref string for PRKDF. Returns NULL on
2774 * malloc failure. */
2776 keyref_from_prkdf (app_t app, prkdf_object_t prkdf)
2780 buf = xtrymalloc (4 + 5 + prkdf->objidlen*2 + 1);
2783 p = stpcpy (buf, "P15");
2784 if (app->app_local->home_df)
2786 snprintf (p, 6, "-%04X",
2787 (unsigned int)(app->app_local->home_df & 0xffff));
2790 p = stpcpy (p, ".");
2791 bin2hex (prkdf->objid, prkdf->objidlen, p);
2796 /* Helper to do_learn_status: Send information about all known
2797 keypairs back. FIXME: much code duplication from
2800 send_keypairinfo (app_t app, ctrl_t ctrl, prkdf_object_t prkdf)
2804 for (; prkdf; prkdf = prkdf->next)
2809 buf = keyref_from_prkdf (app, prkdf);
2811 return gpg_error_from_syserror ();
2813 err = keygrip_from_prkdf (app, prkdf);
2816 log_error ("p15: error getting keygrip from ");
2817 for (j=0; j < prkdf->pathlen; j++)
2818 log_printf ("%s%04hX", j?"/":"", prkdf->path[j]);
2819 log_printf (": %s\n", gpg_strerror (err));
2824 size_t usagelen = 0;
2826 if (prkdf->usageflags.sign
2827 || prkdf->usageflags.sign_recover
2828 || prkdf->usageflags.non_repudiation)
2829 usage[usagelen++] = 's';
2830 if (prkdf->usageflags.sign
2831 || prkdf->usageflags.sign_recover)
2832 usage[usagelen++] = 'c';
2833 if (prkdf->usageflags.decrypt
2834 || prkdf->usageflags.unwrap)
2835 usage[usagelen++] = 'e';
2836 if (prkdf->usageflags.sign
2837 || prkdf->usageflags.sign_recover)
2838 usage[usagelen++] = 'a';
2840 log_assert (strlen (prkdf->keygrip) == 40);
2841 send_status_info (ctrl, "KEYPAIRINFO",
2842 prkdf->keygrip, 2*KEYGRIP_LEN,
2854 /* This is the handler for the LEARN command. */
2856 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
2864 err = do_getattr (app, ctrl, "MANUFACTURER");
2866 err = send_certinfo (app, ctrl, "100",
2867 app->app_local->certificate_info);
2869 err = send_certinfo (app, ctrl, "101",
2870 app->app_local->trusted_certificate_info);
2872 err = send_certinfo (app, ctrl, "102",
2873 app->app_local->useful_certificate_info);
2877 err = send_keypairinfo (app, ctrl, app->app_local->private_key_info);
2883 /* Read a certifciate using the information in CDF and return the
2884 certificate in a newly llocated buffer R_CERT and its length
2887 readcert_by_cdf (app_t app, cdf_object_t cdf,
2888 unsigned char **r_cert, size_t *r_certlen)
2891 unsigned char *buffer = NULL;
2892 const unsigned char *p, *save_p;
2894 int class, tag, constructed, ndef;
2895 size_t totobjlen, objlen, hdrlen;
2902 /* First check whether it has been cached. */
2905 *r_cert = xtrymalloc (cdf->imagelen);
2907 return gpg_error_from_syserror ();
2908 memcpy (*r_cert, cdf->image, cdf->imagelen);
2909 *r_certlen = cdf->imagelen;
2913 /* Read the entire file. fixme: This could be optimized by first
2914 reading the header to figure out how long the certificate
2916 err = select_ef_by_path (app, cdf->path, cdf->pathlen);
2920 err = iso7816_read_binary_ext (app_get_slot (app), 1, cdf->off, cdf->len,
2922 if (!err && (!buflen || *buffer == 0xff))
2923 err = gpg_error (GPG_ERR_NOT_FOUND);
2926 log_error ("p15: error reading certificate id=");
2927 for (i=0; i < cdf->objidlen; i++)
2928 log_printf ("%02X", cdf->objid[i]);
2929 log_printf (" at ");
2930 for (i=0; i < cdf->pathlen; i++)
2931 log_printf ("%s%04hX", i? "/":"", cdf->path[i]);
2932 log_printf (": %s\n", gpg_strerror (err));
2936 /* Check whether this is really a certificate. */
2939 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2940 &ndef, &objlen, &hdrlen);
2944 if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed)
2946 else if ( class == CLASS_UNIVERSAL && tag == TAG_SET && constructed )
2950 err = gpg_error (GPG_ERR_INV_OBJ);
2953 totobjlen = objlen + hdrlen;
2954 assert (totobjlen <= buflen);
2956 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2957 &ndef, &objlen, &hdrlen);
2962 && class == CLASS_UNIVERSAL && tag == TAG_OBJECT_ID && !constructed)
2964 /* The certificate seems to be contained in a userCertificate
2965 container. Skip this and assume the following sequence is
2969 err = gpg_error (GPG_ERR_INV_OBJ);
2975 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2976 &ndef, &objlen, &hdrlen);
2979 if ( !(class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed) )
2981 err = gpg_error (GPG_ERR_INV_OBJ);
2984 totobjlen = objlen + hdrlen;
2985 assert (save_p + totobjlen <= buffer + buflen);
2986 memmove (buffer, save_p, totobjlen);
2991 *r_certlen = totobjlen;
2993 /* Try to cache it. */
2994 if (!cdf->image && (cdf->image = xtrymalloc (*r_certlen)))
2996 memcpy (cdf->image, *r_cert, *r_certlen);
2997 cdf->imagelen = *r_certlen;
3007 /* Handler for the READCERT command.
3009 Read the certificate with id CERTID (as returned by learn_status in
3010 the CERTINFO status lines) and return it in the freshly allocated
3011 buffer to be stored at R_CERT and its length at R_CERTLEN. A error
3012 code will be returned on failure and R_CERT and R_CERTLEN will be
3015 do_readcert (app_t app, const char *certid,
3016 unsigned char **r_cert, size_t *r_certlen)
3023 err = cdf_object_from_certid (app, certid, &cdf);
3025 err = readcert_by_cdf (app, cdf, r_cert, r_certlen);
3031 /* Implement the GETATTR command. This is similar to the LEARN
3032 command but returns just one value via the status interface. */
3034 do_getattr (app_t app, ctrl_t ctrl, const char *name)
3037 prkdf_object_t prkdf;
3039 if (!strcmp (name, "$AUTHKEYID")
3040 || !strcmp (name, "$ENCRKEYID")
3041 || !strcmp (name, "$SIGNKEYID"))
3045 /* We return the ID of the first private key capable of the
3046 * requested action. Note that we do not yet return
3047 * non_repudiation keys for $SIGNKEYID because our D-Trust
3048 * testcard uses rsaPSS, which is not supported by gpgsm and not
3049 * covered by the VS-NfD approval. */
3050 for (prkdf = app->app_local->private_key_info; prkdf;
3051 prkdf = prkdf->next)
3053 if (name[1] == 'A' && (prkdf->usageflags.sign
3054 || prkdf->usageflags.sign_recover))
3056 else if (name[1] == 'E' && (prkdf->usageflags.decrypt
3057 || prkdf->usageflags.unwrap))
3059 else if (name[1] == 'S' && (prkdf->usageflags.sign
3060 || prkdf->usageflags.sign_recover))
3065 buf = keyref_from_prkdf (app, prkdf);
3067 return gpg_error_from_syserror ();
3069 send_status_info (ctrl, name, buf, strlen (buf), NULL, 0);
3074 else if (!strcmp (name, "$DISPSERIALNO"))
3076 /* For certain cards we return special IDs. There is no
3077 general rule for it so we need to decide case by case. */
3078 if (app->app_local->card_type == CARD_TYPE_BELPIC)
3080 /* The eID card has a card number printed on the front matter
3081 which seems to be a good indication. */
3082 unsigned char *buffer;
3083 const unsigned char *p;
3085 unsigned short path[] = { 0x3F00, 0xDF01, 0x4031 };
3087 err = select_ef_by_path (app, path, DIM(path) );
3089 err = iso7816_read_binary (app->slot, 0, 0, &buffer, &buflen);
3092 log_error ("p15: error accessing EF(ID): %s\n",
3093 gpg_strerror (err));
3097 p = find_tlv (buffer, buflen, 1, &n);
3103 memcpy (tmp+4, p+3, 7);
3105 memcpy (tmp+12, p+10, 2);
3107 send_status_info (ctrl, name, tmp, strlen (tmp), NULL, 0);
3115 /* We use the first private key object which has a serial
3116 * number set. If none was found, we parse the first
3117 * object and see whether this has then a serial number. */
3118 for (prkdf = app->app_local->private_key_info; prkdf;
3119 prkdf = prkdf->next)
3120 if (prkdf->serial_number)
3122 if (!prkdf && app->app_local->private_key_info)
3124 prkdf = app->app_local->private_key_info;
3125 keygrip_from_prkdf (app, prkdf);
3126 if (!prkdf->serial_number)
3131 char *sn = get_dispserialno (app, prkdf);
3132 /* Unless there is a bogus S/N in the cert we should
3133 * have a suitable one from the cert here now. */
3134 err = send_status_printf (ctrl, name, "%s", sn);
3139 /* No abbreviated serial number. */
3141 else if (!strcmp (name, "MANUFACTURER"))
3143 if (app->app_local->manufacturer_id)
3144 return send_status_printf (ctrl, "MANUFACTURER", "0 %s",
3145 app->app_local->manufacturer_id);
3149 return gpg_error (GPG_ERR_INV_NAME);
3155 /* Micardo cards require special treatment. This is a helper for the
3156 crypto functions to manage the security environment. We expect that
3157 the key file has already been selected. FID is the one of the
3160 micardo_mse (app_t app, unsigned short fid)
3164 unsigned short refdata = 0;
3166 unsigned char msebuf[10];
3168 /* Read the KeyD file containing extra information on keys. */
3169 err = iso7816_select_file (app->slot, 0x0013, 0);
3172 log_error ("p15: error reading EF_keyD: %s\n", gpg_strerror (err));
3176 for (recno = 1, se_num = -1; ; recno++)
3178 unsigned char *buffer;
3181 const unsigned char *p, *pp;
3183 err = iso7816_read_record (app->slot, recno, 1, 0, &buffer, &buflen);
3184 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
3188 log_error ("p15: error reading EF_keyD record: %s\n",
3189 gpg_strerror (err));
3194 log_info (buffer, buflen, "p15: keyD record: ");
3195 log_printhex (buffer, buflen, "");
3197 p = find_tlv (buffer, buflen, 0x83, &n);
3198 if (p && n == 4 && ((p[2]<<8)|p[3]) == fid)
3200 refdata = ((p[0]<<8)|p[1]);
3201 /* Locate the SE DO and the there included sec env number. */
3202 p = find_tlv (buffer, buflen, 0x7b, &n);
3205 pp = find_tlv (p, n, 0x80, &nn);
3218 log_error ("p15: CRT for keyfile %04hX not found\n", fid);
3219 return gpg_error (GPG_ERR_NOT_FOUND);
3223 /* Restore the security environment to SE_NUM if needed */
3226 err = iso7816_manage_security_env (app->slot, 0xf3, se_num, NULL, 0);
3229 log_error ("p15: restoring SE to %d failed: %s\n",
3230 se_num, gpg_strerror (err));
3235 /* Set the DST reference data. */
3239 msebuf[3] = (refdata >> 8);
3240 msebuf[4] = refdata;
3241 err = iso7816_manage_security_env (app->slot, 0x41, 0xb6, msebuf, 5);
3244 log_error ("p15: setting SE to reference file %04hX failed: %s\n",
3245 refdata, gpg_strerror (err));
3253 /* Prepare the verification of the PIN for the key PRKDF by checking
3254 * the AODF and selecting the key file. KEYREF is used for error
3257 prepare_verify_pin (app_t app, const char *keyref,
3258 prkdf_object_t prkdf, aodf_object_t aodf)
3265 log_info ("p15: using AODF %04hX id=", aodf->fid);
3266 for (i=0; i < aodf->objidlen; i++)
3267 log_printf ("%02X", aodf->objid[i]);
3271 if (aodf->authid && opt.verbose)
3272 log_info ("p15: PIN is controlled by another authentication token\n");
3274 if (aodf->pinflags.integrity_protected
3275 || aodf->pinflags.confidentiality_protected)
3278 "PIN verification requires unsupported protection method\n");
3279 return gpg_error (GPG_ERR_BAD_PIN_METHOD);
3281 if (!aodf->stored_length && aodf->pinflags.needs_padding)
3284 "PIN verification requires padding but no length known\n");
3285 return gpg_error (GPG_ERR_INV_CARD);
3289 if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
3291 /* According to our protocol analysis we need to select a
3292 * special AID here. Before that the master file needs to be
3293 * selected. (RID A000000167 is assigned to IBM) */
3294 static char const dtrust_aid[] =
3295 { 0xA0, 0x00, 0x00, 0x01, 0x67, 0x45, 0x53, 0x49, 0x47, 0x4E };
3297 err = iso7816_select_mf (app_get_slot (app));
3299 err = iso7816_select_application (app_get_slot (app),
3300 dtrust_aid, sizeof dtrust_aid, 0);
3302 log_error ("p15: error selecting D-TRUST's AID for key %s: %s\n",
3303 keyref, gpg_strerror (err));
3307 /* Standard case: Select the key file. Note that this may
3308 * change the security environment thus we need to do it before
3309 * PIN verification. */
3310 err = select_ef_by_path (app, prkdf->path, prkdf->pathlen);
3312 log_error ("p15: error selecting file for key %s: %s\n",
3313 keyref, gpg_strerror (err));
3321 any_control_or_space (const char *string)
3323 const unsigned char *s;
3325 for (s = string; *string; string++)
3326 if (*s <= 0x20 || *s >= 0x7f)
3332 /* Return a malloced serial number to be shown to the user. PRKDF is
3333 * used to get it from a certificate; PRKDF may be NULL. */
3335 get_dispserialno (app_t app, prkdf_object_t prkdf)
3339 /* We prefer the SerialNumber RDN from the Subject-DN but we don't
3340 * use it if it features a percent sign (special character in pin
3341 * prompts) or has any control character. */
3342 if (prkdf && prkdf->serial_number && *prkdf->serial_number
3343 && !strchr (prkdf->serial_number, '%')
3344 && !any_control_or_space (prkdf->serial_number))
3346 serial = xtrystrdup (prkdf->serial_number);
3350 serial = app_get_serialno (app);
3356 /* Return an allocated string to be used as prompt. Returns NULL on
3359 make_pin_prompt (app_t app, int remaining, const char *firstline,
3360 prkdf_object_t prkdf)
3362 char *serial, *tmpbuf, *result;
3364 serial = get_dispserialno (app, prkdf);
3366 /* TRANSLATORS: Put a \x1f right before a colon. This can be
3367 * used by pinentry to nicely align the names and values. Keep
3368 * the %s at the start and end of the string. */
3369 result = xtryasprintf (_("%s"
3370 "Number\x1f: %s%%0A"
3375 prkdf->common_name? prkdf->common_name: "",
3379 return NULL; /* Out of core. */
3381 /* Append a "remaining attempts" info if needed. */
3382 if (remaining != -1 && remaining < 3)
3386 /* TRANSLATORS: This is the number of remaining attempts to
3387 * enter a PIN. Use %%0A (double-percent,0A) for a linefeed. */
3388 rembuf = xtryasprintf (_("Remaining attempts: %d"), remaining);
3391 tmpbuf = strconcat (firstline, "%0A%0A", result,
3392 "%0A%0A", rembuf, NULL);
3402 tmpbuf = strconcat (firstline, "%0A%0A", result, NULL);
3411 /* Given the private key object PRKDF and its authentication object
3412 * AODF ask for the PIN and verify that PIN. */
3414 verify_pin (app_t app,
3415 gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg,
3416 prkdf_object_t prkdf, aodf_object_t aodf)
3431 pin_reference = aodf->pin_reference_valid? aodf->pin_reference : 0;
3433 if (app->app_local->card_type == CARD_TYPE_CARDOS_50)
3435 /* We know that this card supports a verify status check. Note
3436 * that in contrast to PIV cards ISO7816_VERIFY_NOT_NEEDED is
3438 remaining = iso7816_verify_status (app_get_slot (app), pin_reference);
3440 remaining = -1; /* We don't care about the concrete error. */
3444 log_info ("p15: PIN has %d attempts left\n", remaining);
3445 /* On error or if less than 3 better ask. */
3446 prkdf->pin_verified = 0;
3450 remaining = -1; /* Unknown. */
3452 /* Check whether we already verified it. */
3453 if (prkdf->pin_verified)
3454 return 0; /* Already done. */
3456 if (prkdf->usageflags.non_repudiation
3457 && (app->app_local->card_type == CARD_TYPE_BELPIC
3458 || app->app_local->card_product == CARD_PRODUCT_DTRUST))
3459 label = _("||Please enter the PIN for the key to create "
3460 "qualified signatures.");
3462 label = _("||Please enter the PIN for the standard keys.");
3465 char *prompt = make_pin_prompt (app, remaining, label, prkdf);
3467 err = gpg_error_from_syserror ();
3469 err = pincb (pincb_arg, prompt, &pinvalue);
3474 log_info ("p15: PIN callback returned error: %s\n", gpg_strerror (err));
3478 /* We might need to cope with UTF8 things here. Not sure how
3479 min_length etc. are exactly defined, for now we take them as
3480 a plain octet count. */
3481 if (strlen (pinvalue) < aodf->min_length)
3483 log_error ("p15: PIN is too short; minimum length is %lu\n",
3485 err = gpg_error (GPG_ERR_BAD_PIN);
3487 else if (aodf->stored_length && strlen (pinvalue) > aodf->stored_length)
3489 /* This would otherwise truncate the PIN silently. */
3490 log_error ("p15: PIN is too large; maximum length is %lu\n",
3491 aodf->stored_length);
3492 err = gpg_error (GPG_ERR_BAD_PIN);
3494 else if (aodf->max_length_valid && strlen (pinvalue) > aodf->max_length)
3496 log_error ("p15: PIN is too large; maximum length is %lu\n",
3498 err = gpg_error (GPG_ERR_BAD_PIN);
3509 switch (aodf->pintype)
3512 case PIN_TYPE_ASCII_NUMERIC:
3513 for (s=pinvalue; digitp (s); s++)
3517 errstr = "Non-numeric digits found in PIN";
3518 err = gpg_error (GPG_ERR_BAD_PIN);
3523 case PIN_TYPE_HALF_NIBBLE_BCD:
3524 errstr = "PIN type Half-Nibble-BCD is not supported";
3526 case PIN_TYPE_ISO9564_1:
3527 errstr = "PIN type ISO9564-1 is not supported";
3530 errstr = "Unknown PIN type";
3535 log_error ("p15: can't verify PIN: %s\n", errstr);
3537 return err? err : gpg_error (GPG_ERR_BAD_PIN_METHOD);
3541 if (aodf->pintype == PIN_TYPE_BCD )
3546 for (ndigits=0, s=pinvalue; *s; ndigits++, s++)
3548 paddedpin = xtrymalloc (aodf->stored_length+1);
3551 err = gpg_error_from_syserror ();
3557 paddedpin[i++] = 0x20 | (ndigits & 0x0f);
3558 for (s=pinvalue; i < aodf->stored_length && *s && s[1]; s = s+2 )
3559 paddedpin[i++] = (((*s - '0') << 4) | ((s[1] - '0') & 0x0f));
3560 if (i < aodf->stored_length && *s)
3561 paddedpin[i++] = (((*s - '0') << 4)
3562 |((aodf->pad_char_valid?aodf->pad_char:0)&0x0f));
3564 if (aodf->pinflags.needs_padding)
3566 while (i < aodf->stored_length)
3567 paddedpin[i++] = aodf->pad_char_valid? aodf->pad_char : 0;
3571 pinvalue = paddedpin;
3574 else if (aodf->pinflags.needs_padding)
3578 paddedpin = xtrymalloc (aodf->stored_length+1);
3581 err = gpg_error_from_syserror ();
3585 for (i=0, s=pinvalue; i < aodf->stored_length && *s; i++, s++)
3587 /* Not sure what padding char to use if none has been set.
3588 For now we use 0x00; maybe a space would be better. */
3589 for (; i < aodf->stored_length; i++)
3590 paddedpin[i] = aodf->pad_char_valid? aodf->pad_char : 0;
3594 pinvalue = paddedpin;
3597 pinvaluelen = strlen (pinvalue);
3599 /* log_printhex (pinvalue, pinvaluelen, */
3600 /* "about to verify with ref %lu pin:", pin_reference); */
3601 err = iso7816_verify (app_get_slot (app), pin_reference,
3602 pinvalue, pinvaluelen);
3606 log_error ("p15: PIN verification failed: %s\n", gpg_strerror (err));
3610 log_info ("p15: PIN verification succeeded\n");
3611 prkdf->pin_verified = 1;
3619 /* Handler for the PKSIGN command.
3621 Create the signature and return the allocated result in OUTDATA.
3622 If a PIN is required, the PINCB will be used to ask for the PIN;
3623 that callback should return the PIN in an allocated buffer and
3624 store that as the 3rd argument. */
3626 do_sign (app_t app, const char *keyidstr, int hashalgo,
3627 gpg_error_t (*pincb)(void*, const char *, char **),
3629 const void *indata, size_t indatalen,
3630 unsigned char **outdata, size_t *outdatalen )
3632 static unsigned char sha256_prefix[19] = /* OID: 2.16.840.1.101.3.4.2.1 */
3633 { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
3634 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20 };
3635 static unsigned char sha1_prefix[15] = /* Object ID is 1.3.14.3.2.26 */
3636 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
3637 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
3638 static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
3639 { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
3640 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
3643 unsigned char data[32+19]; /* Must be large enough for a SHA-256 digest
3644 * + the largest OID prefix above and also
3645 * fit the 36 bytes of md5sha1. */
3646 prkdf_object_t prkdf; /* The private key object. */
3647 aodf_object_t aodf; /* The associated authentication object. */
3648 int no_data_padding = 0; /* True if the card want the data without padding.*/
3649 int mse_done = 0; /* Set to true if the MSE has been done. */
3650 unsigned int hashlen; /* Length of the hash. */
3651 unsigned int datalen; /* Length of the data to sign (prefix+hash). */
3652 unsigned char *dataptr;
3653 int exmode, le_value;
3656 if (!keyidstr || !*keyidstr)
3657 return gpg_error (GPG_ERR_INV_VALUE);
3658 if (indatalen != 20 && indatalen != 16
3659 && indatalen != 35 && indatalen != 36
3660 && indatalen != (32+19))
3661 return gpg_error (GPG_ERR_INV_VALUE);
3663 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
3666 if (!(prkdf->usageflags.sign || prkdf->usageflags.sign_recover
3667 ||prkdf->usageflags.non_repudiation))
3669 log_error ("p15: key %s may not be used for signing\n", keyidstr);
3670 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
3675 log_error ("p15: no authentication object defined for %s\n", keyidstr);
3676 /* fixme: we might want to go ahead and do without PIN
3678 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
3681 /* Find the authentication object to this private key object. */
3682 for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
3683 if (aodf->objidlen == prkdf->authidlen
3684 && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
3688 log_error ("p15: authentication object for %s missing\n", keyidstr);
3689 return gpg_error (GPG_ERR_INV_CARD);
3692 /* We need some more info about the key - get the keygrip to
3693 * populate these fields. */
3694 err = keygrip_from_prkdf (app, prkdf);
3697 log_error ("p15: keygrip_from_prkdf failed: %s\n", gpg_strerror (err));
3701 /* Prepare PIN verification. This is split so that we can do
3702 * MSE operation for some task after having selected the key file but
3703 * before sending the verify APDU. */
3704 err = prepare_verify_pin (app, keyidstr, prkdf, aodf);
3708 /* Due to the fact that the non-repudiation signature on a BELPIC
3709 card requires a verify immediately before the DSO we set the
3710 MSE before we do the verification. Other cards might also allow
3711 this but I don't want to break anything, thus we do it only
3712 for the BELPIC card here. */
3713 if (app->app_local->card_type == CARD_TYPE_BELPIC)
3715 unsigned char mse[5];
3717 mse[0] = 4; /* Length of the template. */
3718 mse[1] = 0x80; /* Algorithm reference tag. */
3719 if (hashalgo == MD_USER_TLS_MD5SHA1)
3720 mse[2] = 0x01; /* Let card do pkcs#1 0xFF padding. */
3722 mse[2] = 0x02; /* RSASSA-PKCS1-v1.5 using SHA1. */
3723 mse[3] = 0x84; /* Private key reference tag. */
3724 mse[4] = prkdf->key_reference_valid? prkdf->key_reference : 0x82;
3726 err = iso7816_manage_security_env (app->slot,
3729 no_data_padding = 1;
3734 log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
3738 /* Now that we have all the information available run the actual PIN
3740 err = verify_pin (app, pincb, pincb_arg, prkdf, aodf);
3745 /* Prepare the DER object from INDATA. */
3746 if (indatalen == 36)
3748 /* No ASN.1 container used. */
3749 if (hashalgo != MD_USER_TLS_MD5SHA1)
3750 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3751 memcpy (data, indata, indatalen);
3752 datalen = hashlen = 36;
3754 else if (indatalen == 35)
3756 /* Alright, the caller was so kind to send us an already
3757 prepared DER object. Check that it is what we want and that
3758 it matches the hash algorithm. */
3759 if (hashalgo == GCRY_MD_SHA1 && !memcmp (indata, sha1_prefix, 15))
3761 else if (hashalgo == GCRY_MD_RMD160
3762 && !memcmp (indata, rmd160_prefix, 15))
3765 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3766 memcpy (data, indata, indatalen);
3770 else if (indatalen == 32 + 19)
3772 /* Seems to be a prepared SHA256 DER object. */
3773 if (hashalgo == GCRY_MD_SHA256 && !memcmp (indata, sha256_prefix, 19))
3776 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3777 memcpy (data, indata, indatalen);
3783 /* Need to prepend the prefix. */
3784 if (hashalgo == GCRY_MD_SHA256)
3786 memcpy (data, sha256_prefix, 19);
3787 memcpy (data+19, indata, indatalen);
3791 else if (hashalgo == GCRY_MD_SHA1)
3793 memcpy (data, sha1_prefix, 15);
3794 memcpy (data+15, indata, indatalen);
3798 else if (hashalgo == GCRY_MD_RMD160)
3800 memcpy (data, rmd160_prefix, 15);
3801 memcpy (data+15, indata, indatalen);
3806 return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
3810 /* Manage security environment needs to be tweaked for certain cards. */
3813 else if (app->app_local->card_type == CARD_TYPE_TCOS)
3815 /* TCOS creates signatures always using the local key 0. MSE
3818 else if (app->app_local->card_type == CARD_TYPE_MICARDO)
3820 if (!prkdf->pathlen)
3821 err = gpg_error (GPG_ERR_BUG);
3823 err = micardo_mse (app, prkdf->path[prkdf->pathlen-1]);
3825 else if (prkdf->key_reference_valid)
3827 unsigned char mse[3];
3829 mse[0] = 0x84; /* Select asym. key. */
3831 mse[2] = prkdf->key_reference;
3833 err = iso7816_manage_security_env (app->slot,
3839 log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
3844 if (no_data_padding)
3846 dataptr += datalen - hashlen;
3850 if (prkdf->keyalgo == GCRY_PK_RSA && prkdf->keynbits > 2048)
3853 le_value = prkdf->keynbits / 8;
3861 err = iso7816_compute_ds (app_get_slot (app),
3862 exmode, dataptr, datalen,
3863 le_value, outdata, outdatalen);
3869 /* Handler for the PKAUTH command.
3871 This is basically the same as the PKSIGN command but we first check
3872 that the requested key is suitable for authentication; that is, it
3873 must match the criteria used for the attribute $AUTHKEYID. See
3874 do_sign for calling conventions; there is no HASHALGO, though. */
3876 do_auth (app_t app, const char *keyidstr,
3877 gpg_error_t (*pincb)(void*, const char *, char **),
3879 const void *indata, size_t indatalen,
3880 unsigned char **outdata, size_t *outdatalen )
3883 prkdf_object_t prkdf;
3886 if (!keyidstr || !*keyidstr)
3887 return gpg_error (GPG_ERR_INV_VALUE);
3889 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
3892 if (!prkdf->usageflags.sign)
3894 log_error ("p15: key %s may not be used for authentication\n", keyidstr);
3895 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
3898 algo = indatalen == 36? MD_USER_TLS_MD5SHA1 : GCRY_MD_SHA1;
3899 return do_sign (app, keyidstr, algo, pincb, pincb_arg,
3900 indata, indatalen, outdata, outdatalen);
3904 /* Handler for the PKDECRYPT command. Decrypt the data in INDATA and
3905 * return the allocated result in OUTDATA. If a PIN is required the
3906 * PINCB will be used to ask for the PIN; it should return the PIN in
3907 * an allocated buffer and put it into PIN. */
3909 do_decipher (app_t app, const char *keyidstr,
3910 gpg_error_t (*pincb)(void*, const char *, char **),
3912 const void *indata, size_t indatalen,
3913 unsigned char **outdata, size_t *outdatalen,
3914 unsigned int *r_info)
3917 prkdf_object_t prkdf; /* The private key object. */
3918 aodf_object_t aodf; /* The associated authentication object. */
3919 int exmode, le_value, padind;
3923 if (!keyidstr || !*keyidstr)
3924 return gpg_error (GPG_ERR_INV_VALUE);
3925 if (!indatalen || !indata || !outdatalen || !outdata)
3926 return gpg_error (GPG_ERR_INV_ARG);
3928 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
3931 if (!(prkdf->usageflags.decrypt || prkdf->usageflags.unwrap))
3933 log_error ("p15: key %s may not be used for decruption\n", keyidstr);
3934 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
3937 /* Find the authentication object to this private key object. */
3940 log_error ("p15: no authentication object defined for %s\n", keyidstr);
3941 /* fixme: we might want to go ahead and do without PIN
3943 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
3945 for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
3946 if (aodf->objidlen == prkdf->authidlen
3947 && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
3951 log_error ("p15: authentication object for %s missing\n", keyidstr);
3952 return gpg_error (GPG_ERR_INV_CARD);
3955 /* We need some more info about the key - get the keygrip to
3956 * populate these fields. */
3957 err = keygrip_from_prkdf (app, prkdf);
3960 log_error ("p15: keygrip_from_prkdf failed: %s\n", gpg_strerror (err));
3964 /* Verify the PIN. */
3965 err = prepare_verify_pin (app, keyidstr, prkdf, aodf);
3967 err = verify_pin (app, pincb, pincb_arg, prkdf, aodf);
3972 /* The next is guess work for CardOS. */
3973 if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
3975 /* From analyzing an USB trace of a Windows signing application
3976 * we see that the SE is simply reset to 0x14. It seems to be
3977 * sufficient to do this for decryption; signing still works
3978 * with the standard code despite that our trace showed that
3979 * there the SE is restored to 0x09. Note that the special
3980 * D-Trust AID is in any case select by prepare_verify_pin.
3982 * Hey, D-Trust please hand over the specs so that you can
3983 * actually sell your cards and we can properly implement it;
3984 * other vendors understand this and do not demand ridiculous
3985 * paper work or complicated procedures to get samples. */
3986 err = iso7816_manage_security_env (app_get_slot (app),
3987 0xF3, 0x14, NULL, 0);
3990 else if (prkdf->key_reference_valid)
3992 unsigned char mse[6];
3994 /* Note: This works with CardOS but the D-Trust card has the
3995 * problem that the next created signature would be broken. */
3997 mse[0] = 0x80; /* Algorithm reference. */
3999 mse[2] = 0x0a; /* RSA, no padding. */
4002 mse[5] = prkdf->key_reference;
4003 err = iso7816_manage_security_env (app_get_slot (app), 0x41, 0xB8,
4006 /* Check for MSE error. */
4009 log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
4013 exmode = le_value = 0;
4015 if (prkdf->keyalgo == GCRY_PK_RSA && prkdf->keynbits > 2048)
4017 exmode = 1; /* Extended length w/o a limit. */
4018 le_value = prkdf->keynbits / 8;
4021 if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
4024 err = iso7816_decipher (app_get_slot (app), exmode,
4027 outdata, outdatalen);
4033 /* Assume that EF(DIR) has been selected. Read its content and figure
4034 out the home EF of pkcs#15. Return that home DF or 0 if not found
4035 and the value at the address of BELPIC indicates whether it was
4036 found by the belpic aid. */
4037 static unsigned short
4038 read_home_df (int slot, int *r_belpic)
4041 unsigned char *buffer;
4042 const unsigned char *p, *pp;
4043 size_t buflen, n, nn;
4044 unsigned short result = 0;
4048 err = iso7816_read_binary (slot, 0, 0, &buffer, &buflen);
4051 log_error ("p15: error reading EF(DIR): %s\n", gpg_strerror (err));
4055 /* FIXME: We need to scan all records. */
4056 p = find_tlv (buffer, buflen, 0x61, &n);
4059 pp = find_tlv (p, n, 0x4f, &nn);
4060 if (pp && ((nn == sizeof pkcs15_aid && !memcmp (pp, pkcs15_aid, nn))
4061 || (*r_belpic = (nn == sizeof pkcs15be_aid
4062 && !memcmp (pp, pkcs15be_aid, nn)))))
4064 pp = find_tlv (p, n, 0x50, &nn);
4065 if (pp && opt.verbose)
4066 log_info ("p15: application label from EF(DIR) is '%.*s'\n",
4068 pp = find_tlv (p, n, 0x51, &nn);
4069 if (pp && nn == 4 && *pp == 0x3f && !pp[1])
4071 result = ((pp[2] << 8) | pp[3]);
4073 log_info ("p15: application directory is 0x%04hX\n", result);
4083 Select the PKCS#15 application on the card in SLOT.
4086 app_select_p15 (app_t app)
4088 int slot = app->slot;
4090 unsigned short def_home_df = 0;
4091 card_type_t card_type = CARD_TYPE_UNKNOWN;
4095 rc = iso7816_select_application (slot, pkcs15_aid, sizeof pkcs15_aid, 0);
4097 { /* Not found: Try to locate it from 2F00. We use direct path
4098 selection here because it seems that the Belgian eID card
4099 does only allow for that. Many other cards supports this
4100 selection method too. Note, that we don't use
4101 select_application above for the Belgian card - the call
4102 works but it seems that it does not switch to the correct DF.
4103 Using the 2f02 just works. */
4104 unsigned short path[1] = { 0x2f00 };
4106 rc = iso7816_select_path (slot, path, 1);
4110 def_home_df = read_home_df (slot, &is_belpic);
4113 path[0] = def_home_df;
4114 rc = iso7816_select_path (slot, path, 1);
4119 { /* Still not found: Try the default DF. */
4120 def_home_df = 0x5015;
4121 rc = iso7816_select_file (slot, def_home_df, 1);
4125 /* Determine the type of the card. The general case is to look
4126 it up from the ATR table. For the Belgian eID card we know
4127 it instantly from the AID. */
4130 card_type = CARD_TYPE_BELPIC;
4138 atr = apdu_get_atr (app->slot, &atrlen);
4140 rc = gpg_error (GPG_ERR_INV_CARD);
4143 for (i=0; card_atr_list[i].atrlen; i++)
4144 if (card_atr_list[i].atrlen == atrlen
4145 && !memcmp (card_atr_list[i].atr, atr, atrlen))
4147 card_type = card_atr_list[i].type;
4156 app->apptype = "P15";
4158 app->app_local = xtrycalloc (1, sizeof *app->app_local);
4159 if (!app->app_local)
4161 rc = gpg_error_from_syserror ();
4165 /* Set the home DF. Note that we currently can't do that if the
4166 selection via application ID worked. This will store 0 there
4167 instead. FIXME: We either need to figure the home_df via the
4168 DIR file or using the return values from the select file
4170 app->app_local->home_df = def_home_df;
4172 /* Store the card type. FIXME: We might want to put this into
4173 the common APP structure. */
4174 app->app_local->card_type = card_type;
4176 app->app_local->card_product = CARD_PRODUCT_UNKNOWN;
4178 /* Store whether we may and should use direct path selection. */
4179 app->app_local->direct_path_selection = direct;
4181 /* Read basic information and thus check whether this is a real
4183 rc = read_p15_info (app);
4187 /* Special serial number munging. We need to check for a German
4188 prototype card right here because we need to access to
4189 EF(TokenInfo). We mark such a serial number by the using a
4190 prefix of FF0100. */
4191 if (app->serialnolen == 12
4192 && !memcmp (app->serialno, "\xD2\x76\0\0\0\0\0\0\0\0\0\0", 12))
4194 /* This is a German card with a silly serial number. Try to get
4195 the serial number from the EF(TokenInfo). . */
4198 /* FIXME: actually get it from EF(TokenInfo). */
4200 p = xtrymalloc (3 + app->serialnolen);
4202 rc = gpg_error (gpg_err_code_from_errno (errno));
4205 memcpy (p, "\xff\x01", 3);
4206 memcpy (p+3, app->serialno, app->serialnolen);
4207 app->serialnolen += 3;
4208 xfree (app->serialno);
4213 app->fnc.deinit = do_deinit;
4214 app->fnc.learn_status = do_learn_status;
4215 app->fnc.readcert = do_readcert;
4216 app->fnc.getattr = do_getattr;
4217 app->fnc.setattr = NULL;
4218 app->fnc.genkey = NULL;
4219 app->fnc.sign = do_sign;
4220 app->fnc.auth = do_auth;
4221 app->fnc.decipher = do_decipher;
4222 app->fnc.change_pin = NULL;
4223 app->fnc.check_pin = NULL;