1 /* app-p15.c - The pkcs#15 card application.
2 * Copyright (C) 2005 Free Software Foundation, Inc.
3 * Copyright (C) 2020, 2021 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.
42 #include "../common/i18n.h"
43 #include "../common/tlv.h"
44 #include "../common/host2net.h"
45 #include "../common/openpgpdefs.h"
46 #include "apdu.h" /* fixme: we should move the card detection to a
50 static const char oid_kp_codeSigning[] = "1.3.6.1.5.5.7.3.3";
51 static const char oid_kp_timeStamping[] = "1.3.6.1.5.5.7.3.8";
52 static const char oid_kp_ocspSigning[] = "1.3.6.1.5.5.7.3.9";
53 static const char oid_kp_ms_documentSigning[] = "1.3.6.1.4.1.311.10.3.12";
54 static const char oid_kp_ms_old_documentSigning[] = "1.3.6.1.4.1.311.3.10.3.12";
56 static const char oid_kp_emailProtection[]= "1.3.6.1.5.5.7.3.4";
58 static const char oid_kp_serverAuth[] = "1.3.6.1.5.5.7.3.1";
59 static const char oid_kp_clientAuth[] = "1.3.6.1.5.5.7.3.2";
60 static const char oid_kp_ms_smartcardLogon[] = "1.3.6.1.4.1.311.20.2.2";
62 static const char oid_kp_anyExtendedKeyUsage[] = "2.5.29.37.0";
64 static const char oid_kp_gpgUsageCert[] = "1.3.6.1.4.1.11591.2.6.1";
65 static const char oid_kp_gpgUsageSign[] = "1.3.6.1.4.1.11591.2.6.2";
66 static const char oid_kp_gpgUsageEncr[] = "1.3.6.1.4.1.11591.2.6.3";
67 static const char oid_kp_gpgUsageAuth[] = "1.3.6.1.4.1.11591.2.6.4";
69 /* Types of cards we know and which needs special treatment. */
77 CARD_TYPE_BELPIC /* Belgian eID card specs. */
81 /* The OS of card as specified by card_type_t is not always
82 * sufficient. Thus we also distinguish the actual product build upon
87 CARD_PRODUCT_RSCS, /* Rohde&Schwarz Cybersecurity */
88 CARD_PRODUCT_DTRUST /* D-Trust GmbH (bundesdruckerei.de) */
93 /* A list card types with ATRs noticed with these cards. */
94 #define X(a) ((unsigned char const *)(a))
98 unsigned char const *atr;
100 } card_atr_list[] = {
101 { 19, X("\x3B\xBA\x13\x00\x81\x31\x86\x5D\x00\x64\x05\x0A\x02\x01\x31\x80"
103 CARD_TYPE_TCOS }, /* SLE44 */
104 { 19, X("\x3B\xBA\x14\x00\x81\x31\x86\x5D\x00\x64\x05\x14\x02\x02\x31\x80"
106 CARD_TYPE_TCOS }, /* SLE66S */
107 { 19, X("\x3B\xBA\x96\x00\x81\x31\x86\x5D\x00\x64\x05\x60\x02\x03\x31\x80"
109 CARD_TYPE_TCOS }, /* SLE66P */
110 { 27, X("\x3B\xFF\x94\x00\xFF\x80\xB1\xFE\x45\x1F\x03\x00\x68\xD2\x76\x00"
111 "\x00\x28\xFF\x05\x1E\x31\x80\x00\x90\x00\x23"),
112 CARD_TYPE_MICARDO }, /* German BMI card */
113 { 19, X("\x3B\x6F\x00\xFF\x00\x68\xD2\x76\x00\x00\x28\xFF\x05\x1E\x31\x80"
115 CARD_TYPE_MICARDO }, /* German BMI card (ATR due to reader problem) */
116 { 26, X("\x3B\xFE\x94\x00\xFF\x80\xB1\xFA\x45\x1F\x03\x45\x73\x74\x45\x49"
117 "\x44\x20\x76\x65\x72\x20\x31\x2E\x30\x43"),
118 CARD_TYPE_MICARDO }, /* EstEID (Estonian Big Brother card) */
119 { 11, X("\x3b\xd2\x18\x00\x81\x31\xfe\x58\xc9\x01\x14"),
120 CARD_TYPE_CARDOS_50 }, /* CardOS 5.0 */
121 { 11, X("\x3b\xd2\x18\x00\x81\x31\xfe\x58\xc9\x03\x16"),
122 CARD_TYPE_CARDOS_53 }, /* CardOS 5.3 */
128 /* Macro to test for CardOS 5.0 and 5.3. */
129 #define IS_CARDOS_5(a) ((a)->app_local->card_type == CARD_TYPE_CARDOS_50 \
130 || (a)->app_local->card_type == CARD_TYPE_CARDOS_53)
132 /* The default PKCS-15 home DF */
133 #define DEFAULT_HOME_DF 0x5015
135 /* The AID of PKCS15. */
136 static char const pkcs15_aid[] = { 0xA0, 0, 0, 0, 0x63,
137 0x50, 0x4B, 0x43, 0x53, 0x2D, 0x31, 0x35 };
139 /* The Belgian eID variant - they didn't understood why a shared AID
140 is useful for a standard. Oh well. */
141 static char const pkcs15be_aid[] = { 0xA0, 0, 0, 0x01, 0x77,
142 0x50, 0x4B, 0x43, 0x53, 0x2D, 0x31, 0x35 };
145 /* The PIN types as defined in pkcs#15 v1.1 */
149 PIN_TYPE_ASCII_NUMERIC = 1,
151 PIN_TYPE_HALF_NIBBLE_BCD = 3,
152 PIN_TYPE_ISO9564_1 = 4
156 /* A bit array with for the key usage flags from the
157 commonKeyAttributes. */
158 struct keyusage_flags_s
160 unsigned int encrypt: 1;
161 unsigned int decrypt: 1;
162 unsigned int sign: 1;
163 unsigned int sign_recover: 1;
164 unsigned int wrap: 1;
165 unsigned int unwrap: 1;
166 unsigned int verify: 1;
167 unsigned int verify_recover: 1;
168 unsigned int derive: 1;
169 unsigned int non_repudiation: 1;
171 typedef struct keyusage_flags_s keyusage_flags_t;
174 /* A bit array with for the key access flags from the
175 commonKeyAttributes. */
176 struct keyaccess_flags_s
178 unsigned int any:1; /* Any access flag set. */
179 unsigned int sensitive:1;
180 unsigned int extractable:1;
181 unsigned int always_sensitive:1;
182 unsigned int never_extractable:1;
183 unsigned int local:1;
185 typedef struct keyaccess_flags_s keyaccess_flags_t;
188 /* A bit array with for the gpg usage flags. */
189 struct gpgusage_flags_s
191 unsigned int any:1; /* Any of the next flags are set. */
192 unsigned int cert:1; /* 1.3.6.1.4.1.11591.2.6.1 */
193 unsigned int sign:1; /* 1.3.6.1.4.1.11591.2.6.2 */
194 unsigned int encr:1; /* 1.3.6.1.4.1.11591.2.6.3 */
195 unsigned int auth:1; /* 1.3.6.1.4.1.11591.2.6.4 */
197 typedef struct gpgusage_flags_s gpgusage_flags_t;
200 /* This is an object to store information about a Certificate
201 Directory File (CDF) in a format suitable for further processing by
202 us. To keep memory management, simple we use a linked list of
203 items; i.e. one such object represents one certificate and the list
207 /* Link to next item when used in a linked list. */
208 struct cdf_object_s *next;
210 /* Flags to indicate whether fields are valid. */
211 unsigned int have_off:1;
213 /* Length and allocated buffer with the Id of this object.
214 * This field is used for X.509 in PKCS#11 to make it easier to
215 * match a private key with a certificate. */
217 unsigned char *objid;
219 /* Length and allocated buffer with the authId of this object or
220 NULL if no authID is known. */
222 unsigned char *authid;
224 /* NULL or the malloced label of this object. */
227 /* To avoid reading and parsing a certificate more than once, we
228 * cache the ksba object. */
231 /* The offset and length of the object. They are only valid if
232 HAVE_OFF is true and set to 0 if HAVE_OFF is false. */
233 unsigned long off, len;
235 /* The length of the path as given in the CDF and the path itself.
236 path[0] is the top DF (usually 0x3f00). The path will never be
239 unsigned short path[1];
241 typedef struct cdf_object_s *cdf_object_t;
244 /* This is an object to store information about a Private Key
245 Directory File (PrKDF) in a format suitable for further processing
246 by us. To keep memory management, simple we use a linked list of
247 items; i.e. one such object represents one certificate and the list
249 struct prkdf_object_s
251 /* Link to next item when used in a linked list. */
252 struct prkdf_object_s *next;
254 /* Flags to indicate whether fields are valid. */
255 unsigned int keygrip_valid:1;
256 unsigned int key_reference_valid:1;
257 unsigned int have_off:1;
258 unsigned int have_keytime:1;
260 /* Flag indicating that the corresponding PIN has already been
261 * verified. Note that for cards which are able to return the
262 * verification stus, this flag is not used. */
263 unsigned int pin_verified:1;
265 /* PKCS#15 info whether this is an EC key. Default is RSA. Note
266 * that there is also a KEYALGO field which is derived from the
267 * publick key via Libgcrypt. */
268 unsigned int is_ecc:1;
270 /* The key's usage flags. */
271 keyusage_flags_t usageflags;
273 /* The key's access flags. */
274 keyaccess_flags_t accessflags;
276 /* Extended key usage flags. Only used if .valid is set. This
277 * information is computed from an associated certificate15. */
279 unsigned int valid:1;
285 /* OpenPGP key features for this key. This is taken from special
286 * extended key usage flags different from those tracked in EXTUSAGE
287 * above. There is also no valid flag as in EXTUSAGE. */
288 gpgusage_flags_t gpgusage;
290 /* The keygrip of the key. This is used as a cache. */
291 char keygrip[2*KEYGRIP_LEN+1];
293 /* A malloced algorithm string or NULL if not known. */
296 /* The Gcrypt algo identifier for the key. It is valid if the
297 * keygrip is also valid. See also is_ecc above. */
300 /* The length of the key in bits (e.g. for RSA the length of the
301 * modulus). It is valid if the keygrip is also valid. */
302 unsigned int keynbits;
304 /* The creation time of the key or 0 if not known. */
307 /* Malloced CN from the Subject-DN of the corresponding certificate
308 * or NULL if not known. */
311 /* Malloced SerialNumber from the Subject-DN of the corresponding
312 * certificate or NULL if not known. */
315 /* KDF/KEK parameter for OpenPGP's ECDH. First byte is zero if not
317 unsigned char ecdh_kdf[4];
319 /* Length and allocated buffer with the Id of this object. */
321 unsigned char *objid;
323 /* Length and allocated buffer with the authId of this object or
324 NULL if no authID is known. */
326 unsigned char *authid;
328 /* NULL or the malloced label of this object. */
331 /* The keyReference and a flag telling whether it is valid. */
332 unsigned long key_reference;
334 /* The offset and length of the object. They are only valid if
335 * HAVE_OFF is true otherwise they are set to 0. */
336 unsigned long off, len;
338 /* The length of the path as given in the PrKDF and the path itself.
339 path[0] is the top DF (usually 0x3f00). */
341 unsigned short path[1];
343 typedef struct prkdf_object_s *prkdf_object_t;
344 typedef struct prkdf_object_s *pukdf_object_t;
347 /* This is an object to store information about a Authentication
348 Object Directory File (AODF) in a format suitable for further
349 processing by us. To keep memory management, simple we use a linked
350 list of items; i.e. one such object represents one authentication
351 object and the list the entire AOKDF. */
354 /* Link to next item when used in a linked list. */
355 struct aodf_object_s *next;
357 /* Flags to indicate whether fields are valid. */
358 unsigned int have_off:1;
360 /* Length and allocated buffer with the Id of this object. */
362 unsigned char *objid;
364 /* Length and allocated buffer with the authId of this object or
365 NULL if no authID is known. */
367 unsigned char *authid;
369 /* NULL or the malloced label of this object. */
372 /* The file ID of this AODF. */
378 unsigned int case_sensitive: 1;
379 unsigned int local: 1;
380 unsigned int change_disabled: 1;
381 unsigned int unblock_disabled: 1;
382 unsigned int initialized: 1;
383 unsigned int needs_padding: 1;
384 unsigned int unblocking_pin: 1;
385 unsigned int so_pin: 1;
386 unsigned int disable_allowed: 1;
387 unsigned int integrity_protected: 1;
388 unsigned int confidentiality_protected: 1;
389 unsigned int exchange_ref_data: 1;
395 /* The minimum length of a PIN. */
396 unsigned long min_length;
398 /* The stored length of a PIN. */
399 unsigned long stored_length;
401 /* The maximum length of a PIN and a flag telling whether it is valid. */
402 unsigned long max_length;
403 int max_length_valid;
405 /* The pinReference and a flag telling whether it is valid. */
406 unsigned long pin_reference;
407 int pin_reference_valid;
409 /* The padChar and a flag telling whether it is valid. */
413 /* The offset and length of the object. They are only valid if
414 HAVE_OFF is true and set to 0 if HAVE_OFF is false. */
415 unsigned long off, len;
417 /* The length of the path as given in the Aodf and the path itself.
418 path[0] is the top DF (usually 0x3f00). PATH is optional and thus
419 may be NULL. Malloced.*/
421 unsigned short *path;
423 typedef struct aodf_object_s *aodf_object_t;
426 /* Context local to this application. */
429 /* The home DF. Note, that we don't yet support a multilevel
430 hierarchy. Thus we assume this is directly below the MF. */
431 unsigned short home_df;
433 /* The type of the card's OS. */
434 card_type_t card_type;
436 /* The vendor's product. */
437 card_product_t card_product;
439 /* Flag indicating whether we may use direct path selection. */
440 int direct_path_selection;
442 /* Flag indicating whether the card has any key with a gpgusage set. */
445 /* Structure with the EFIDs of the objects described in the ODF
449 unsigned short private_keys;
450 unsigned short public_keys;
451 unsigned short trusted_public_keys;
452 unsigned short secret_keys;
453 unsigned short certificates;
454 unsigned short trusted_certificates;
455 unsigned short useful_certificates;
456 unsigned short data_objects;
457 unsigned short auth_objects;
460 /* The PKCS#15 serialnumber from EF(TokeiNFo) or NULL. Malloced. */
461 unsigned char *serialno;
464 /* The manufacturerID from the TokenInfo EF. Malloced or NULL. */
465 char *manufacturer_id;
467 /* The label from the TokenInfo EF. Malloced or NULL. */
470 /* The tokenflags from the TokenInfo EF. Malloced or NULL. */
471 unsigned char *tokenflags;
472 unsigned int tokenflagslen;
474 /* Information on all certificates. */
475 cdf_object_t certificate_info;
476 /* Information on all trusted certificates. */
477 cdf_object_t trusted_certificate_info;
478 /* Information on all useful certificates. */
479 cdf_object_t useful_certificate_info;
481 /* Information on all public keys. */
482 prkdf_object_t public_key_info;
484 /* Information on all private keys. */
485 pukdf_object_t private_key_info;
487 /* Information on all authentication objects. */
488 aodf_object_t auth_object_info;
493 /*** Local prototypes. ***/
494 static gpg_error_t select_ef_by_path (app_t app, const unsigned short *path,
496 static gpg_error_t keygrip_from_prkdf (app_t app, prkdf_object_t prkdf);
497 static gpg_error_t readcert_by_cdf (app_t app, cdf_object_t cdf,
498 unsigned char **r_cert, size_t *r_certlen);
499 static char *get_dispserialno (app_t app, prkdf_object_t prkdf);
500 static gpg_error_t do_getattr (app_t app, ctrl_t ctrl, const char *name);
505 cardtype2str (card_type_t cardtype)
509 case CARD_TYPE_UNKNOWN: return "";
510 case CARD_TYPE_TCOS: return "TCOS";
511 case CARD_TYPE_MICARDO: return "Micardo";
512 case CARD_TYPE_CARDOS_50: return "CardOS 5.0";
513 case CARD_TYPE_CARDOS_53: return "CardOS 5.3";
514 case CARD_TYPE_BELPIC: return "Belgian eID";
520 cardproduct2str (card_product_t cardproduct)
524 case CARD_PRODUCT_UNKNOWN: return "";
525 case CARD_PRODUCT_RSCS: return "RSCS";
526 case CARD_PRODUCT_DTRUST: return "D-Trust";
531 /* Release the CDF object A */
533 release_cdflist (cdf_object_t a)
537 cdf_object_t tmp = a->next;
547 /* Release the PrKDF object A. */
549 release_prkdflist (prkdf_object_t a)
553 prkdf_object_t tmp = a->next;
554 xfree (a->keyalgostr);
555 xfree (a->common_name);
556 xfree (a->serial_number);
566 release_pukdflist (pukdf_object_t a)
568 release_prkdflist (a);
571 /* Release just one aodf object. */
573 release_aodf_object (aodf_object_t a)
585 /* Release the AODF list A. */
587 release_aodflist (aodf_object_t a)
591 aodf_object_t tmp = a->next;
592 release_aodf_object (a);
599 release_lists (app_t app)
601 release_cdflist (app->app_local->certificate_info);
602 app->app_local->certificate_info = NULL;
603 release_cdflist (app->app_local->trusted_certificate_info);
604 app->app_local->trusted_certificate_info = NULL;
605 release_cdflist (app->app_local->useful_certificate_info);
606 app->app_local->useful_certificate_info = NULL;
607 release_pukdflist (app->app_local->public_key_info);
608 app->app_local->public_key_info = NULL;
609 release_prkdflist (app->app_local->private_key_info);
610 app->app_local->private_key_info = NULL;
611 release_aodflist (app->app_local->auth_object_info);
612 app->app_local->auth_object_info = NULL;
617 release_tokeninfo (app_t app)
619 xfree (app->app_local->manufacturer_id);
620 app->app_local->manufacturer_id = NULL;
621 xfree (app->app_local->token_label);
622 app->app_local->token_label = NULL;
623 xfree (app->app_local->tokenflags);
624 app->app_local->tokenflags = NULL;
625 xfree (app->app_local->serialno);
626 app->app_local->serialno = NULL;
630 /* Release all local resources. */
632 do_deinit (app_t app)
634 if (app && app->app_local)
637 release_tokeninfo (app);
638 xfree (app->app_local);
639 app->app_local = NULL;
644 /* Do a select and a read for the file with EFID. EFID_DESC is a
645 desctription of the EF to be used with error messages. On success
646 BUFFER and BUFLEN contain the entire content of the EF. The caller
647 must free BUFFER only on success. If EFID is 0 no seelct is done. */
649 select_and_read_binary (app_t app, unsigned short efid, const char *efid_desc,
650 unsigned char **buffer, size_t *buflen)
657 err = select_ef_by_path (app, &efid, 1);
660 log_error ("p15: error selecting %s (0x%04X): %s\n",
661 efid_desc, efid, gpg_strerror (err));
666 err = iso7816_read_binary_ext (app_get_slot (app),
667 0, 0, 0, buffer, buflen, &sw);
669 log_error ("p15: error reading %s (0x%04X): %s (sw=%04X)\n",
670 efid_desc, efid, gpg_strerror (err), sw);
675 /* If EFID is not 0 do a select and then read the record RECNO.
676 * EFID_DESC is a description of the EF to be used with error
677 * messages. On success BUFFER and BUFLEN contain the entire content
678 * of the EF. The caller must free BUFFER only on success. */
680 select_and_read_record (app_t app, unsigned short efid, int recno,
681 const char *efid_desc,
682 unsigned char **buffer, size_t *buflen, int *r_sw)
692 err = select_ef_by_path (app, &efid, 1);
695 log_error ("p15: error selecting %s (0x%04X): %s\n",
696 efid_desc, efid, gpg_strerror (err));
703 err = iso7816_read_record_ext (app_get_slot (app),
704 recno, 1, 0, buffer, buflen, &sw);
707 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
709 else if (err && sw == SW_FILE_STRUCT)
712 log_error ("p15: error reading %s (0x%04X) record %d: %s (sw=%04X)\n",
713 efid_desc, efid, recno, gpg_strerror (err), sw);
718 /* On CardOS with a Linear TLV file structure the records starts
719 * with some tag (often the record number) followed by the length
720 * byte for this record. Detect and remove this prefix. */
721 if (*buflen > 2 && (*buffer)[0] != 0x30 && (*buffer)[1] == *buflen - 2)
723 memmove (*buffer, *buffer + 2, *buflen - 2);
724 *buflen = *buflen - 2;
731 /* This function calls select file to read a file using a complete
732 path which may or may not start at the master file (MF). */
734 select_ef_by_path (app_t app, const unsigned short *path, size_t pathlen)
740 return gpg_error (GPG_ERR_INV_VALUE);
742 /* log_debug ("%s: path=", __func__); */
743 /* for (j=0; j < pathlen; j++) */
744 /* log_printf ("%s%04hX", j? "/":"", path[j]); */
745 /* log_printf ("%s\n",app->app_local->direct_path_selection?" (direct)":"");*/
747 if (app->app_local->direct_path_selection)
749 if (pathlen && *path == 0x3f00 )
752 err = iso7816_select_mf (app_get_slot (app));
754 err = iso7816_select_path (app_get_slot (app), path+1, pathlen-1,
758 err = iso7816_select_path (app_get_slot (app), path, pathlen,
759 app->app_local->home_df);
762 log_error ("p15: error selecting path ");
768 if (pathlen && *path != 0x3f00 )
769 log_error ("p15: warning: relative path select not yet implemented\n");
771 /* FIXME: Use home_df. */
772 for (i=0; i < pathlen; i++)
774 err = iso7816_select_file (app_get_slot (app),
775 path[i], !(i+1 == pathlen));
778 log_error ("p15: error selecting part %d from path ", i);
786 if (pathlen && *path != 0x3f00 )
787 log_printf ("3F00/");
789 log_printf ("%04hX/", app->app_local->home_df);
790 for (j=0; j < pathlen; j++)
791 log_printf ("%s%04hX", j? "/":"", path[j]);
792 log_printf (": %s\n", gpg_strerror (err));
797 /* Parse a cert Id string (or a key Id string) and return the binary
798 object Id string in a newly allocated buffer stored at R_OBJID and
799 R_OBJIDLEN. On Error NULL will be stored there and an error code
800 returned. On success caller needs to free the buffer at R_OBJID. */
802 parse_certid (app_t app, const char *certid,
803 unsigned char **r_objid, size_t *r_objidlen)
808 unsigned char *objid;
814 if (certid[0] != 'P' && strlen (certid) == 40) /* This is a keygrip. */
816 prkdf_object_t prkdf;
818 for (prkdf = app->app_local->private_key_info;
819 prkdf; prkdf = prkdf->next)
820 if (!keygrip_from_prkdf (app, prkdf)
821 && !strcmp (certid, prkdf->keygrip))
823 if (!prkdf || !prkdf->objidlen || !prkdf->objid)
824 return gpg_error (GPG_ERR_NOT_FOUND);
825 objidlen = prkdf->objidlen;
826 objid = xtrymalloc (objidlen);
828 return gpg_error_from_syserror ();
829 memcpy (objid, prkdf->objid, prkdf->objidlen);
831 else /* This is a usual keyref. */
833 if (app->app_local->home_df != DEFAULT_HOME_DF)
834 snprintf (tmpbuf, sizeof tmpbuf, "P15-%04X.",
835 (unsigned int)(app->app_local->home_df & 0xffff));
837 strcpy (tmpbuf, "P15.");
838 if (strncmp (certid, tmpbuf, strlen (tmpbuf)) )
840 if (!strncmp (certid, "P15.", 4)
841 || (!strncmp (certid, "P15-", 4)
842 && hexdigitp (certid+4)
843 && hexdigitp (certid+5)
844 && hexdigitp (certid+6)
845 && hexdigitp (certid+7)
846 && certid[8] == '.'))
847 return gpg_error (GPG_ERR_NOT_FOUND);
848 return gpg_error (GPG_ERR_INV_ID);
850 certid += strlen (tmpbuf);
851 for (s=certid, objidlen=0; hexdigitp (s); s++, objidlen++)
853 if (*s || !objidlen || (objidlen%2))
854 return gpg_error (GPG_ERR_INV_ID);
856 objid = xtrymalloc (objidlen);
858 return gpg_error_from_syserror ();
859 for (s=certid, i=0; i < objidlen; i++, s+=2)
860 objid[i] = xtoi_2 (s);
864 *r_objidlen = objidlen;
869 /* Find a certificate object by its object ID and store a pointer to
872 cdf_object_from_objid (app_t app, size_t objidlen, const unsigned char *objid,
877 for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
878 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
881 for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
882 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
885 for (cdf = app->app_local->useful_certificate_info; cdf; cdf = cdf->next)
886 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
889 return gpg_error (GPG_ERR_NOT_FOUND);
895 /* Find a certificate object by its label and store a pointer to it at
898 cdf_object_from_label (app_t app, const char *label, cdf_object_t *r_cdf)
903 return gpg_error (GPG_ERR_NOT_FOUND);
905 for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
906 if (cdf->label && !strcmp (cdf->label, label))
909 for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
910 if (cdf->label && !strcmp (cdf->label, label))
913 for (cdf = app->app_local->useful_certificate_info; cdf; cdf = cdf->next)
914 if (cdf->label && !strcmp (cdf->label, label))
917 return gpg_error (GPG_ERR_NOT_FOUND);
923 /* Find a certificate object by the certificate ID CERTID and store a
924 * pointer to it at R_CDF. */
926 cdf_object_from_certid (app_t app, const char *certid, cdf_object_t *r_cdf)
930 unsigned char *objid;
932 prkdf_object_t prkdf;
934 err = parse_certid (app, certid, &objid, &objidlen);
938 err = cdf_object_from_objid (app, objidlen, objid, &cdf);
939 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
941 /* Try again by finding the certid in the prkdf and matching by
943 for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
944 if (prkdf->objidlen == objidlen
945 && !memcmp (prkdf->objid, objid, objidlen))
948 err = cdf_object_from_label (app, prkdf->label, &cdf);
958 /* Find a private key object by the key Id string KEYIDSTR and store a
959 pointer to it at R_PRKDF. */
961 prkdf_object_from_keyidstr (app_t app, const char *keyidstr,
962 prkdf_object_t *r_prkdf)
966 unsigned char *objid;
967 prkdf_object_t prkdf;
969 err = parse_certid (app, keyidstr, &objid, &objidlen);
973 for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
974 if (prkdf->objidlen == objidlen && !memcmp (prkdf->objid, objid, objidlen))
978 return gpg_error (GPG_ERR_NOT_FOUND);
986 /* Read and parse the Object Directory File and store away the
987 pointers. ODF_FID shall contain the FID of the ODF.
989 Example of such a file:
991 A0 06 30 04 04 02 60 34 = Private Keys
992 A4 06 30 04 04 02 60 35 = Certificates
993 A5 06 30 04 04 02 60 36 = Trusted Certificates
994 A7 06 30 04 04 02 60 37 = Data Objects
995 A8 06 30 04 04 02 60 38 = Auth Objects
997 These are all PathOrObjects using the path CHOICE element. The
998 paths are octet strings of length 2. Using this Path CHOICE
999 element is recommended, so we only implement that for now.
1002 read_ef_odf (app_t app, unsigned short odf_fid)
1005 unsigned char *buffer, *p;
1007 unsigned short value;
1009 unsigned short home_df = 0;
1012 app->app_local->odf.private_keys = 0;
1013 app->app_local->odf.public_keys = 0;
1014 app->app_local->odf.trusted_public_keys = 0;
1015 app->app_local->odf.secret_keys = 0;
1016 app->app_local->odf.certificates = 0;
1017 app->app_local->odf.trusted_certificates = 0;
1018 app->app_local->odf.useful_certificates = 0;
1019 app->app_local->odf.data_objects = 0;
1020 app->app_local->odf.auth_objects = 0;
1022 err = select_and_read_binary (app, odf_fid, "ODF",
1029 log_error ("p15: error: ODF too short\n");
1031 return gpg_error (GPG_ERR_INV_OBJ);
1034 home_df = app->app_local->home_df;
1036 while (buflen && *p && *p != 0xff)
1039 && (p[0] & 0xf0) == 0xA0
1040 && !memcmp (p+1, "\x06\x30\x04\x04\x02", 5) )
1044 else if ( buflen >= 12
1045 && (p[0] & 0xf0) == 0xA0
1046 && !memcmp (p+1, "\x0a\x30\x08\x04\x06\x3F\x00", 7)
1047 && (!home_df || home_df == ((p[8]<<8)|p[9])) )
1049 /* FIXME: Is this hack still required? */
1050 /* If we do not know the home DF, we take it from the first
1051 * ODF object. Here are sample values:
1052 * a0 0a 30 08 0406 3f00 5015 4401
1053 * a1 0a 30 08 0406 3f00 5015 4411
1054 * a4 0a 30 08 0406 3f00 5015 4441
1055 * a5 0a 30 08 0406 3f00 5015 4451
1056 * a8 0a 30 08 0406 3f00 5015 4481
1060 home_df = ((p[8]<<8)|p[9]);
1061 app->app_local->home_df = home_df;
1062 log_info ("p15: application directory detected as 0x%04hX\n",
1064 /* We assume that direct path selection is possible. */
1065 app->app_local->direct_path_selection = 1;
1068 /* We only allow a full path if all files are at the same
1069 level and below the home directory. To extend this we
1070 would need to make use of new data type capable of
1071 keeping a full path. */
1076 log_printhex (p, buflen, "p15: ODF format not supported:");
1078 return gpg_error (GPG_ERR_INV_OBJ);
1080 switch ((p[0] & 0x0f))
1082 case 0: value = app->app_local->odf.private_keys; break;
1083 case 1: value = app->app_local->odf.public_keys; break;
1084 case 2: value = app->app_local->odf.trusted_public_keys; break;
1085 case 3: value = app->app_local->odf.secret_keys; break;
1086 case 4: value = app->app_local->odf.certificates; break;
1087 case 5: value = app->app_local->odf.trusted_certificates; break;
1088 case 6: value = app->app_local->odf.useful_certificates; break;
1089 case 7: value = app->app_local->odf.data_objects; break;
1090 case 8: value = app->app_local->odf.auth_objects; break;
1091 default: value = 0; break;
1095 log_error ("p15: duplicate object type %d in ODF ignored\n",
1099 value = ((p[offset] << 8) | p[offset+1]);
1100 switch ((p[0] & 0x0f))
1102 case 0: app->app_local->odf.private_keys = value; break;
1103 case 1: app->app_local->odf.public_keys = value; break;
1104 case 2: app->app_local->odf.trusted_public_keys = value; break;
1105 case 3: app->app_local->odf.secret_keys = value; break;
1106 case 4: app->app_local->odf.certificates = value; break;
1107 case 5: app->app_local->odf.trusted_certificates = value; break;
1108 case 6: app->app_local->odf.useful_certificates = value; break;
1109 case 7: app->app_local->odf.data_objects = value; break;
1110 case 8: app->app_local->odf.auth_objects = value; break;
1112 log_error ("p15: unknown object type %d in ODF ignored\n",
1117 if (buflen < offset)
1125 /* Print a warning if non-null garbage is left over. */
1126 for (n=0; n < buflen && !p[n]; n++)
1130 log_info ("p15: warning: garbage detected at end of ODF: ");
1131 log_printhex (p, buflen, "");
1140 /* Helper for the read_ef_foo functions to read the first record or
1141 * the entire data. */
1143 read_first_record (app_t app, unsigned short fid, const char *fid_desc,
1144 unsigned char **r_buffer, size_t *r_buflen,
1145 int *r_use_read_record)
1152 *r_use_read_record = 0;
1155 return gpg_error (GPG_ERR_NO_DATA); /* No such file. */
1157 if (IS_CARDOS_5 (app))
1159 *r_use_read_record = 1;
1160 err = select_and_read_record (app, fid, 1, fid_desc,
1161 r_buffer, r_buflen, &sw);
1162 if (err && sw == SW_FILE_STRUCT)
1164 *r_use_read_record = 0;
1165 err = select_and_read_binary (app, 0, fid_desc, r_buffer, r_buflen);
1169 err = select_and_read_binary (app, fid, fid_desc, r_buffer, r_buflen);
1171 /* We get a not_found state in read_record mode if the select
1172 * succeeded but reading the record failed. Map that to no_data
1173 * which is what the caller of the read_ef_foo functions expect. */
1174 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1175 err = gpg_error (GPG_ERR_NO_DATA);
1181 /* Parse the BIT STRING with the keyUsageFlags from the
1182 CommonKeyAttributes. */
1184 parse_keyusage_flags (const unsigned char *der, size_t derlen,
1185 keyusage_flags_t *usageflags)
1187 unsigned int bits, mask;
1188 int i, unused, full;
1190 memset (usageflags, 0, sizeof *usageflags);
1192 return gpg_error (GPG_ERR_INV_OBJ);
1194 unused = *der++; derlen--;
1195 if ((!derlen && unused) || unused/8 > derlen)
1196 return gpg_error (GPG_ERR_ENCODING_PROBLEM);
1197 full = derlen - (unused+7)/8;
1200 for (i=1; unused; i <<= 1, unused--)
1206 bits = *der++; derlen--;
1217 if ((bits & 0x80)) usageflags->encrypt = 1;
1218 if ((bits & 0x40)) usageflags->decrypt = 1;
1219 if ((bits & 0x20)) usageflags->sign = 1;
1220 if ((bits & 0x10)) usageflags->sign_recover = 1;
1221 if ((bits & 0x08)) usageflags->wrap = 1;
1222 if ((bits & 0x04)) usageflags->unwrap = 1;
1223 if ((bits & 0x02)) usageflags->verify = 1;
1224 if ((bits & 0x01)) usageflags->verify_recover = 1;
1229 bits = *der++; derlen--;
1239 if ((bits & 0x80)) usageflags->derive = 1;
1240 if ((bits & 0x40)) usageflags->non_repudiation = 1;
1247 dump_keyusage_flags (keyusage_flags_t usageflags)
1251 log_info ("p15: usage=");
1252 if (usageflags.encrypt)
1253 log_printf ("%sencrypt", s), s = ",";
1254 if (usageflags.decrypt)
1255 log_printf ("%sdecrypt", s), s = ",";
1256 if (usageflags.sign )
1257 log_printf ("%ssign", s), s = ",";
1258 if (usageflags.sign_recover)
1259 log_printf ("%ssign_recover", s), s = ",";
1260 if (usageflags.wrap )
1261 log_printf ("%swrap", s), s = ",";
1262 if (usageflags.unwrap )
1263 log_printf ("%sunwrap", s), s = ",";
1264 if (usageflags.verify )
1265 log_printf ("%sverify", s), s = ",";
1266 if (usageflags.verify_recover)
1267 log_printf ("%sverify_recover", s), s = ",";
1268 if (usageflags.derive )
1269 log_printf ("%sderive", s), s = ",";
1270 if (usageflags.non_repudiation)
1271 log_printf ("%snon_repudiation", s), s = ",";
1276 dump_keyaccess_flags (keyaccess_flags_t accessflags)
1280 log_info ("p15: access=");
1281 if (accessflags.sensitive)
1282 log_printf ("%ssensitive", s), s = ",";
1283 if (accessflags.extractable)
1284 log_printf ("%sextractable", s), s = ",";
1285 if (accessflags.always_sensitive)
1286 log_printf ("%salways_sensitive", s), s = ",";
1287 if (accessflags.never_extractable)
1288 log_printf ("%snever_extractable", s), s = ",";
1289 if (accessflags.local)
1290 log_printf ("%slocal", s), s = ",";
1295 dump_gpgusage_flags (gpgusage_flags_t gpgusage)
1299 log_info ("p15: gpgusage=");
1301 log_printf ("%scert", s), s = ",";
1303 log_printf ("%ssign", s), s = ",";
1305 log_printf ("%sencr", s), s = ",";
1307 log_printf ("%sauth", s), s = ",";
1311 /* Parse the BIT STRING with the keyAccessFlags from the
1312 CommonKeyAttributes. */
1314 parse_keyaccess_flags (const unsigned char *der, size_t derlen,
1315 keyaccess_flags_t *accessflags)
1317 unsigned int bits, mask;
1318 int i, unused, full;
1320 memset (accessflags, 0, sizeof *accessflags);
1322 return gpg_error (GPG_ERR_INV_OBJ);
1324 unused = *der++; derlen--;
1325 if ((!derlen && unused) || unused/8 > derlen)
1326 return gpg_error (GPG_ERR_ENCODING_PROBLEM);
1327 full = derlen - (unused+7)/8;
1330 for (i=1; unused; i <<= 1, unused--)
1336 bits = *der++; derlen--;
1347 if ((bits & 0x10)) accessflags->local = 1;
1348 if ((bits & 0x08)) accessflags->never_extractable = 1;
1349 if ((bits & 0x04)) accessflags->always_sensitive = 1;
1350 if ((bits & 0x02)) accessflags->extractable = 1;
1351 if ((bits & 0x01)) accessflags->sensitive = 1;
1353 accessflags->any = 1;
1358 /* Parse the commonObjectAttributes and store a malloced authid at
1359 * (r_authid,r_authidlen). (NULL,0) is stored on error or if no
1360 * authid is found. IF R_LABEL is not NULL the label is stored there
1361 * as a malloced string (spaces are replaced by underscores).
1364 * 2 30 17: SEQUENCE { -- commonObjectAttributes
1365 * 4 0C 8: UTF8String 'SK.CH.DS' -- label
1366 * 14 03 2: BIT STRING 6 unused bits
1368 * 18 04 1: OCTET STRING --authid
1373 parse_common_obj_attr (unsigned char const **buffer, size_t *size,
1374 unsigned char **r_authid, size_t *r_authidlen,
1379 int class, tag, constructed, ndef;
1380 size_t objlen, hdrlen, nnn;
1381 const unsigned char *ppp;
1391 err = parse_ber_header (buffer, size, &class, &tag, &constructed,
1392 &ndef, &objlen, &hdrlen);
1393 if (!err && (objlen > *size || tag != TAG_SEQUENCE))
1394 err = gpg_error (GPG_ERR_INV_OBJ);
1403 /* Search the optional AuthId. */
1406 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1407 &ndef, &objlen, &hdrlen);
1408 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1409 err = gpg_error (GPG_ERR_INV_OBJ);
1413 if (tag == TAG_UTF8_STRING)
1417 *r_label = xtrymalloc (objlen + 1);
1420 err = gpg_error_from_syserror ();
1423 memcpy (*r_label, ppp, objlen);
1424 (*r_label)[objlen] = 0;
1425 /* We don't want spaces in the labels due to the properties
1427 for (p = *r_label; *p; p++)
1428 if (ascii_isspace (*p))
1436 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1437 &ndef, &objlen, &hdrlen);
1438 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1439 err = gpg_error (GPG_ERR_INV_OBJ);
1443 if (tag == TAG_BIT_STRING)
1445 ppp += objlen; /* Skip the CommonObjectFlags. */
1449 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1450 &ndef, &objlen, &hdrlen);
1451 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1452 err = gpg_error (GPG_ERR_INV_OBJ);
1456 if (tag == TAG_OCTET_STRING && objlen)
1458 *r_authid = xtrymalloc (objlen);
1461 err = gpg_error_from_syserror ();
1464 memcpy (*r_authid, ppp, objlen);
1465 *r_authidlen = objlen;
1469 if (ignore_eof && gpg_err_code (err) == GPG_ERR_EOF)
1472 log_error ("p15: error parsing commonObjectAttributes at %d: %s\n",
1473 where, gpg_strerror (err));
1485 /* Parse the commonKeyAttributes. On success store the objid at
1486 * (R_OBJID/R_OBJIDLEN), sets the key usage flags at USAGEFLAGS and
1487 * the optiona key refrence at R_KEY_REFERENCE. The latter is only
1488 * valid if true is also stored at R_KEY_REFERENCE_VALID.
1492 * 21 30 12: SEQUENCE { -- commonKeyAttributes
1493 * 23 04 1: OCTET STRING
1495 * 26 03 3: BIT STRING 6 unused bits
1496 * : '1000000000'B (bit 9)
1497 * 31 02 2: INTEGER 80 -- keyReference (optional)
1501 parse_common_key_attr (unsigned char const **buffer, size_t *size,
1502 unsigned char **r_objid, size_t *r_objidlen,
1503 keyusage_flags_t *usageflags,
1504 keyaccess_flags_t *accessflags,
1505 unsigned long *r_key_reference,
1506 int *r_key_reference_valid)
1510 int class, tag, constructed, ndef;
1511 size_t objlen, hdrlen, nnn;
1512 const unsigned char *ppp;
1515 const unsigned char *objid = NULL;
1517 unsigned long key_reference = 0;
1518 int key_reference_valid = 0;
1522 memset (usageflags, 0, sizeof *usageflags);
1523 memset (accessflags, 0, sizeof *accessflags);
1524 *r_key_reference_valid = 0;
1527 err = parse_ber_header (buffer, size, &class, &tag, &constructed,
1528 &ndef, &objlen, &hdrlen);
1529 if (!err && (objlen > *size || tag != TAG_SEQUENCE))
1530 err = gpg_error (GPG_ERR_INV_OBJ);
1541 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1542 &ndef, &objlen, &hdrlen);
1543 if (!err && (objlen > nnn
1544 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
1545 err = gpg_error (GPG_ERR_INV_OBJ);
1554 /* Get the KeyUsageFlags. */
1556 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1557 &ndef, &objlen, &hdrlen);
1558 if (!err && (objlen > nnn
1559 || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
1560 err = gpg_error (GPG_ERR_INV_OBJ);
1564 err = parse_keyusage_flags (ppp, objlen, usageflags);
1570 ignore_eof = 1; /* Remaining items are optional. */
1572 /* Find the keyReference */
1574 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1575 &ndef, &objlen, &hdrlen);
1576 if (!err && objlen > nnn)
1577 err = gpg_error (GPG_ERR_INV_OBJ);
1581 if (class == CLASS_UNIVERSAL && tag == TAG_BOOLEAN)
1583 /* Skip the native element. */
1587 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1588 &ndef, &objlen, &hdrlen);
1589 if (!err && objlen > nnn)
1590 err = gpg_error (GPG_ERR_INV_OBJ);
1594 if (class == CLASS_UNIVERSAL && tag == TAG_BIT_STRING)
1596 /* These are the keyAccessFlags. */
1597 err = parse_keyaccess_flags (ppp, objlen, accessflags);
1603 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1604 &ndef, &objlen, &hdrlen);
1605 if (!err && objlen > nnn)
1606 err = gpg_error (GPG_ERR_INV_OBJ);
1610 if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
1612 /* This is the keyReference. */
1613 for (ul=0; objlen; objlen--)
1616 ul |= (*ppp++) & 0xff;
1620 key_reference_valid = 1;
1624 if (ignore_eof && gpg_err_code (err) == GPG_ERR_EOF)
1629 if (!objid || !objidlen)
1630 err = gpg_error (GPG_ERR_INV_OBJ);
1633 *r_objid = xtrymalloc (objidlen);
1635 err = gpg_error_from_syserror ();
1638 memcpy (*r_objid, objid, objidlen);
1639 *r_objidlen = objidlen;
1643 if (!err && key_reference_valid)
1645 *r_key_reference = key_reference;
1646 *r_key_reference_valid = 1;
1650 log_error ("p15: error parsing commonKeyAttributes at %d: %s\n",
1651 where, gpg_strerror (err));
1657 /* Read and parse the Private Key Directory Files.
1661 * SEQUENCE { -- commonObjectAttributes
1662 * UTF8String 'SK.CH.DS'
1663 * BIT STRING 6 unused bits
1664 * '01'B (bit 0) -- flags: non-modifiable,private
1665 * OCTET STRING --authid
1668 * SEQUENCE { -- commonKeyAttributes
1671 * BIT STRING 6 unused bits
1672 * '1000000000'B (bit 9) -- keyusage: non-repudiation
1673 * INTEGER 80 -- keyReference (optional)
1675 * [1] { -- keyAttributes
1676 * SEQUENCE { -- privateRSAKeyAttributes
1677 * SEQUENCE { -- objectValue
1678 * OCTET STRING --path
1681 * INTEGER 1024 -- modulus
1686 * Sample part for EC objects:
1687 * [1] { -- keyAttributes
1688 * [1] { -- privateECkeyAttributes
1689 * SEQUENCE { -- objectValue
1691 * OCTET STRING 50 72 4B 03
1693 * INTEGER 33 -- Not in PKCS#15v1.1, need to buy 7816-15?
1698 read_ef_prkdf (app_t app, unsigned short fid, prkdf_object_t *result)
1701 unsigned char *buffer;
1703 const unsigned char *p;
1704 size_t n, objlen, hdrlen;
1705 int class, tag, constructed, ndef;
1706 prkdf_object_t prkdflist = NULL;
1709 unsigned char *authid = NULL;
1710 size_t authidlen = 0;
1711 unsigned char *objid = NULL;
1712 size_t objidlen = 0;
1716 err = read_first_record (app, fid, "PrKDF", &buffer, &buflen, &record_mode);
1723 /* Loop over the records. We stop as soon as we detect a new record
1724 starting with 0x00 or 0xff as these values are commonly used to
1725 pad data blocks and are no valid ASN.1 encoding. Note the
1726 special handling for record mode at the end of the loop. */
1727 while (n && *p && *p != 0xff)
1729 const unsigned char *pp;
1732 const char *errstr = NULL;
1733 prkdf_object_t prkdf = NULL;
1735 keyusage_flags_t usageflags;
1736 keyaccess_flags_t accessflags;
1737 unsigned long key_reference = 0;
1738 int key_reference_valid = 0;
1742 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1743 &ndef, &objlen, &hdrlen);
1746 else if (objlen > n)
1747 err = gpg_error (GPG_ERR_INV_OBJ);
1748 else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
1749 ; /* PrivateRSAKeyAttributes */
1750 else if (class == CLASS_CONTEXT)
1754 case 0: is_ecc = 1; break; /* PrivateECKeyAttributes */
1755 case 1: errstr = "DH key objects are not supported"; break;
1756 case 2: errstr = "DSA key objects are not supported"; break;
1757 case 3: errstr = "KEA key objects are not supported"; break;
1758 default: errstr = "unknown privateKeyObject"; break;
1765 err = gpg_error (GPG_ERR_INV_OBJ);
1771 log_error ("p15: error parsing PrKDF record: %s\n",
1772 gpg_strerror (err));
1781 /* Parse the commonObjectAttributes. */
1785 err = parse_common_obj_attr (&pp, &nn, &authid, &authidlen, &label);
1789 /* Parse the commonKeyAttributes. */
1792 err = parse_common_key_attr (&pp, &nn,
1794 &usageflags, &accessflags,
1795 &key_reference, &key_reference_valid);
1800 /* Skip commonPrivateKeyAttributes. */
1802 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1803 &ndef, &objlen, &hdrlen);
1804 if (!err && objlen > nn)
1805 err = gpg_error (GPG_ERR_INV_OBJ);
1808 if (class == CLASS_CONTEXT && tag == 0)
1814 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1815 &ndef, &objlen, &hdrlen);
1817 /* Parse the keyAttributes. */
1818 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1819 err = gpg_error (GPG_ERR_INV_OBJ);
1825 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1826 &ndef, &objlen, &hdrlen);
1829 else if (!err && objlen > nn)
1830 err = gpg_error (GPG_ERR_INV_OBJ);
1831 else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
1832 ; /* A typeAttribute always starts with a sequence. */
1834 err = gpg_error (GPG_ERR_INV_OBJ);
1840 /* Check that the reference is a Path object. */
1842 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1843 &ndef, &objlen, &hdrlen);
1844 if (!err && objlen > nn)
1845 err = gpg_error (GPG_ERR_INV_OBJ);
1848 if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
1850 errstr = "unsupported reference type";
1855 /* Parse the Path object. */
1857 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1858 &ndef, &objlen, &hdrlen);
1859 if (!err && objlen > nn)
1860 err = gpg_error (GPG_ERR_INV_OBJ);
1864 /* Make sure that the next element is a non zero path and of
1865 even length (FID are two bytes each). */
1866 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
1867 || !objlen || (objlen & 1) )
1869 errstr = "invalid path reference";
1873 /* Create a new PrKDF list item. */
1874 prkdf = xtrycalloc (1, (sizeof *prkdf
1875 - sizeof(unsigned short)
1876 + objlen/2 * sizeof(unsigned short)));
1879 err = gpg_error_from_syserror ();
1882 prkdf->is_ecc = is_ecc;
1884 prkdf->objidlen = objidlen;
1885 prkdf->objid = objid;
1889 prkdf->authidlen = authidlen;
1890 prkdf->authid = authid;
1895 prkdf->label = label;
1899 prkdf->pathlen = objlen/2;
1900 for (i=0; i < prkdf->pathlen; i++, pp += 2, nn -= 2)
1901 prkdf->path[i] = ((pp[0] << 8) | pp[1]);
1903 prkdf->usageflags = usageflags;
1904 prkdf->accessflags = accessflags;
1905 prkdf->key_reference = key_reference;
1906 prkdf->key_reference_valid = key_reference_valid;
1910 /* An index and length follows. */
1911 prkdf->have_off = 1;
1913 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1914 &ndef, &objlen, &hdrlen);
1915 if (!err && (objlen > nn
1916 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1917 err = gpg_error (GPG_ERR_INV_OBJ);
1921 for (ul=0; objlen; objlen--)
1924 ul |= (*pp++) & 0xff;
1930 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1931 &ndef, &objlen, &hdrlen);
1932 if (!err && (objlen > nn
1933 || class != CLASS_CONTEXT || tag != 0))
1934 err = gpg_error (GPG_ERR_INV_OBJ);
1938 for (ul=0; objlen; objlen--)
1941 ul |= (*pp++) & 0xff;
1947 /* The info is printed later in read_p15_info because we also
1948 * want to look at the certificates. */
1950 /* Put it into the list. */
1951 prkdf->next = prkdflist;
1954 goto next_record; /* Ready with this record. */
1957 log_error ("p15: error parsing PrKDF record at %d: %s - skipped\n",
1958 where, errstr? errstr : gpg_strerror (err));
1961 xfree (prkdf->objid);
1962 xfree (prkdf->authid);
1963 xfree (prkdf->label);
1969 /* If the card uses a record oriented file structure, read the
1970 * next record. Otherwise we keep on parsing the current buffer. */
1974 xfree (buffer); buffer = NULL;
1975 err = select_and_read_record (app, 0, recno, "PrKDF",
1976 &buffer, &buflen, NULL);
1978 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1985 } /* End looping over all records. */
1993 release_prkdflist (prkdflist);
1995 *result = prkdflist;
2000 /* Read and parse the Public Keys Directory File. */
2002 read_ef_pukdf (app_t app, unsigned short fid, pukdf_object_t *result)
2005 unsigned char *buffer;
2007 const unsigned char *p;
2008 size_t n, objlen, hdrlen;
2009 int class, tag, constructed, ndef;
2010 pukdf_object_t pukdflist = NULL;
2013 unsigned char *authid = NULL;
2014 size_t authidlen = 0;
2015 unsigned char *objid = NULL;
2016 size_t objidlen = 0;
2020 err = read_first_record (app, fid, "PuKDF", &buffer, &buflen, &record_mode);
2027 /* Loop over the records. We stop as soon as we detect a new record
2028 * starting with 0x00 or 0xff as these values are commonly used to
2029 * pad data blocks and are no valid ASN.1 encoding. Note the
2030 * special handling for record mode at the end of the loop. */
2031 while (n && *p && *p != 0xff)
2033 const unsigned char *pp;
2036 const char *errstr = NULL;
2037 pukdf_object_t pukdf = NULL;
2039 keyusage_flags_t usageflags;
2040 keyaccess_flags_t accessflags;
2041 unsigned long key_reference = 0;
2042 int key_reference_valid = 0;
2045 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2046 &ndef, &objlen, &hdrlen);
2049 else if (objlen > n)
2050 err = gpg_error (GPG_ERR_INV_OBJ);
2051 else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
2052 ; /* PublicRSAKeyAttributes */
2053 else if (class == CLASS_CONTEXT)
2057 case 0: break; /* EC key object */
2058 case 1: errstr = "DH key objects are not supported"; break;
2059 case 2: errstr = "DSA key objects are not supported"; break;
2060 case 3: errstr = "KEA key objects are not supported"; break;
2061 default: errstr = "unknown publicKeyObject"; break;
2068 err = gpg_error (GPG_ERR_INV_OBJ);
2074 log_error ("p15: error parsing PuKDF record: %s\n",
2075 gpg_strerror (err));
2084 /* Parse the commonObjectAttributes. */
2088 err = parse_common_obj_attr (&pp, &nn, &authid, &authidlen, &label);
2092 /* Parse the commonKeyAttributes. */
2095 err = parse_common_key_attr (&pp, &nn,
2097 &usageflags, &accessflags,
2098 &key_reference, &key_reference_valid);
2103 /* Parse the subClassAttributes. */
2105 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2106 &ndef, &objlen, &hdrlen);
2107 if (!err && objlen > nn)
2108 err = gpg_error (GPG_ERR_INV_OBJ);
2111 if (class == CLASS_CONTEXT && tag == 0)
2113 /* Skip this CommonPublicKeyAttribute. */
2118 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2119 &ndef, &objlen, &hdrlen);
2121 /* We expect a typeAttribute. */
2122 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
2123 err = gpg_error (GPG_ERR_INV_OBJ);
2125 goto parse_error; /* No typeAttribute. */
2129 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2130 &ndef, &objlen, &hdrlen);
2133 else if (!err && objlen > nn)
2134 err = gpg_error (GPG_ERR_INV_OBJ);
2135 else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
2136 ; /* A typeAttribute always starts with a sequence. */
2138 err = gpg_error (GPG_ERR_INV_OBJ);
2144 /* Check that the reference is a Path object. */
2146 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2147 &ndef, &objlen, &hdrlen);
2148 if (!err && objlen > nn)
2149 err = gpg_error (GPG_ERR_INV_OBJ);
2152 if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
2154 errstr = "unsupported reference type";
2159 /* Parse the Path object. */
2161 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2162 &ndef, &objlen, &hdrlen);
2163 if (!err && objlen > nn)
2164 err = gpg_error (GPG_ERR_INV_OBJ);
2168 /* Make sure that the next element is a non zero path and of
2169 even length (FID are two bytes each). */
2170 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
2171 || !objlen || (objlen & 1) )
2173 errstr = "invalid path reference";
2177 /* Create a new PuKDF list item. */
2178 pukdf = xtrycalloc (1, (sizeof *pukdf
2179 - sizeof(unsigned short)
2180 + objlen/2 * sizeof(unsigned short)));
2183 err = gpg_error_from_syserror ();
2186 pukdf->objidlen = objidlen;
2187 pukdf->objid = objid;
2191 pukdf->authidlen = authidlen;
2192 pukdf->authid = authid;
2197 pukdf->label = label;
2201 pukdf->pathlen = objlen/2;
2202 for (i=0; i < pukdf->pathlen; i++, pp += 2, nn -= 2)
2203 pukdf->path[i] = ((pp[0] << 8) | pp[1]);
2205 pukdf->usageflags = usageflags;
2206 pukdf->accessflags = accessflags;
2207 pukdf->key_reference = key_reference;
2208 pukdf->key_reference_valid = key_reference_valid;
2212 /* An index and length follows. */
2213 pukdf->have_off = 1;
2215 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2216 &ndef, &objlen, &hdrlen);
2217 if (!err && (objlen > nn
2218 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
2219 err = gpg_error (GPG_ERR_INV_OBJ);
2223 for (ul=0; objlen; objlen--)
2226 ul |= (*pp++) & 0xff;
2232 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2233 &ndef, &objlen, &hdrlen);
2234 if (!err && (objlen > nn
2235 || class != CLASS_CONTEXT || tag != 0))
2236 err = gpg_error (GPG_ERR_INV_OBJ);
2240 for (ul=0; objlen; objlen--)
2243 ul |= (*pp++) & 0xff;
2252 log_info ("p15: PuKDF %04hX: id=", fid);
2253 for (i=0; i < pukdf->objidlen; i++)
2254 log_printf ("%02X", pukdf->objid[i]);
2256 log_printf (" (%s)", pukdf->label);
2257 log_info ("p15: path=");
2258 for (i=0; i < pukdf->pathlen; i++)
2259 log_printf ("%s%04hX", i?"/":"",pukdf->path[i]);
2260 if (pukdf->have_off)
2261 log_printf ("[%lu/%lu]", pukdf->off, pukdf->len);
2264 log_printf (" authid=");
2265 for (i=0; i < pukdf->authidlen; i++)
2266 log_printf ("%02X", pukdf->authid[i]);
2268 if (pukdf->key_reference_valid)
2269 log_printf (" keyref=0x%02lX", pukdf->key_reference);
2270 if (pukdf->accessflags.any)
2271 dump_keyaccess_flags (pukdf->accessflags);
2272 dump_keyusage_flags (pukdf->usageflags);
2276 /* Put it into the list. */
2277 pukdf->next = pukdflist;
2280 goto next_record; /* Ready with this record. */
2283 log_error ("p15: error parsing PuKDF record at %d: %s - skipped\n",
2284 where, errstr? errstr : gpg_strerror (err));
2287 xfree (pukdf->objid);
2288 xfree (pukdf->authid);
2289 xfree (pukdf->label);
2295 /* If the card uses a record oriented file structure, read the
2296 * next record. Otherwise we keep on parsing the current buffer. */
2300 xfree (buffer); buffer = NULL;
2301 err = select_and_read_record (app, 0, recno, "PuKDF",
2302 &buffer, &buflen, NULL);
2304 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2311 } /* End looping over all records. */
2319 release_pukdflist (pukdflist);
2321 *result = pukdflist;
2326 /* Read and parse the Certificate Directory Files identified by FID.
2327 On success a newlist of CDF object gets stored at RESULT and the
2328 caller is then responsible of releasing this list. On error a
2329 error code is returned and RESULT won't get changed. */
2331 read_ef_cdf (app_t app, unsigned short fid, int cdftype, cdf_object_t *result)
2334 unsigned char *buffer;
2336 const unsigned char *p;
2337 size_t n, objlen, hdrlen;
2338 int class, tag, constructed, ndef;
2339 cdf_object_t cdflist = NULL;
2342 unsigned char *authid = NULL;
2343 size_t authidlen = 0;
2347 err = read_first_record (app, fid, "CDF", &buffer, &buflen, &record_mode);
2354 /* Loop over the records. We stop as soon as we detect a new record
2355 starting with 0x00 or 0xff as these values are commonly used to
2356 pad data blocks and are no valid ASN.1 encoding. Note the
2357 special handling for record mode at the end of the loop. */
2358 while (n && *p && *p != 0xff)
2360 const unsigned char *pp;
2363 const char *errstr = NULL;
2364 cdf_object_t cdf = NULL;
2366 const unsigned char *objid;
2369 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2370 &ndef, &objlen, &hdrlen);
2371 if (!err && (objlen > n || tag != TAG_SEQUENCE))
2372 err = gpg_error (GPG_ERR_INV_OBJ);
2375 log_error ("p15: error parsing CDF record: %s\n", gpg_strerror (err));
2383 /* Parse the commonObjectAttributes. */
2387 err = parse_common_obj_attr (&pp, &nn, &authid, &authidlen, &label);
2391 /* Parse the commonCertificateAttributes. */
2393 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2394 &ndef, &objlen, &hdrlen);
2395 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
2396 err = gpg_error (GPG_ERR_INV_OBJ);
2400 const unsigned char *ppp = pp;
2401 size_t nnn = objlen;
2408 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
2409 &ndef, &objlen, &hdrlen);
2410 if (!err && (objlen > nnn
2411 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
2412 err = gpg_error (GPG_ERR_INV_OBJ);
2419 /* Parse the certAttribute. */
2421 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2422 &ndef, &objlen, &hdrlen);
2423 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
2424 err = gpg_error (GPG_ERR_INV_OBJ);
2430 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2431 &ndef, &objlen, &hdrlen);
2432 if (!err && (objlen > nn
2433 || class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE))
2434 err = gpg_error (GPG_ERR_INV_OBJ);
2439 /* Check that the reference is a Path object. */
2441 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2442 &ndef, &objlen, &hdrlen);
2443 if (!err && objlen > nn)
2444 err = gpg_error (GPG_ERR_INV_OBJ);
2447 if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
2449 errstr = "unsupported reference type";
2454 /* Parse the Path object. */
2456 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2457 &ndef, &objlen, &hdrlen);
2458 if (!err && objlen > nn)
2459 err = gpg_error (GPG_ERR_INV_OBJ);
2463 /* Make sure that the next element is a non zero path and of
2464 even length (FID are two bytes each). */
2465 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
2466 || !objlen || (objlen & 1) )
2468 errstr = "invalid path reference";
2471 /* Create a new CDF list item. */
2472 cdf = xtrycalloc (1, (sizeof *cdf
2473 - sizeof(unsigned short)
2474 + objlen/2 * sizeof(unsigned short)));
2477 err = gpg_error_from_syserror ();
2482 cdf->authidlen = authidlen;
2483 cdf->authid = authid;
2492 cdf->objidlen = objidlen;
2493 cdf->objid = xtrymalloc (objidlen);
2496 err = gpg_error_from_syserror ();
2500 memcpy (cdf->objid, objid, objidlen);
2502 cdf->pathlen = objlen/2;
2503 for (i=0; i < cdf->pathlen; i++, pp += 2, nn -= 2)
2504 cdf->path[i] = ((pp[0] << 8) | pp[1]);
2508 /* An index and length follows. */
2511 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2512 &ndef, &objlen, &hdrlen);
2513 if (!err && (objlen > nn
2514 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
2515 err = gpg_error (GPG_ERR_INV_OBJ);
2519 for (ul=0; objlen; objlen--)
2522 ul |= (*pp++) & 0xff;
2528 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2529 &ndef, &objlen, &hdrlen);
2530 if (!err && (objlen > nn
2531 || class != CLASS_CONTEXT || tag != 0))
2532 err = gpg_error (GPG_ERR_INV_OBJ);
2536 for (ul=0; objlen; objlen--)
2539 ul |= (*pp++) & 0xff;
2547 log_info ("p15: CDF-%c %04hX: id=", cdftype, fid);
2548 for (i=0; i < cdf->objidlen; i++)
2549 log_printf ("%02X", cdf->objid[i]);
2551 log_printf (" (%s)", cdf->label);
2552 log_info ("p15: path=");
2553 for (i=0; i < cdf->pathlen; i++)
2554 log_printf ("%s%04hX", i?"/":"", cdf->path[i]);
2556 log_printf ("[%lu/%lu]", cdf->off, cdf->len);
2559 log_printf (" authid=");
2560 for (i=0; i < cdf->authidlen; i++)
2561 log_printf ("%02X", cdf->authid[i]);
2566 /* Put it into the list. */
2567 cdf->next = cdflist;
2570 goto next_record; /* Ready with this record. */
2573 log_error ("p15: error parsing CDF record at %d: %s - skipped\n",
2574 where, errstr? errstr : gpg_strerror (err));
2581 /* If the card uses a record oriented file structure, read the
2582 * next record. Otherwise we keep on parsing the current buffer. */
2586 xfree (buffer); buffer = NULL;
2587 err = select_and_read_record (app, 0, recno, "CDF",
2588 &buffer, &buflen, NULL);
2590 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2597 } /* End loop over all records. */
2604 release_cdflist (cdflist);
2613 SEQUENCE { -- CommonObjectAttributes
2614 UTF8String 'specific PIN for DS'
2615 BIT STRING 0 unused bits
2618 SEQUENCE { -- CommonAuthenticationObjectAttributes
2623 [1] { -- typeAttributes
2624 SEQUENCE { -- PinAttributes
2625 BIT STRING 0 unused bits
2626 '0000100000110010'B -- local,initialized,needs-padding
2628 ENUMERATED 1 -- ascii-numeric
2629 INTEGER 6 -- minLength
2630 INTEGER 6 -- storedLength
2631 INTEGER 8 -- maxLength
2634 GeneralizedTime 19/04/2002 12:12 GMT -- lastPinChange
2637 3F 00 40 16 -- path to DF of PIN
2644 /* Read and parse an Authentication Object Directory File identified
2645 by FID. On success a newlist of AODF objects gets stored at RESULT
2646 and the caller is responsible of releasing this list. On error a
2647 error code is returned and RESULT won't get changed. */
2649 read_ef_aodf (app_t app, unsigned short fid, aodf_object_t *result)
2652 unsigned char *buffer;
2654 const unsigned char *p;
2655 size_t n, objlen, hdrlen;
2656 int class, tag, constructed, ndef;
2657 aodf_object_t aodflist = NULL;
2662 err = read_first_record (app, fid, "AODF", &buffer, &buflen, &record_mode);
2669 /* Loop over the records. We stop as soon as we detect a new record
2670 starting with 0x00 or 0xff as these values are commonly used to
2671 pad data blocks and are no valid ASN.1 encoding. Note the
2672 special handling for record mode at the end of the loop. */
2673 while (n && *p && *p != 0xff)
2675 const unsigned char *pp;
2678 const char *errstr = NULL;
2679 aodf_object_t aodf = NULL;
2684 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2685 &ndef, &objlen, &hdrlen);
2688 else if (objlen > n)
2689 err = gpg_error (GPG_ERR_INV_OBJ);
2690 else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
2691 ; /* PinAttributes */
2692 else if (class == CLASS_CONTEXT)
2696 case 0: errstr = "biometric auth types are not supported"; break;
2697 case 1: errstr = "authKey auth types are not supported"; break;
2698 case 2: errstr = "external auth type are not supported"; break;
2699 default: errstr = "unknown privateKeyObject"; break;
2705 err = gpg_error (GPG_ERR_INV_OBJ);
2712 log_error ("p15: error parsing AODF record: %s\n",
2713 gpg_strerror (err));
2721 /* Allocate memory for a new AODF list item. */
2722 aodf = xtrycalloc (1, sizeof *aodf);
2727 /* Parse the commonObjectAttributes. */
2729 err = parse_common_obj_attr (&pp, &nn, &aodf->authid, &aodf->authidlen,
2734 /* Parse the CommonAuthenticationObjectAttributes. */
2736 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2737 &ndef, &objlen, &hdrlen);
2738 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
2739 err = gpg_error (GPG_ERR_INV_OBJ);
2743 const unsigned char *ppp = pp;
2744 size_t nnn = objlen;
2751 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
2752 &ndef, &objlen, &hdrlen);
2753 if (!err && (objlen > nnn
2754 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
2755 err = gpg_error (GPG_ERR_INV_OBJ);
2759 aodf->objidlen = objlen;
2760 aodf->objid = xtrymalloc (objlen);
2763 memcpy (aodf->objid, ppp, objlen);
2766 /* Parse the typeAttributes. */
2768 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2769 &ndef, &objlen, &hdrlen);
2770 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
2771 err = gpg_error (GPG_ERR_INV_OBJ);
2777 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2778 &ndef, &objlen, &hdrlen);
2781 else if (!err && objlen > nn)
2782 err = gpg_error (GPG_ERR_INV_OBJ);
2783 else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
2784 ; /* A typeAttribute always starts with a sequence */
2786 err = gpg_error (GPG_ERR_INV_OBJ);
2794 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2795 &ndef, &objlen, &hdrlen);
2796 if (!err && (objlen > nn || !objlen
2797 || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
2798 err = gpg_error (GPG_ERR_INV_OBJ);
2803 unsigned int bits, mask;
2806 unused = *pp++; nn--; objlen--;
2807 if ((!objlen && unused) || unused/8 > objlen)
2809 err = gpg_error (GPG_ERR_ENCODING_PROBLEM);
2812 full = objlen - (unused+7)/8;
2815 for (i=1; unused; i <<= 1, unused--)
2818 /* The first octet */
2822 bits = *pp++; nn--; objlen--;
2831 if ((bits & 0x80)) /* ASN.1 bit 0. */
2832 aodf->pinflags.case_sensitive = 1;
2833 if ((bits & 0x40)) /* ASN.1 bit 1. */
2834 aodf->pinflags.local = 1;
2836 aodf->pinflags.change_disabled = 1;
2838 aodf->pinflags.unblock_disabled = 1;
2840 aodf->pinflags.initialized = 1;
2842 aodf->pinflags.needs_padding = 1;
2844 aodf->pinflags.unblocking_pin = 1;
2846 aodf->pinflags.so_pin = 1;
2847 /* The second octet. */
2851 bits = *pp++; nn--; objlen--;
2860 aodf->pinflags.disable_allowed = 1;
2862 aodf->pinflags.integrity_protected = 1;
2864 aodf->pinflags.confidentiality_protected = 1;
2866 aodf->pinflags.exchange_ref_data = 1;
2867 /* Skip remaining bits. */
2875 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2876 &ndef, &objlen, &hdrlen);
2877 if (!err && (objlen > nn
2878 || class != CLASS_UNIVERSAL || tag != TAG_ENUMERATED))
2879 err = gpg_error (GPG_ERR_INV_OBJ);
2880 if (!err && objlen > sizeof (ul))
2881 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
2885 for (ul=0; objlen; objlen--)
2888 ul |= (*pp++) & 0xff;
2896 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2897 &ndef, &objlen, &hdrlen);
2898 if (!err && (objlen > nn
2899 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
2900 err = gpg_error (GPG_ERR_INV_OBJ);
2901 if (!err && objlen > sizeof (ul))
2902 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
2905 for (ul=0; objlen; objlen--)
2908 ul |= (*pp++) & 0xff;
2911 aodf->min_length = ul;
2916 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2917 &ndef, &objlen, &hdrlen);
2918 if (!err && (objlen > nn
2919 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
2920 err = gpg_error (GPG_ERR_INV_OBJ);
2921 if (!err && objlen > sizeof (ul))
2922 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
2925 for (ul=0; objlen; objlen--)
2928 ul |= (*pp++) & 0xff;
2931 aodf->stored_length = ul;
2933 /* optional maxLength */
2935 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2936 &ndef, &objlen, &hdrlen);
2937 if (gpg_err_code (err) == GPG_ERR_EOF)
2939 if (!err && objlen > nn)
2940 err = gpg_error (GPG_ERR_INV_OBJ);
2943 if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
2945 if (objlen > sizeof (ul))
2947 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
2950 for (ul=0; objlen; objlen--)
2953 ul |= (*pp++) & 0xff;
2956 aodf->max_length = ul;
2957 aodf->max_length_valid = 1;
2960 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2961 &ndef, &objlen, &hdrlen);
2962 if (gpg_err_code (err) == GPG_ERR_EOF)
2964 if (!err && objlen > nn)
2965 err = gpg_error (GPG_ERR_INV_OBJ);
2970 /* Optional pinReference. */
2971 if (class == CLASS_CONTEXT && tag == 0)
2973 if (objlen > sizeof (ul))
2975 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
2978 for (ul=0; objlen; objlen--)
2981 ul |= (*pp++) & 0xff;
2984 aodf->pin_reference = ul;
2985 aodf->pin_reference_valid = 1;
2988 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2989 &ndef, &objlen, &hdrlen);
2990 if (gpg_err_code (err) == GPG_ERR_EOF)
2992 if (!err && objlen > nn)
2993 err = gpg_error (GPG_ERR_INV_OBJ);
2998 /* Optional padChar. */
2999 if (class == CLASS_UNIVERSAL && tag == TAG_OCTET_STRING)
3003 errstr = "padChar is not of size(1)";
3006 aodf->pad_char = *pp++; nn--;
3007 aodf->pad_char_valid = 1;
3010 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
3011 &ndef, &objlen, &hdrlen);
3012 if (gpg_err_code (err) == GPG_ERR_EOF)
3014 if (!err && objlen > nn)
3015 err = gpg_error (GPG_ERR_INV_OBJ);
3020 /* Skip optional lastPinChange. */
3021 if (class == CLASS_UNIVERSAL && tag == TAG_GENERALIZED_TIME)
3027 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
3028 &ndef, &objlen, &hdrlen);
3029 if (gpg_err_code (err) == GPG_ERR_EOF)
3031 if (!err && objlen > nn)
3032 err = gpg_error (GPG_ERR_INV_OBJ);
3037 /* Optional Path object. */
3038 if (class == CLASS_UNIVERSAL || tag == TAG_SEQUENCE)
3040 const unsigned char *ppp = pp;
3041 size_t nnn = objlen;
3047 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
3048 &ndef, &objlen, &hdrlen);
3049 if (!err && objlen > nnn)
3050 err = gpg_error (GPG_ERR_INV_OBJ);
3054 /* Make sure that the next element is a non zero FID and of
3055 even length (FID are two bytes each). */
3056 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
3057 || !objlen || (objlen & 1) )
3059 errstr = "invalid path reference";
3063 aodf->pathlen = objlen/2;
3064 aodf->path = xtrycalloc (aodf->pathlen, sizeof *aodf->path);
3067 for (i=0; i < aodf->pathlen; i++, ppp += 2, nnn -= 2)
3068 aodf->path[i] = ((ppp[0] << 8) | ppp[1]);
3072 /* An index and length follows. */
3075 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
3076 &ndef, &objlen, &hdrlen);
3077 if (!err && (objlen > nnn
3078 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
3079 err = gpg_error (GPG_ERR_INV_OBJ);
3083 for (ul=0; objlen; objlen--)
3086 ul |= (*ppp++) & 0xff;
3092 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
3093 &ndef, &objlen, &hdrlen);
3094 if (!err && (objlen > nnn
3095 || class != CLASS_CONTEXT || tag != 0))
3096 err = gpg_error (GPG_ERR_INV_OBJ);
3100 for (ul=0; objlen; objlen--)
3103 ul |= (*ppp++) & 0xff;
3110 /* Ignore further objects which might be there due to future
3111 extensions of pkcs#15. */
3114 if (gpg_err_code (err) == GPG_ERR_EOF)
3118 log_info ("p15: AODF %04hX: id=", fid);
3119 for (i=0; i < aodf->objidlen; i++)
3120 log_printf ("%02X", aodf->objid[i]);
3122 log_printf (" (%s)", aodf->label);
3126 log_printf (" path=");
3127 for (i=0; i < aodf->pathlen; i++)
3128 log_printf ("%s%04hX", i?"/":"",aodf->path[i]);
3130 log_printf ("[%lu/%lu]", aodf->off, aodf->len);
3134 log_printf (" authid=");
3135 for (i=0; i < aodf->authidlen; i++)
3136 log_printf ("%02X", aodf->authid[i]);
3138 if (aodf->pin_reference_valid)
3139 log_printf (" pinref=0x%02lX", aodf->pin_reference);
3140 log_printf (" min=%lu", aodf->min_length);
3141 log_printf (" stored=%lu", aodf->stored_length);
3142 if (aodf->max_length_valid)
3143 log_printf (" max=%lu", aodf->max_length);
3144 if (aodf->pad_char_valid)
3145 log_printf (" pad=0x%02x", aodf->pad_char);
3147 log_info ("p15: flags=");
3149 if (aodf->pinflags.case_sensitive)
3150 log_printf ("%scase_sensitive", s), s = ",";
3151 if (aodf->pinflags.local)
3152 log_printf ("%slocal", s), s = ",";
3153 if (aodf->pinflags.change_disabled)
3154 log_printf ("%schange_disabled", s), s = ",";
3155 if (aodf->pinflags.unblock_disabled)
3156 log_printf ("%sunblock_disabled", s), s = ",";
3157 if (aodf->pinflags.initialized)
3158 log_printf ("%sinitialized", s), s = ",";
3159 if (aodf->pinflags.needs_padding)
3160 log_printf ("%sneeds_padding", s), s = ",";
3161 if (aodf->pinflags.unblocking_pin)
3162 log_printf ("%sunblocking_pin", s), s = ",";
3163 if (aodf->pinflags.so_pin)
3164 log_printf ("%sso_pin", s), s = ",";
3165 if (aodf->pinflags.disable_allowed)
3166 log_printf ("%sdisable_allowed", s), s = ",";
3167 if (aodf->pinflags.integrity_protected)
3168 log_printf ("%sintegrity_protected", s), s = ",";
3169 if (aodf->pinflags.confidentiality_protected)
3170 log_printf ("%sconfidentiality_protected", s), s = ",";
3171 if (aodf->pinflags.exchange_ref_data)
3172 log_printf ("%sexchange_ref_data", s), s = ",";
3177 switch (aodf->pintype)
3179 case PIN_TYPE_BCD: s2 = "bcd"; break;
3180 case PIN_TYPE_ASCII_NUMERIC: s2 = "ascii-numeric"; break;
3181 case PIN_TYPE_UTF8: s2 = "utf8"; break;
3182 case PIN_TYPE_HALF_NIBBLE_BCD: s2 = "half-nibble-bcd"; break;
3183 case PIN_TYPE_ISO9564_1: s2 = "iso9564-1"; break;
3185 sprintf (numbuf, "%lu", (unsigned long)aodf->pintype);
3188 log_printf ("%stype=%s", s, s2); s = ",";
3193 /* Put it into the list. */
3194 aodf->next = aodflist;
3197 goto next_record; /* Ready with this record. */
3200 err = gpg_error_from_syserror ();
3201 release_aodf_object (aodf);
3205 log_error ("p15: error parsing AODF record at %d: %s - skipped\n",
3206 where, errstr? errstr : gpg_strerror (err));
3208 release_aodf_object (aodf);
3211 /* If the card uses a record oriented file structure, read the
3212 * next record. Otherwise we keep on parsing the current buffer. */
3216 xfree (buffer); buffer = NULL;
3217 err = select_and_read_record (app, 0, recno, "AODF",
3218 &buffer, &buflen, NULL);
3220 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
3227 } /* End looping over all records. */
3232 release_aodflist (aodflist);
3239 /* Print the BIT STRING with the tokenflags from the TokenInfo. */
3241 print_tokeninfo_tokenflags (const unsigned char *der, size_t derlen)
3243 unsigned int bits, mask;
3244 int i, unused, full;
3249 log_printf (" [invalid object]");
3253 unused = *der++; derlen--;
3254 if ((!derlen && unused) || unused/8 > derlen)
3256 log_printf (" [wrong encoding]");
3259 full = derlen - (unused+7)/8;
3262 for (i=1; unused; i <<= 1, unused--)
3268 bits = *der++; derlen--;
3279 if ((bits & 0x80)) log_printf (" readonly");
3280 if ((bits & 0x40)) log_printf (" loginRequired");
3281 if ((bits & 0x20)) log_printf (" prnGeneration");
3282 if ((bits & 0x10)) log_printf (" eidCompliant");
3283 if ((bits & 0x08)) other = 1;
3284 if ((bits & 0x04)) other = 1;
3285 if ((bits & 0x02)) other = 1;
3286 if ((bits & 0x01)) other = 1;
3293 log_printf (" [unknown]");
3298 /* Read and parse the EF(TokenInfo).
3300 * TokenInfo ::= SEQUENCE {
3301 * version INTEGER {v1(0)} (v1,...),
3302 * serialNumber OCTET STRING,
3303 * manufacturerID Label OPTIONAL,
3304 * label [0] Label OPTIONAL,
3305 * tokenflags TokenFlags,
3306 * seInfo SEQUENCE OF SecurityEnvironmentInfo OPTIONAL,
3307 * recordInfo [1] RecordInfo OPTIONAL,
3308 * supportedAlgorithms [2] SEQUENCE OF AlgorithmInfo OPTIONAL,
3310 * issuerId [3] Label OPTIONAL,
3311 * holderId [4] Label OPTIONAL,
3312 * lastUpdate [5] LastUpdate OPTIONAL,
3313 * preferredLanguage PrintableString OPTIONAL -- In accordance with
3315 * } (CONSTRAINED BY { -- Each AlgorithmInfo.reference value must be unique --})
3317 * TokenFlags ::= BIT STRING {
3319 * loginRequired (1),
3320 * prnGeneration (2),
3326 * 30 31 02 01 00 04 04 05 45 36 9F 0C 0C 44 2D 54 01......E6...D-T
3327 * 72 75 73 74 20 47 6D 62 48 80 14 4F 66 66 69 63 rust GmbH..Offic
3328 * 65 20 69 64 65 6E 74 69 74 79 20 63 61 72 64 03 e identity card.
3329 * 02 00 40 20 63 61 72 64 03 02 00 40 00 00 00 00 ..@ card...@....
3330 * 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
3334 * 5 4: OCTET STRING 05 45 36 9F
3335 * 11 12: UTF8String 'D-Trust GmbH'
3336 * 25 20: [0] 'Office identity card'
3338 * : '00000010'B (bit 1)
3339 * : Error: Spurious zero bits in bitstring.
3343 read_ef_tokeninfo (app_t app)
3346 unsigned char *buffer = NULL;
3348 const unsigned char *p;
3349 size_t n, objlen, hdrlen;
3350 int class, tag, constructed, ndef;
3353 release_tokeninfo (app);
3354 app->app_local->card_product = CARD_PRODUCT_UNKNOWN;
3356 err = select_and_read_binary (app, 0x5032, "TokenInfo", &buffer, &buflen);
3363 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3364 &ndef, &objlen, &hdrlen);
3365 if (!err && (objlen > n || tag != TAG_SEQUENCE))
3366 err = gpg_error (GPG_ERR_INV_OBJ);
3369 log_error ("p15: error parsing TokenInfo: %s\n", gpg_strerror (err));
3376 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3377 &ndef, &objlen, &hdrlen);
3378 if (!err && (objlen > n || tag != TAG_INTEGER))
3379 err = gpg_error (GPG_ERR_INV_OBJ);
3383 for (ul=0; objlen; objlen--)
3386 ul |= (*p++) & 0xff;
3391 log_error ("p15: invalid version %lu in TokenInfo\n", ul);
3392 err = gpg_error (GPG_ERR_INV_OBJ);
3397 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3398 &ndef, &objlen, &hdrlen);
3399 if (!err && (objlen > n || tag != TAG_OCTET_STRING || !objlen))
3400 err = gpg_error (GPG_ERR_INV_OBJ);
3404 xfree (app->app_local->serialno);
3405 app->app_local->serialno = xtrymalloc (objlen);
3406 if (!app->app_local->serialno)
3408 err = gpg_error_from_syserror ();
3411 memcpy (app->app_local->serialno, p, objlen);
3412 app->app_local->serialnolen = objlen;
3416 /* Is there an optional manufacturerID? */
3417 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3418 &ndef, &objlen, &hdrlen);
3419 if (!err && (objlen > n || !objlen))
3420 err = gpg_error (GPG_ERR_INV_OBJ);
3423 if (class == CLASS_UNIVERSAL && tag == TAG_UTF8_STRING)
3425 app->app_local->manufacturer_id = percent_data_escape (0, NULL,
3430 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3431 &ndef, &objlen, &hdrlen);
3432 if (!err && (objlen > n || !objlen))
3433 err = gpg_error (GPG_ERR_INV_OBJ);
3437 if (class == CLASS_CONTEXT && tag == 0)
3439 app->app_local->token_label = percent_data_escape (0, NULL, p, objlen);
3444 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3445 &ndef, &objlen, &hdrlen);
3446 if (!err && (objlen > n || !objlen))
3447 err = gpg_error (GPG_ERR_INV_OBJ);
3451 /* The next is the mandatory tokenflags object. */
3452 if (class == CLASS_UNIVERSAL && tag == TAG_BIT_STRING)
3454 app->app_local->tokenflagslen = objlen;
3455 app->app_local->tokenflags = xtrymalloc (objlen);
3456 if (!app->app_local->tokenflags)
3458 err = gpg_error_from_syserror ();
3461 memcpy (app->app_local->tokenflags, p, objlen);
3473 /* Get all the basic information from the pkcs#15 card, check the
3474 structure and initialize our local context. This is used once at
3475 application initialization. */
3477 read_p15_info (app_t app)
3480 prkdf_object_t prkdf;
3483 err = read_ef_tokeninfo (app);
3486 /* If we don't have a serial number yet but the TokenInfo provides
3488 if (!APP_CARD(app)->serialno && app->app_local->serialno)
3490 APP_CARD(app)->serialno = app->app_local->serialno;
3491 APP_CARD(app)->serialnolen = app->app_local->serialnolen;
3492 app->app_local->serialno = NULL;
3493 app->app_local->serialnolen = 0;
3494 err = app_munge_serialno (APP_CARD(app));
3499 release_lists (app);
3501 /* Read the ODF so that we know the location of all directory
3503 /* Fixme: We might need to get a non-standard ODF FID from TokenInfo. */
3504 err = read_ef_odf (app, 0x5031);
3508 /* Read certificate information. */
3509 log_assert (!app->app_local->certificate_info);
3510 log_assert (!app->app_local->trusted_certificate_info);
3511 log_assert (!app->app_local->useful_certificate_info);
3512 err = read_ef_cdf (app, app->app_local->odf.certificates, 'c',
3513 &app->app_local->certificate_info);
3514 if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
3515 err = read_ef_cdf (app, app->app_local->odf.trusted_certificates, 't',
3516 &app->app_local->trusted_certificate_info);
3517 if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
3518 err = read_ef_cdf (app, app->app_local->odf.useful_certificates, 'u',
3519 &app->app_local->useful_certificate_info);
3520 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
3525 /* Read information about public keys. */
3526 log_assert (!app->app_local->public_key_info);
3527 err = read_ef_pukdf (app, app->app_local->odf.public_keys,
3528 &app->app_local->public_key_info);
3529 if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
3530 err = read_ef_pukdf (app, app->app_local->odf.trusted_public_keys,
3531 &app->app_local->public_key_info);
3532 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
3537 /* Read information about private keys. */
3538 log_assert (!app->app_local->private_key_info);
3539 err = read_ef_prkdf (app, app->app_local->odf.private_keys,
3540 &app->app_local->private_key_info);
3541 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
3546 /* Read information about authentication objects. */
3547 log_assert (!app->app_local->auth_object_info);
3548 err = read_ef_aodf (app, app->app_local->odf.auth_objects,
3549 &app->app_local->auth_object_info);
3550 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
3554 /* See whether we can extend the private key information using
3555 * information from certificates. We use only the first matching
3556 * certificate; if we want to change this strategy we should walk
3557 * over the certificates and then find the corresponsing private key
3559 app->app_local->any_gpgusage = 0;
3560 for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
3568 log_printhex (prkdf->objid, prkdf->objidlen, "p15: prkdf id=");
3569 if (cdf_object_from_objid (app, prkdf->objidlen, prkdf->objid, &cdf)
3570 && cdf_object_from_label (app, prkdf->label, &cdf))
3571 continue; /* No matching certificate. */
3572 if (!cdf->cert) /* Read and parse the certificate. */
3573 readcert_by_cdf (app, cdf, NULL, NULL);
3575 continue; /* Unsupported or broken certificate. */
3580 const unsigned char *der;
3581 size_t off, derlen, objlen, hdrlen;
3582 int class, tag, constructed, ndef;
3584 for (i=0; !(err = ksba_cert_get_extension
3585 (cdf->cert, i, &oid, NULL, &off, &derlen)); i++)
3586 if (!strcmp (oid, "1.3.6.1.4.1.11591.2.2.10") )
3588 if (!err && (der = ksba_cert_get_image (cdf->cert, NULL)))
3591 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
3592 &ndef, &objlen, &hdrlen);
3593 if (!err && (objlen > derlen || tag != TAG_OCTET_STRING || ndef))
3594 err = gpg_error (GPG_ERR_INV_OBJ);
3599 log_printhex (der, derlen, "p15: OpenPGP KDF parms:");
3600 /* Store them if they match the known OpenPGP format. */
3601 if (derlen == 4 && der[0] == 3 && der[1] == 1)
3602 memcpy (prkdf->ecdh_kdf, der, 4);
3608 if (ksba_cert_get_ext_key_usages (cdf->cert, &extusage))
3609 continue; /* No extended key usage attribute. */
3612 log_debug ("p15: ExtKeyUsages: %s\n", extusage);
3614 while (p && (pend=strchr (p, ':')))
3617 if ( *pend == 'C' ) /* Look only at critical usages. */
3619 prkdf->extusage.valid = 1;
3621 if (!strcmp (p, oid_kp_codeSigning)
3622 || !strcmp (p, oid_kp_timeStamping)
3623 || !strcmp (p, oid_kp_ocspSigning)
3624 || !strcmp (p, oid_kp_ms_documentSigning)
3625 || !strcmp (p, oid_kp_ms_old_documentSigning))
3626 prkdf->extusage.sign = 1;
3627 else if (!strcmp (p, oid_kp_emailProtection))
3628 prkdf->extusage.encr = 1;
3629 else if (!strcmp (p, oid_kp_serverAuth)
3630 || !strcmp (p, oid_kp_clientAuth)
3631 || !strcmp (p, oid_kp_ms_smartcardLogon))
3632 prkdf->extusage.auth = 1;
3633 else if (!strcmp (p, oid_kp_anyExtendedKeyUsage))
3635 prkdf->extusage.sign = 1;
3636 prkdf->extusage.encr = 1;
3637 prkdf->extusage.auth = 1;
3645 /* Now check the gpg Usage. Here we don't care about
3646 * critical or non-critical here. */
3648 ; /* No more need to look for other caps. */
3649 else if (!strcmp (p, oid_kp_gpgUsageCert))
3651 prkdf->gpgusage.cert = 1;
3652 prkdf->gpgusage.any = 1;
3653 app->app_local->any_gpgusage = 1;
3655 else if (!strcmp (p, oid_kp_gpgUsageSign))
3657 prkdf->gpgusage.sign = 1;
3658 prkdf->gpgusage.any = 1;
3659 app->app_local->any_gpgusage = 1;
3661 else if (!strcmp (p, oid_kp_gpgUsageEncr))
3663 prkdf->gpgusage.encr = 1;
3664 prkdf->gpgusage.any = 1;
3665 app->app_local->any_gpgusage = 1;
3667 else if (!strcmp (p, oid_kp_gpgUsageAuth))
3669 prkdf->gpgusage.auth = 1;
3670 prkdf->gpgusage.any = 1;
3671 app->app_local->any_gpgusage = 1;
3674 /* Skip to next item. */
3675 if ((p = strchr (pend, '\n')))
3681 /* See whether we can figure out something about the card. */
3682 if (!app->app_local->card_product
3683 && app->app_local->manufacturer_id
3684 && !strcmp (app->app_local->manufacturer_id, "www.atos.net/cardos")
3685 && IS_CARDOS_5 (app))
3687 /* This is a modern CARDOS card. */
3689 for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
3691 if (prkdf->label && !strcmp (prkdf->label, "IdentityKey")
3692 && prkdf->key_reference_valid && prkdf->key_reference == 1
3695 else if (prkdf->label && !strcmp (prkdf->label, "TransportKey")
3696 && prkdf->key_reference_valid && prkdf->key_reference==2
3701 app->app_local->card_product = CARD_PRODUCT_RSCS;
3704 if (!app->app_local->card_product
3705 && app->app_local->token_label
3706 && !strcmp (app->app_local->token_label, "D-TRUST Card V3")
3707 && app->app_local->card_type == CARD_TYPE_CARDOS_50)
3709 app->app_local->card_product = CARD_PRODUCT_DTRUST;
3713 /* Now print the info about the PrKDF. */
3719 const char *cardstr;
3721 for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
3723 log_info ("p15: PrKDF %04hX: id=", app->app_local->odf.private_keys);
3724 for (i=0; i < prkdf->objidlen; i++)
3725 log_printf ("%02X", prkdf->objid[i]);
3727 log_printf (" (%s)", prkdf->label);
3728 log_info ("p15: path=");
3729 for (i=0; i < prkdf->pathlen; i++)
3730 log_printf ("%s%04hX", i?"/":"",prkdf->path[i]);
3731 if (prkdf->have_off)
3732 log_printf ("[%lu/%lu]", prkdf->off, prkdf->len);
3735 log_printf (" authid=");
3736 for (i=0; i < prkdf->authidlen; i++)
3737 log_printf ("%02X", prkdf->authid[i]);
3739 if (prkdf->key_reference_valid)
3740 log_printf (" keyref=0x%02lX", prkdf->key_reference);
3741 log_printf (" type=%s", prkdf->is_ecc? "ecc":"rsa");
3742 if (prkdf->accessflags.any)
3743 dump_keyaccess_flags (prkdf->accessflags);
3744 dump_keyusage_flags (prkdf->usageflags);
3745 if (prkdf->extusage.valid)
3746 log_info ("p15: extusage=%s%s%s%s%s",
3747 prkdf->extusage.sign? "sign":"",
3748 (prkdf->extusage.sign
3749 && prkdf->extusage.encr)?",":"",
3750 prkdf->extusage.encr? "encr":"",
3751 ((prkdf->extusage.sign || prkdf->extusage.encr)
3752 && prkdf->extusage.auth)?",":"",
3753 prkdf->extusage.auth? "auth":"");
3754 if (prkdf->gpgusage.any)
3755 dump_gpgusage_flags (prkdf->gpgusage);
3760 log_info ("p15: TokenInfo:\n");
3761 if (app->app_local->serialno)
3763 log_info ("p15: serialNumber .: ");
3764 log_printhex (app->app_local->serialno, app->app_local->serialnolen,
3767 else if (APP_CARD(app)->serialno)
3769 log_info ("p15: serialNumber .: ");
3770 log_printhex (APP_CARD(app)->serialno, APP_CARD(app)->serialnolen,
3774 if (app->app_local->manufacturer_id)
3775 log_info ("p15: manufacturerID: %s\n",
3776 app->app_local->manufacturer_id);
3777 if (app->app_local->card_product)
3779 cardstr = cardproduct2str (app->app_local->card_product);
3780 log_info ("p15: product ......: %d%s%s%s\n",
3781 app->app_local->card_product,
3782 *cardstr? " (":"", cardstr, *cardstr? ")":"");
3784 if (app->app_local->token_label)
3785 log_info ("p15: label ........: %s\n", app->app_local->token_label);
3786 if (app->app_local->tokenflags)
3788 log_info ("p15: tokenflags ...:");
3789 print_tokeninfo_tokenflags (app->app_local->tokenflags,
3790 app->app_local->tokenflagslen);
3794 log_info ("p15: atr ..........: ");
3795 atr = apdu_get_atr (app_get_slot (app), &atrlen);
3797 log_printf ("[error]\n");
3800 log_printhex (atr, atrlen, "");
3804 cardstr = cardtype2str (app->app_local->card_type);
3805 log_info ("p15: cardtype .....: %d%s%s%s\n",
3806 app->app_local->card_type,
3807 *cardstr? " (":"", cardstr, *cardstr? ")":"");
3814 /* Helper to do_learn_status: Send information about all certificates
3815 listed in CERTINFO back. Use CERTTYPE as type of the
3818 send_certinfo (app_t app, ctrl_t ctrl, const char *certtype,
3819 cdf_object_t certinfo)
3821 for (; certinfo; certinfo = certinfo->next)
3827 buf = xtrymalloc (9 + certinfo->objidlen*2 + 1);
3829 return gpg_error_from_syserror ();
3830 p = stpcpy (buf, "P15");
3831 if (app->app_local->home_df != DEFAULT_HOME_DF)
3833 snprintf (p, 6, "-%04X",
3834 (unsigned int)(app->app_local->home_df & 0xffff));
3837 p = stpcpy (p, ".");
3838 bin2hex (certinfo->objid, certinfo->objidlen, p);
3840 label = (certinfo->label && *certinfo->label)? certinfo->label : "-";
3841 labelbuf = percent_data_escape (0, NULL, label, strlen (label));
3845 return gpg_error_from_syserror ();
3848 send_status_info (ctrl, "CERTINFO",
3849 certtype, strlen (certtype),
3851 labelbuf, strlen (labelbuf),
3859 /* Get the keygrip of the private key object PRKDF. On success the
3860 * keygrip, the algo and the length are stored in the KEYGRIP,
3861 * KEYALGO, and KEYNBITS fields of the PRKDF object. */
3863 keygrip_from_prkdf (app_t app, prkdf_object_t prkdf)
3870 gcry_sexp_t s_pkey = NULL;
3872 /* Easy if we got a cached version. */
3873 if (prkdf->keygrip_valid)
3876 xfree (prkdf->common_name);
3877 prkdf->common_name = NULL;
3878 xfree (prkdf->serial_number);
3879 prkdf->serial_number = NULL;
3881 /* We could have also checked whether a public key directory file
3882 * and a matching public key for PRKDF is available. This would
3883 * make extraction of the key faster. However, this way we don't
3884 * have a way to look at extended key attributes to check gpgusage.
3885 * FIXME: Add public key lookup if no certificate was found. */
3887 /* Look for a matching certificate. A certificate matches if the id
3888 * matches the one of the private key info. If none was found we
3889 * also try to match on the label. */
3890 err = cdf_object_from_objid (app, prkdf->objidlen, prkdf->objid, &cdf);
3891 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
3892 err = cdf_object_from_label (app, prkdf->label, &cdf);
3894 err = gpg_error (GPG_ERR_NOT_FOUND);
3898 err = readcert_by_cdf (app, cdf, &der, &derlen);
3902 err = ksba_cert_new (&cert);
3904 err = ksba_cert_init_from_mem (cert, der, derlen);
3907 err = app_help_get_keygrip_string (cert, prkdf->keygrip, &s_pkey, NULL);
3908 if (!err && !prkdf->gpgusage.any)
3910 /* Try to get the CN and the SerialNumber from the certificate;
3911 * we use a very simple approach here which should work in many
3912 * cases. Eventually we should add a rfc-2253 parser into
3913 * libksba to make it easier to parse such a string.
3914 * We don't do this if this is marked as gpg key and thus
3915 * has only a dummy certificate.
3917 * First example string:
3918 * "CN=Otto Schily,O=Miniluv,C=DE"
3919 * Second example string:
3920 * "2.5.4.5=#445452323030303236333531,2.5.4.4=#4B6F6368,"
3921 * "2.5.4.42=#5765726E6572,CN=Werner Koch,OU=For testing"
3922 * " purposes only!,O=Testorganisation,C=DE"
3924 char *dn = ksba_cert_get_subject (cert, 0);
3927 char *p, *pend, *buf;
3929 p = strstr (dn, "CN=");
3930 if (p && (p==dn || p[-1] == ','))
3933 if (!(pend = strchr (p, ',')))
3934 pend = p + strlen (p);
3935 if (pend && pend > p
3936 && (prkdf->common_name = xtrymalloc ((pend - p) + 1)))
3938 memcpy (prkdf->common_name, p, pend-p);
3939 prkdf->common_name[pend-p] = 0;
3942 p = strstr (dn, "2.5.4.5=#"); /* OID of the SerialNumber */
3943 if (p && (p==dn || p[-1] == ','))
3946 if (!(pend = strchr (p, ',')))
3947 pend = p + strlen (p);
3948 if (pend && pend > p
3949 && (buf = xtrymalloc ((pend - p) + 1)))
3951 memcpy (buf, p, pend-p);
3953 if (!hex2str (buf, buf, strlen (buf)+1, NULL))
3954 xfree (buf); /* Invalid hex encoding. */
3956 prkdf->serial_number = buf;
3963 if (!err && !prkdf->keytime)
3965 ksba_isotime_t isot;
3968 ksba_cert_get_validity (cert, 0, isot);
3969 t = isotime2epoch (isot);
3970 prkdf->keytime = (t == (time_t)(-1))? 0 : (u32)t;
3971 prkdf->have_keytime = 1;
3974 if (!err && !prkdf->keyalgostr)
3975 prkdf->keyalgostr = pubkey_algo_string (s_pkey, NULL);
3977 ksba_cert_release (cert);
3981 prkdf->keyalgo = get_pk_algo_from_key (s_pkey);
3982 if (!prkdf->keyalgo)
3984 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
3988 prkdf->keynbits = gcry_pk_get_nbits (s_pkey);
3989 if (!prkdf->keynbits)
3991 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
3995 prkdf->keygrip_valid = 1; /* Yeah, got everything. */
3998 gcry_sexp_release (s_pkey);
4003 /* Return a malloced keyref string for PRKDF. Returns NULL on
4004 * malloc failure. */
4006 keyref_from_prkdf (app_t app, prkdf_object_t prkdf)
4010 buf = xtrymalloc (4 + 5 + prkdf->objidlen*2 + 1);
4013 p = stpcpy (buf, "P15");
4014 if (app->app_local->home_df != DEFAULT_HOME_DF)
4016 snprintf (p, 6, "-%04X",
4017 (unsigned int)(app->app_local->home_df & 0xffff));
4020 p = stpcpy (p, ".");
4021 bin2hex (prkdf->objid, prkdf->objidlen, p);
4026 /* Helper to do_learn_status: Send information about all known
4027 keypairs back. FIXME: much code duplication from
4030 send_keypairinfo (app_t app, ctrl_t ctrl, prkdf_object_t prkdf)
4034 for (; prkdf; prkdf = prkdf->next)
4039 buf = keyref_from_prkdf (app, prkdf);
4041 return gpg_error_from_syserror ();
4043 err = keygrip_from_prkdf (app, prkdf);
4046 log_error ("p15: error getting keygrip from ");
4047 for (j=0; j < prkdf->pathlen; j++)
4048 log_printf ("%s%04hX", j?"/":"", prkdf->path[j]);
4049 log_printf (": %s\n", gpg_strerror (err));
4055 const char *algostr;
4056 size_t usagelen = 0;
4058 if (prkdf->gpgusage.any)
4060 if (prkdf->gpgusage.sign)
4061 usage[usagelen++] = 's';
4062 if (prkdf->gpgusage.cert)
4063 usage[usagelen++] = 'c';
4064 if (prkdf->gpgusage.encr)
4065 usage[usagelen++] = 'e';
4066 if (prkdf->gpgusage.auth)
4067 usage[usagelen++] = 'a';
4071 if ((prkdf->usageflags.sign
4072 || prkdf->usageflags.sign_recover
4073 || prkdf->usageflags.non_repudiation)
4074 && (!prkdf->extusage.valid
4075 || prkdf->extusage.sign))
4076 usage[usagelen++] = 's';
4077 if ((prkdf->usageflags.sign
4078 || prkdf->usageflags.sign_recover)
4079 && (!prkdf->extusage.valid || prkdf->extusage.sign))
4080 usage[usagelen++] = 'c';
4081 if ((prkdf->usageflags.decrypt
4082 || prkdf->usageflags.unwrap)
4083 && (!prkdf->extusage.valid || prkdf->extusage.encr))
4084 usage[usagelen++] = 'e';
4085 if ((prkdf->usageflags.sign
4086 || prkdf->usageflags.sign_recover)
4087 && (!prkdf->extusage.valid || prkdf->extusage.auth))
4088 usage[usagelen++] = 'a';
4091 log_assert (strlen (prkdf->keygrip) == 40);
4092 if (prkdf->keytime && prkdf->have_keytime)
4093 snprintf (keytime, sizeof keytime, "%lu",
4094 (unsigned long)prkdf->keytime);
4096 strcpy (keytime, "-");
4098 algostr = prkdf->keyalgostr;
4100 send_status_info (ctrl, "KEYPAIRINFO",
4101 prkdf->keygrip, 2*KEYGRIP_LEN,
4104 keytime, strlen (keytime),
4105 algostr, strlen (algostr?algostr:""),
4115 /* This is the handler for the LEARN command. Note that if
4116 * APP_LEARN_FLAG_REREAD is set and this function returns an error,
4117 * the caller must deinitialize this application. */
4119 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
4123 if (flags & APP_LEARN_FLAG_REREAD)
4125 err = read_p15_info (app);
4130 if ((flags & APP_LEARN_FLAG_KEYPAIRINFO))
4134 err = do_getattr (app, ctrl, "MANUFACTURER");
4136 err = send_certinfo (app, ctrl, "100",
4137 app->app_local->certificate_info);
4139 err = send_certinfo (app, ctrl, "101",
4140 app->app_local->trusted_certificate_info);
4142 err = send_certinfo (app, ctrl, "102",
4143 app->app_local->useful_certificate_info);
4147 err = send_keypairinfo (app, ctrl, app->app_local->private_key_info);
4150 err = do_getattr (app, ctrl, "CHV-STATUS");
4152 err = do_getattr (app, ctrl, "CHV-LABEL");
4159 /* Read a certificate using the information in CDF and return the
4160 * certificate in a newly malloced buffer R_CERT and its length
4161 * R_CERTLEN. Also parses the certificate. R_CERT and R_CERTLEN may
4162 * be NULL to do just the caching. */
4164 readcert_by_cdf (app_t app, cdf_object_t cdf,
4165 unsigned char **r_cert, size_t *r_certlen)
4168 unsigned char *buffer = NULL;
4169 const unsigned char *p, *save_p;
4171 int class, tag, constructed, ndef;
4172 size_t totobjlen, objlen, hdrlen;
4181 /* First check whether it has been cached. */
4184 const unsigned char *image;
4187 if (!r_cert || !r_certlen)
4188 return 0; /* Caller does not actually want the result. */
4190 image = ksba_cert_get_image (cdf->cert, &imagelen);
4193 log_error ("p15: ksba_cert_get_image failed\n");
4194 return gpg_error (GPG_ERR_INTERNAL);
4196 *r_cert = xtrymalloc (imagelen);
4198 return gpg_error_from_syserror ();
4199 memcpy (*r_cert, image, imagelen);
4200 *r_certlen = imagelen;
4204 /* Read the entire file. fixme: This could be optimized by first
4205 reading the header to figure out how long the certificate
4207 err = select_ef_by_path (app, cdf->path, cdf->pathlen);
4211 err = iso7816_read_binary_ext (app_get_slot (app), 1, cdf->off, cdf->len,
4212 &buffer, &buflen, NULL);
4213 if (!err && (!buflen || *buffer == 0xff))
4214 err = gpg_error (GPG_ERR_NOT_FOUND);
4217 log_error ("p15: error reading certificate id=");
4218 for (i=0; i < cdf->objidlen; i++)
4219 log_printf ("%02X", cdf->objid[i]);
4220 log_printf (" at ");
4221 for (i=0; i < cdf->pathlen; i++)
4222 log_printf ("%s%04hX", i? "/":"", cdf->path[i]);
4223 log_printf (": %s\n", gpg_strerror (err));
4227 /* Check whether this is really a certificate. */
4230 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
4231 &ndef, &objlen, &hdrlen);
4235 if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed)
4237 else if ( class == CLASS_UNIVERSAL && tag == TAG_SET && constructed )
4241 err = gpg_error (GPG_ERR_INV_OBJ);
4244 totobjlen = objlen + hdrlen;
4245 log_assert (totobjlen <= buflen);
4247 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
4248 &ndef, &objlen, &hdrlen);
4253 && class == CLASS_UNIVERSAL && tag == TAG_OBJECT_ID && !constructed)
4255 /* The certificate seems to be contained in a userCertificate
4256 container. Skip this and assume the following sequence is
4260 err = gpg_error (GPG_ERR_INV_OBJ);
4266 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
4267 &ndef, &objlen, &hdrlen);
4270 if ( !(class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed) )
4272 err = gpg_error (GPG_ERR_INV_OBJ);
4275 totobjlen = objlen + hdrlen;
4276 log_assert (save_p + totobjlen <= buffer + buflen);
4277 memmove (buffer, save_p, totobjlen);
4281 /* Try to parse and cache the certificate. */
4282 err = ksba_cert_new (&cdf->cert);
4285 err = ksba_cert_init_from_mem (cdf->cert, buffer, totobjlen);
4286 if (!err) /* Call us to use the just cached cert object. */
4287 err = readcert_by_cdf (app, cdf, r_cert, r_certlen);
4290 ksba_cert_release (cdf->cert);
4297 log_error ("p15: caching certificate failed: %s\n",
4298 gpg_strerror (err));
4299 /* We return the certificate anyway so that the caller has a
4300 * chance to get an even unsupported or broken certificate. */
4301 if (r_cert && r_certlen)
4305 *r_certlen = totobjlen;
4315 /* Handler for the READCERT command.
4317 Read the certificate with id CERTID (as returned by learn_status in
4318 the CERTINFO status lines) and return it in the freshly allocated
4319 buffer to be stored at R_CERT and its length at R_CERTLEN. A error
4320 code will be returned on failure and R_CERT and R_CERTLEN will be
4323 do_readcert (app_t app, const char *certid,
4324 unsigned char **r_cert, size_t *r_certlen)
4331 err = cdf_object_from_certid (app, certid, &cdf);
4333 err = readcert_by_cdf (app, cdf, r_cert, r_certlen);
4338 /* Sort helper for an array of authentication objects. */
4340 compare_aodf_objid (const void *arg_a, const void *arg_b)
4342 const aodf_object_t a = *(const aodf_object_t *)arg_a;
4343 const aodf_object_t b = *(const aodf_object_t *)arg_b;
4346 rc = memcmp (a->objid, b->objid,
4347 a->objidlen < b->objidlen? a->objidlen : b->objidlen);
4350 if (a->objidlen < b->objidlen)
4352 else if (a->objidlen > b->objidlen)
4360 send_key_fpr_line (ctrl_t ctrl, int number, const unsigned char *fpr)
4365 bin2hex (fpr, 20, buf);
4367 *numbuf = 0; /* Don't print the key number */
4369 snprintf (numbuf, sizeof numbuf, "%d", number);
4370 send_status_info (ctrl, "KEY-FPR",
4371 numbuf, (size_t)strlen(numbuf),
4372 buf, (size_t)strlen (buf),
4377 /* If possible Emit a FPR-KEY status line for the private key object
4378 * PRKDF using NUMBER as index. */
4380 send_key_fpr (app_t app, ctrl_t ctrl, prkdf_object_t prkdf, int number)
4384 unsigned char *pk, *fixed_pk;
4385 size_t pklen, fixed_pklen;
4386 const unsigned char *m, *e, *q;
4387 size_t mlen, elen, qlen;
4388 unsigned char fpr20[20];
4390 if (cdf_object_from_objid (app, prkdf->objidlen, prkdf->objid, &cdf)
4391 && cdf_object_from_label (app, prkdf->label, &cdf))
4394 readcert_by_cdf (app, cdf, NULL, NULL);
4397 if (!prkdf->have_keytime)
4399 pk = ksba_cert_get_public_key (cdf->cert);
4402 pklen = gcry_sexp_canon_len (pk, 0, NULL, &err);
4404 if (uncompress_ecc_q_in_canon_sexp (pk, pklen, &fixed_pk, &fixed_pklen))
4411 xfree (pk); pk = NULL;
4413 pklen = fixed_pklen;
4416 switch (prkdf->keyalgo)
4419 if (!get_rsa_pk_from_canon_sexp (pk, pklen,
4420 &m, &mlen, &e, &elen)
4421 && !compute_openpgp_fpr_rsa (4,
4425 send_key_fpr_line (ctrl, number, fpr20);
4432 /* Note that NUMBER 2 indicates the encryption key. */
4433 if (!get_ecc_q_from_canon_sexp (pk, pklen, &q, &qlen)
4434 && !compute_openpgp_fpr_ecc (4,
4441 send_key_fpr_line (ctrl, number, fpr20);
4444 default: /* No Fingerprint for an unknown algo. */
4452 /* Implement the GETATTR command. This is similar to the LEARN
4453 command but returns just one value via the status interface. */
4455 do_getattr (app_t app, ctrl_t ctrl, const char *name)
4458 prkdf_object_t prkdf;
4460 if (!strcmp (name, "$AUTHKEYID")
4461 || !strcmp (name, "$ENCRKEYID")
4462 || !strcmp (name, "$SIGNKEYID"))
4466 /* We return the ID of the first private key capable of the
4467 * requested action. If any gpgusage flag has been set for the
4468 * card we consult the gpgusage flags and not the regualr usage
4471 /* FIXME: This changed: Note that we do not yet return
4472 * non_repudiation keys for $SIGNKEYID because our D-Trust
4473 * testcard uses rsaPSS, which is not supported by gpgsm and not
4474 * covered by the VS-NfD approval. */
4475 for (prkdf = app->app_local->private_key_info; prkdf;
4476 prkdf = prkdf->next)
4478 if (app->app_local->any_gpgusage)
4480 if ((name[1] == 'A' && prkdf->gpgusage.auth)
4481 || (name[1] == 'E' && prkdf->gpgusage.encr)
4482 || (name[1] == 'S' && prkdf->gpgusage.sign))
4487 if ((name[1] == 'A' && (prkdf->usageflags.sign
4488 || prkdf->usageflags.sign_recover))
4489 || (name[1] == 'E' && (prkdf->usageflags.decrypt
4490 || prkdf->usageflags.unwrap))
4491 || (name[1] == 'S' && (prkdf->usageflags.sign
4492 || prkdf->usageflags.sign_recover)))
4498 buf = keyref_from_prkdf (app, prkdf);
4500 return gpg_error_from_syserror ();
4502 send_status_info (ctrl, name, buf, strlen (buf), NULL, 0);
4507 else if (!strcmp (name, "$DISPSERIALNO"))
4509 /* For certain cards we return special IDs. There is no
4510 general rule for it so we need to decide case by case. */
4511 if (app->app_local->card_type == CARD_TYPE_BELPIC)
4513 /* The eID card has a card number printed on the front matter
4514 which seems to be a good indication. */
4515 unsigned char *buffer;
4516 const unsigned char *p;
4518 unsigned short path[] = { 0x3F00, 0xDF01, 0x4031 };
4520 err = select_ef_by_path (app, path, DIM(path) );
4522 err = iso7816_read_binary (app_get_slot (app), 0, 0,
4526 log_error ("p15: error accessing EF(ID): %s\n",
4527 gpg_strerror (err));
4531 p = find_tlv (buffer, buflen, 1, &n);
4537 memcpy (tmp+4, p+3, 7);
4539 memcpy (tmp+12, p+10, 2);
4541 send_status_info (ctrl, name, tmp, strlen (tmp), NULL, 0);
4549 /* We use the first private key object which has a serial
4550 * number set. If none was found, we parse the first
4551 * object and see whether this has then a serial number. */
4552 for (prkdf = app->app_local->private_key_info; prkdf;
4553 prkdf = prkdf->next)
4554 if (prkdf->serial_number)
4556 if (!prkdf && app->app_local->private_key_info)
4558 prkdf = app->app_local->private_key_info;
4559 keygrip_from_prkdf (app, prkdf);
4560 if (!prkdf->serial_number)
4565 char *sn = get_dispserialno (app, prkdf);
4566 /* Unless there is a bogus S/N in the cert we should
4567 * have a suitable one from the cert here now. */
4568 err = send_status_printf (ctrl, name, "%s", sn);
4573 /* No abbreviated serial number. */
4575 else if (!strcmp (name, "MANUFACTURER"))
4577 if (app->app_local->manufacturer_id)
4578 return send_status_printf (ctrl, "MANUFACTURER", "0 %s",
4579 app->app_local->manufacturer_id);
4583 else if (!strcmp (name, "CHV-STATUS") || !strcmp (name, "CHV-LABEL"))
4585 int is_label = (name[4] == 'L');
4587 aodf_object_t aodfarray[16];
4593 /* Put the AODFs into an array for easier sorting. Note that we
4594 * handle onl the first 16 encountrer which should be more than
4596 for (aodf = app->app_local->auth_object_info;
4597 aodf && naodf < DIM(aodfarray); aodf = aodf->next)
4598 if (aodf->objidlen && aodf->pin_reference_valid)
4599 aodfarray[naodf++] = aodf;
4600 qsort (aodfarray, naodf, sizeof *aodfarray, compare_aodf_objid);
4602 init_membuf (&mb, 256);
4603 for (i = 0; i < naodf; i++)
4606 /* log_debug ("p15: AODF[%d] pinref=%lu id=", */
4607 /* i, aodfarray[i]->pin_reference); */
4608 /* for (j=0; j < aodfarray[i]->objidlen; j++) */
4609 /* log_printf ("%02X", aodfarray[i]->objid[j]); */
4610 /* Note that there is no need to percent escape the label
4611 * because all white space have been replaced by '_'. */
4613 put_membuf_printf (&mb, "%s%s", i? " ":"",
4614 (aodfarray[i]->label
4615 && *aodfarray[i]->label)?
4616 aodfarray[i]->label:"X");
4619 (&mb, "%s%d", i? " ":"",
4620 iso7816_verify_status (app_get_slot (app),
4621 aodfarray[i]->pin_reference));
4623 put_membuf( &mb, "", 1);
4624 p = get_membuf (&mb, NULL);
4626 return gpg_error_from_syserror ();
4627 err = send_status_direct (ctrl, is_label? "CHV-LABEL":"CHV-STATUS", p);
4631 else if (!strcmp (name, "KEY-LABEL"))
4633 /* Send KEY-LABEL lines for all private key objects. */
4635 char *idbuf, *labelbuf;
4637 for (prkdf = app->app_local->private_key_info; prkdf;
4638 prkdf = prkdf->next)
4640 idbuf = keyref_from_prkdf (app, prkdf);
4642 return gpg_error_from_syserror ();
4644 label = (prkdf->label && *prkdf->label)? prkdf->label : "-";
4645 labelbuf = percent_data_escape (0, NULL, label, strlen (label));
4649 return gpg_error_from_syserror ();
4652 send_status_info (ctrl, name,
4653 idbuf, strlen (idbuf),
4654 labelbuf, strlen(labelbuf),
4661 else if (!strcmp (name, "KEY-FPR"))
4663 /* Send KEY-FPR for the two openpgp keys. */
4664 for (prkdf = app->app_local->private_key_info; prkdf;
4665 prkdf = prkdf->next)
4667 if (app->app_local->any_gpgusage)
4669 if (prkdf->gpgusage.sign)
4674 if (prkdf->usageflags.sign || prkdf->usageflags.sign_recover)
4679 send_key_fpr (app, ctrl, prkdf, 1);
4680 for (prkdf = app->app_local->private_key_info; prkdf;
4681 prkdf = prkdf->next)
4683 if (app->app_local->any_gpgusage)
4685 if (prkdf->gpgusage.encr)
4690 if (prkdf->usageflags.decrypt || prkdf->usageflags.unwrap)
4695 send_key_fpr (app, ctrl, prkdf, 2);
4699 return gpg_error (GPG_ERR_INV_NAME);
4705 /* Micardo cards require special treatment. This is a helper for the
4706 crypto functions to manage the security environment. We expect that
4707 the key file has already been selected. FID is the one of the
4710 micardo_mse (app_t app, unsigned short fid)
4714 unsigned short refdata = 0;
4716 unsigned char msebuf[10];
4718 /* Read the KeyD file containing extra information on keys. */
4719 err = iso7816_select_file (app_get_slot (app), 0x0013, 0);
4722 log_error ("p15: error reading EF_keyD: %s\n", gpg_strerror (err));
4726 for (recno = 1, se_num = -1; ; recno++)
4728 unsigned char *buffer;
4731 const unsigned char *p, *pp;
4733 err = iso7816_read_record (app_get_slot (app), recno, 1, 0,
4735 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
4739 log_error ("p15: error reading EF_keyD record: %s\n",
4740 gpg_strerror (err));
4745 log_info (buffer, buflen, "p15: keyD record: ");
4746 log_printhex (buffer, buflen, "");
4748 p = find_tlv (buffer, buflen, 0x83, &n);
4749 if (p && n == 4 && ((p[2]<<8)|p[3]) == fid)
4751 refdata = ((p[0]<<8)|p[1]);
4752 /* Locate the SE DO and the there included sec env number. */
4753 p = find_tlv (buffer, buflen, 0x7b, &n);
4756 pp = find_tlv (p, n, 0x80, &nn);
4769 log_error ("p15: CRT for keyfile %04hX not found\n", fid);
4770 return gpg_error (GPG_ERR_NOT_FOUND);
4774 /* Restore the security environment to SE_NUM if needed */
4777 err = iso7816_manage_security_env (app_get_slot (app),
4778 0xf3, se_num, NULL, 0);
4781 log_error ("p15: restoring SE to %d failed: %s\n",
4782 se_num, gpg_strerror (err));
4787 /* Set the DST reference data. */
4791 msebuf[3] = (refdata >> 8);
4792 msebuf[4] = refdata;
4793 err = iso7816_manage_security_env (app_get_slot (app), 0x41, 0xb6, msebuf, 5);
4796 log_error ("p15: setting SE to reference file %04hX failed: %s\n",
4797 refdata, gpg_strerror (err));
4805 /* Prepare the verification of the PIN for the key PRKDF by checking
4806 * the AODF and selecting the key file. KEYREF is used for error
4807 * messages. AODF may be NULL if no verification needs to be done. */
4809 prepare_verify_pin (app_t app, const char *keyref,
4810 prkdf_object_t prkdf, aodf_object_t aodf)
4819 log_info ("p15: using AODF %04hX id=", aodf->fid);
4820 for (i=0; i < aodf->objidlen; i++)
4821 log_printf ("%02X", aodf->objid[i]);
4825 if (aodf->authid && opt.verbose)
4826 log_info ("p15: PIN is controlled by another authentication token\n");
4828 if (aodf->pinflags.integrity_protected
4829 || aodf->pinflags.confidentiality_protected)
4831 log_error ("p15: PIN verification requires"
4832 " unsupported protection method\n");
4833 return gpg_error (GPG_ERR_BAD_PIN_METHOD);
4835 if (!aodf->stored_length && aodf->pinflags.needs_padding)
4837 log_error ("p15: PIN verification requires"
4838 " padding but no length known\n");
4839 return gpg_error (GPG_ERR_INV_CARD);
4844 if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
4846 /* According to our protocol analysis we need to select a
4847 * special AID here. Before that the master file needs to be
4848 * selected. (RID A000000167 is assigned to IBM) */
4849 static char const dtrust_aid[] =
4850 { 0xA0, 0x00, 0x00, 0x01, 0x67, 0x45, 0x53, 0x49, 0x47, 0x4E };
4852 err = iso7816_select_mf (app_get_slot (app));
4854 err = iso7816_select_application (app_get_slot (app),
4855 dtrust_aid, sizeof dtrust_aid, 0);
4857 log_error ("p15: error selecting D-TRUST's AID for key %s: %s\n",
4858 keyref, gpg_strerror (err));
4862 /* Standard case: Select the key file. Note that this may
4863 * change the security environment thus we need to do it before
4864 * PIN verification. */
4865 err = select_ef_by_path (app, prkdf->path, prkdf->pathlen);
4867 log_error ("p15: error selecting file for key %s: %s\n",
4868 keyref, gpg_strerror (err));
4872 log_info ("p15: skipping EF selection for auth object '%s'\n", keyref);
4881 any_control_or_space (const char *string)
4883 const unsigned char *s;
4885 for (s = string; *string; string++)
4886 if (*s <= 0x20 || *s >= 0x7f)
4892 /* Return a malloced serial number to be shown to the user. PRKDF is
4893 * used to get it from a certificate; PRKDF may be NULL. */
4895 get_dispserialno (app_t app, prkdf_object_t prkdf)
4899 /* We prefer the SerialNumber RDN from the Subject-DN but we don't
4900 * use it if it features a percent sign (special character in pin
4901 * prompts) or has any control character. */
4902 if (prkdf && prkdf->serial_number && *prkdf->serial_number
4903 && !strchr (prkdf->serial_number, '%')
4904 && !any_control_or_space (prkdf->serial_number))
4906 serial = xtrystrdup (prkdf->serial_number);
4910 serial = app_get_serialno (app);
4916 /* Return an allocated string to be used as prompt. PRKDF may be
4917 * NULL. Returns NULL on malloc error. */
4919 make_pin_prompt (app_t app, int remaining, const char *firstline,
4920 prkdf_object_t prkdf)
4922 char *serial, *tmpbuf, *result;
4925 serial = get_dispserialno (app, prkdf);
4927 if (prkdf && prkdf->common_name)
4928 holder = prkdf->common_name;
4929 else if (app->app_local->token_label)
4930 holder = app->app_local->token_label;
4934 /* TRANSLATORS: Put a \x1f right before a colon. This can be
4935 * used by pinentry to nicely align the names and values. Keep
4936 * the %s at the start and end of the string. */
4937 result = xtryasprintf (_("%s"
4938 "Number\x1f: %s%%0A"
4947 return NULL; /* Out of core. */
4949 /* Append a "remaining attempts" info if needed. */
4950 if (remaining != -1 && remaining < 3)
4954 /* TRANSLATORS: This is the number of remaining attempts to
4955 * enter a PIN. Use %%0A (double-percent,0A) for a linefeed. */
4956 rembuf = xtryasprintf (_("Remaining attempts: %d"), remaining);
4959 tmpbuf = strconcat (firstline, "%0A%0A", result,
4960 "%0A%0A", rembuf, NULL);
4970 tmpbuf = strconcat (firstline, "%0A%0A", result, NULL);
4979 /* Given the private key object PRKDF and its authentication object
4980 * AODF ask for the PIN and verify that PIN. If AODF is NULL, no
4981 * authentication is done. */
4983 verify_pin (app_t app,
4984 gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg,
4985 prkdf_object_t prkdf, aodf_object_t aodf)
5001 pin_reference = aodf->pin_reference_valid? aodf->pin_reference : 0;
5003 if (IS_CARDOS_5 (app))
5005 /* We know that this card supports a verify status check. Note
5006 * that in contrast to PIV cards ISO7816_VERIFY_NOT_NEEDED is
5007 * not supported. Noet that we don't use the pin_verified cache
5008 * status because that is not as reliable than to ask the card
5009 * about its state. */
5010 if (prkdf) /* Clear the cache which we don't use. */
5011 prkdf->pin_verified = 0;
5013 remaining = iso7816_verify_status (app_get_slot (app), pin_reference);
5014 if (remaining == ISO7816_VERIFY_NOT_NEEDED)
5019 else if (remaining < 0)
5020 remaining = -1; /* We don't care about the concrete error. */
5021 else if (remaining < 3)
5022 log_info ("p15: PIN has %d attempts left\n", remaining);
5025 remaining = -1; /* Unknown. */
5027 /* Check whether we already verified it. */
5028 if (prkdf && (prkdf->pin_verified || verified))
5029 return 0; /* Already done. */
5032 && prkdf->usageflags.non_repudiation
5033 && (app->app_local->card_type == CARD_TYPE_BELPIC
5034 || app->app_local->card_product == CARD_PRODUCT_DTRUST))
5035 label = _("||Please enter the PIN for the key to create "
5036 "qualified signatures.");
5037 else if (aodf->pinflags.so_pin)
5038 label = _("|A|Please enter the Admin PIN");
5039 else if (aodf->pinflags.unblocking_pin)
5040 label = _("|P|Please enter the PIN Unblocking Code (PUK) "
5041 "for the standard keys.");
5043 label = _("||Please enter the PIN for the standard keys.");
5046 char *prompt = make_pin_prompt (app, remaining, label, prkdf);
5048 err = gpg_error_from_syserror ();
5050 err = pincb (pincb_arg, prompt, &pinvalue);
5055 log_info ("p15: PIN callback returned error: %s\n", gpg_strerror (err));
5059 /* We might need to cope with UTF8 things here. Not sure how
5060 min_length etc. are exactly defined, for now we take them as
5061 a plain octet count. */
5062 if (strlen (pinvalue) < aodf->min_length)
5064 log_error ("p15: PIN is too short; minimum length is %lu\n",
5066 err = gpg_error (GPG_ERR_BAD_PIN);
5068 else if (aodf->stored_length && strlen (pinvalue) > aodf->stored_length)
5070 /* This would otherwise truncate the PIN silently. */
5071 log_error ("p15: PIN is too large; maximum length is %lu\n",
5072 aodf->stored_length);
5073 err = gpg_error (GPG_ERR_BAD_PIN);
5075 else if (aodf->max_length_valid && strlen (pinvalue) > aodf->max_length)
5077 log_error ("p15: PIN is too large; maximum length is %lu\n",
5079 err = gpg_error (GPG_ERR_BAD_PIN);
5090 switch (aodf->pintype)
5093 case PIN_TYPE_ASCII_NUMERIC:
5094 for (s=pinvalue; digitp (s); s++)
5098 errstr = "Non-numeric digits found in PIN";
5099 err = gpg_error (GPG_ERR_BAD_PIN);
5104 case PIN_TYPE_HALF_NIBBLE_BCD:
5105 errstr = "PIN type Half-Nibble-BCD is not supported";
5107 case PIN_TYPE_ISO9564_1:
5108 errstr = "PIN type ISO9564-1 is not supported";
5111 errstr = "Unknown PIN type";
5116 log_error ("p15: can't verify PIN: %s\n", errstr);
5118 return err? err : gpg_error (GPG_ERR_BAD_PIN_METHOD);
5122 if (aodf->pintype == PIN_TYPE_BCD )
5127 for (ndigits=0, s=pinvalue; *s; ndigits++, s++)
5129 paddedpin = xtrymalloc (aodf->stored_length+1);
5132 err = gpg_error_from_syserror ();
5138 paddedpin[i++] = 0x20 | (ndigits & 0x0f);
5139 for (s=pinvalue; i < aodf->stored_length && *s && s[1]; s = s+2 )
5140 paddedpin[i++] = (((*s - '0') << 4) | ((s[1] - '0') & 0x0f));
5141 if (i < aodf->stored_length && *s)
5142 paddedpin[i++] = (((*s - '0') << 4)
5143 |((aodf->pad_char_valid?aodf->pad_char:0)&0x0f));
5145 if (aodf->pinflags.needs_padding)
5147 while (i < aodf->stored_length)
5148 paddedpin[i++] = aodf->pad_char_valid? aodf->pad_char : 0;
5152 pinvalue = paddedpin;
5155 else if (aodf->pinflags.needs_padding)
5159 paddedpin = xtrymalloc (aodf->stored_length+1);
5162 err = gpg_error_from_syserror ();
5166 for (i=0, s=pinvalue; i < aodf->stored_length && *s; i++, s++)
5168 /* Not sure what padding char to use if none has been set.
5169 For now we use 0x00; maybe a space would be better. */
5170 for (; i < aodf->stored_length; i++)
5171 paddedpin[i] = aodf->pad_char_valid? aodf->pad_char : 0;
5175 pinvalue = paddedpin;
5178 pinvaluelen = strlen (pinvalue);
5180 /* log_printhex (pinvalue, pinvaluelen, */
5181 /* "about to verify with ref %lu pin:", pin_reference); */
5182 err = iso7816_verify (app_get_slot (app), pin_reference,
5183 pinvalue, pinvaluelen);
5187 log_error ("p15: PIN verification failed: %s\n", gpg_strerror (err));
5191 log_info ("p15: PIN verification succeeded\n");
5193 prkdf->pin_verified = 1;
5201 /* Handler for the PKSIGN command.
5203 Create the signature and return the allocated result in OUTDATA.
5204 If a PIN is required, the PINCB will be used to ask for the PIN;
5205 that callback should return the PIN in an allocated buffer and
5206 store that as the 3rd argument. */
5208 do_sign (app_t app, ctrl_t ctrl, const char *keyidstr, int hashalgo,
5209 gpg_error_t (*pincb)(void*, const char *, char **),
5211 const void *indata, size_t indatalen,
5212 unsigned char **outdata, size_t *outdatalen )
5215 prkdf_object_t prkdf; /* The private key object. */
5216 aodf_object_t aodf; /* The associated authentication object. */
5217 int mse_done = 0; /* Set to true if the MSE has been done. */
5218 unsigned int digestlen; /* Length of the hash. */
5219 int exmode, le_value;
5220 unsigned char oidbuf[64];
5223 unsigned char *indata_buffer = NULL; /* Malloced helper. */
5227 if (!keyidstr || !*keyidstr || !indatalen)
5228 return gpg_error (GPG_ERR_INV_VALUE);
5230 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5233 if (!(prkdf->usageflags.sign
5234 || prkdf->usageflags.sign_recover
5235 || prkdf->usageflags.non_repudiation
5236 || prkdf->gpgusage.cert
5237 || prkdf->gpgusage.sign
5238 || prkdf->gpgusage.auth ))
5240 log_error ("p15: key %s may not be used for signing\n", keyidstr);
5241 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
5246 log_error ("p15: no authentication object defined for %s\n", keyidstr);
5247 /* fixme: we might want to go ahead and do without PIN
5249 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
5252 /* Find the authentication object to this private key object. */
5253 for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5254 if (aodf->objidlen == prkdf->authidlen
5255 && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
5258 log_info ("p15: no authentication for %s needed\n", keyidstr);
5260 /* We need some more info about the key - get the keygrip to
5261 * populate these fields. */
5262 err = keygrip_from_prkdf (app, prkdf);
5265 log_error ("p15: keygrip_from_prkdf failed: %s\n", gpg_strerror (err));
5270 digestlen = gcry_md_get_algo_dlen (hashalgo);
5272 /* We handle ECC separately from RSA so that we do not need to touch
5273 * working code. In particular we prepare the input data before the
5274 * verify and a possible MSE. */
5277 if (digestlen != 32 && digestlen != 48 && digestlen != 64)
5279 log_error ("p15: ECC signing not possible: dlen=%u\n", digestlen);
5280 err = gpg_error (GPG_ERR_DIGEST_ALGO);
5284 if (indatalen == digestlen)
5285 ; /* Already prepared. */
5286 else if (indatalen > digestlen)
5288 /* Assume a PKCS#1 prefix and remove it. */
5289 oidbuflen = sizeof oidbuf;
5290 err = gcry_md_get_asnoid (hashalgo, &oidbuf, &oidbuflen);
5293 log_error ("p15: no OID for hash algo %d\n", hashalgo);
5294 err = gpg_error (GPG_ERR_INTERNAL);
5297 if (indatalen != oidbuflen + digestlen
5298 || memcmp (indata, oidbuf, oidbuflen))
5300 log_error ("p15: input data too long for ECC: len=%zu\n",
5302 err = gpg_error (GPG_ERR_INV_VALUE);
5305 indata = (const char*)indata + oidbuflen;
5306 indatalen -= oidbuflen;
5310 log_error ("p15: input data too short for ECC: len=%zu\n",
5312 err = gpg_error (GPG_ERR_INV_VALUE);
5316 else /* Prepare RSA input. */
5318 unsigned int framelen;
5319 unsigned char *frame;
5322 framelen = (prkdf->keynbits+7) / 8;
5325 log_error ("p15: key length unknown"
5326 " - can't prepare PKCS#v1.5 frame\n");
5327 err = gpg_error (GPG_ERR_INV_VALUE);
5331 oidbuflen = sizeof oidbuf;
5334 /* We assume that indata already has the required
5335 * digestinfo; thus merely prepend the padding below. */
5337 else if ((err = gcry_md_get_asnoid (hashalgo, &oidbuf, &oidbuflen)))
5339 log_debug ("p15: no OID for hash algo %d\n", hashalgo);
5344 if (indatalen == digestlen)
5346 /* Plain hash in INDATA; prepend the digestinfo. */
5347 indata_buffer = xtrymalloc (oidbuflen + indatalen);
5350 err = gpg_error_from_syserror ();
5353 memcpy (indata_buffer, oidbuf, oidbuflen);
5354 memcpy (indata_buffer+oidbuflen, indata, indatalen);
5355 indata = indata_buffer;
5356 indatalen = oidbuflen + indatalen;
5358 else if (indatalen == oidbuflen + digestlen
5359 && !memcmp (indata, oidbuf, oidbuflen))
5360 ; /* We already got the correct prefix. */
5363 err = gpg_error (GPG_ERR_INV_VALUE);
5364 log_error ("p15: bad input for signing with RSA and hash %d\n",
5369 /* Now prepend the pkcs#v1.5 padding. We require at least 8
5370 * byte of padding and 3 extra bytes for the prefix and the
5371 * delimiting nul. */
5372 if (!indatalen || indatalen + 8 + 4 > framelen)
5374 err = gpg_error (GPG_ERR_INV_VALUE);
5375 log_error ("p15: input does not fit into a %u bit PKCS#v1.5 frame\n",
5379 frame = xtrymalloc (framelen);
5382 err = gpg_error_from_syserror ();
5385 if (app->app_local->card_type == CARD_TYPE_BELPIC)
5387 /* This card wants only the plain hash w/o any prefix. */
5388 /* FIXME: We may want to remove this code because it is unlikely
5389 * that such cards are still in use. */
5390 memcpy (frame, indata, indatalen);
5391 framelen = indatalen;
5397 frame[n++] = 1; /* Block type. */
5398 i = framelen - indatalen - 3 ;
5399 memset (frame+n, 0xff, i);
5401 frame[n++] = 0; /* Delimiter. */
5402 memcpy (frame+n, indata, indatalen);
5404 log_assert (n == framelen);
5406 /* And now put it into the indata_buffer. */
5407 xfree (indata_buffer);
5408 indata_buffer = frame;
5409 indata = indata_buffer;
5410 indatalen = framelen;
5413 /* Prepare PIN verification. This is split so that we can do
5414 * MSE operation for some task after having selected the key file but
5415 * before sending the verify APDU. */
5416 err = prepare_verify_pin (app, keyidstr, prkdf, aodf);
5420 /* Due to the fact that the non-repudiation signature on a BELPIC
5421 card requires a verify immediately before the DSO we set the
5422 MSE before we do the verification. Other cards might also allow
5423 this but I don't want to break anything, thus we do it only
5424 for the BELPIC card here.
5425 FIXME: see comment above about these cards. */
5426 if (app->app_local->card_type == CARD_TYPE_BELPIC)
5428 unsigned char mse[5];
5430 mse[0] = 4; /* Length of the template. */
5431 mse[1] = 0x80; /* Algorithm reference tag. */
5432 if (hashalgo == MD_USER_TLS_MD5SHA1)
5433 mse[2] = 0x01; /* Let card do pkcs#1 0xFF padding. */
5435 mse[2] = 0x02; /* RSASSA-PKCS1-v1.5 using SHA1. */
5436 mse[3] = 0x84; /* Private key reference tag. */
5437 mse[4] = prkdf->key_reference_valid? prkdf->key_reference : 0x82;
5439 err = iso7816_manage_security_env (app_get_slot (app),
5446 log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5450 /* Now that we have all the information available run the actual PIN
5452 err = verify_pin (app, pincb, pincb_arg, prkdf, aodf);
5456 /* Manage security environment needs to be tweaked for certain cards. */
5459 else if (app->app_local->card_type == CARD_TYPE_TCOS)
5461 /* TCOS creates signatures always using the local key 0. MSE
5464 else if (app->app_local->card_type == CARD_TYPE_MICARDO)
5466 if (!prkdf->pathlen)
5467 err = gpg_error (GPG_ERR_BUG);
5469 err = micardo_mse (app, prkdf->path[prkdf->pathlen-1]);
5471 else if (prkdf->key_reference_valid)
5473 unsigned char mse[3];
5475 mse[0] = 0x84; /* Select asym. key. */
5477 mse[2] = prkdf->key_reference;
5479 err = iso7816_manage_security_env (app_get_slot (app),
5485 log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5489 if (prkdf->keyalgo == GCRY_PK_RSA && prkdf->keynbits > 2048)
5492 le_value = prkdf->keynbits / 8;
5500 err = iso7816_compute_ds (app_get_slot (app),
5501 exmode, indata, indatalen,
5502 le_value, outdata, outdatalen);
5505 xfree (indata_buffer);
5510 /* Handler for the PKAUTH command.
5512 This is basically the same as the PKSIGN command but we first check
5513 that the requested key is suitable for authentication; that is, it
5514 must match the criteria used for the attribute $AUTHKEYID. See
5515 do_sign for calling conventions; there is no HASHALGO, though. */
5517 do_auth (app_t app, ctrl_t ctrl, const char *keyidstr,
5518 gpg_error_t (*pincb)(void*, const char *, char **),
5520 const void *indata, size_t indatalen,
5521 unsigned char **outdata, size_t *outdatalen )
5524 prkdf_object_t prkdf;
5527 if (!keyidstr || !*keyidstr)
5528 return gpg_error (GPG_ERR_INV_VALUE);
5530 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5533 if (!(prkdf->usageflags.sign || prkdf->gpgusage.auth))
5535 log_error ("p15: key %s may not be used for authentication\n", keyidstr);
5536 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
5539 algo = indatalen == 36? MD_USER_TLS_MD5SHA1 : GCRY_MD_SHA1;
5540 return do_sign (app, ctrl, keyidstr, algo, pincb, pincb_arg,
5541 indata, indatalen, outdata, outdatalen);
5545 /* Handler for the PKDECRYPT command. Decrypt the data in INDATA and
5546 * return the allocated result in OUTDATA. If a PIN is required the
5547 * PINCB will be used to ask for the PIN; it should return the PIN in
5548 * an allocated buffer and put it into PIN. */
5550 do_decipher (app_t app, ctrl_t ctrl, const char *keyidstr,
5551 gpg_error_t (*pincb)(void*, const char *, char **),
5553 const void *indata, size_t indatalen,
5554 unsigned char **outdata, size_t *outdatalen,
5555 unsigned int *r_info)
5558 prkdf_object_t prkdf; /* The private key object. */
5559 aodf_object_t aodf; /* The associated authentication object. */
5560 int exmode, le_value, padind;
5565 if (!keyidstr || !*keyidstr)
5566 return gpg_error (GPG_ERR_INV_VALUE);
5567 if (!indatalen || !indata || !outdatalen || !outdata)
5568 return gpg_error (GPG_ERR_INV_ARG);
5570 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5573 if (!(prkdf->usageflags.decrypt
5574 || prkdf->usageflags.unwrap
5575 || prkdf->gpgusage.encr ))
5577 log_error ("p15: key %s may not be used for decryption\n", keyidstr);
5578 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
5581 /* Find the authentication object to this private key object. */
5584 log_error ("p15: no authentication object defined for %s\n", keyidstr);
5585 /* fixme: we might want to go ahead and do without PIN
5587 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
5589 for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5590 if (aodf->objidlen == prkdf->authidlen
5591 && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
5594 log_info ("p15: no authentication for %s needed\n", keyidstr);
5596 /* We need some more info about the key - get the keygrip to
5597 * populate these fields. */
5598 err = keygrip_from_prkdf (app, prkdf);
5601 log_error ("p15: keygrip_from_prkdf failed: %s\n", gpg_strerror (err));
5605 /* Verify the PIN. */
5606 err = prepare_verify_pin (app, keyidstr, prkdf, aodf);
5608 err = verify_pin (app, pincb, pincb_arg, prkdf, aodf);
5612 if (prkdf->is_ecc && IS_CARDOS_5(app))
5615 err = iso7816_manage_security_env (app_get_slot (app), 0xF3, 0x01,
5619 log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5625 /* The next is guess work for CardOS. */
5626 if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
5628 /* From analyzing an USB trace of a Windows signing application
5629 * we see that the SE is simply reset to 0x14. It seems to be
5630 * sufficient to do this for decryption; signing still works
5631 * with the standard code despite that our trace showed that
5632 * there the SE is restored to 0x09. Note that the special
5633 * D-Trust AID is in any case select by prepare_verify_pin.
5635 * Hey, D-Trust please hand over the specs so that you can
5636 * actually sell your cards and we can properly implement it;
5637 * other vendors understand this and do not demand ridiculous
5638 * paper work or complicated procedures to get samples. */
5639 err = iso7816_manage_security_env (app_get_slot (app),
5640 0xF3, 0x14, NULL, 0);
5643 else if (prkdf->key_reference_valid)
5645 unsigned char mse[9];
5648 /* Note: This works with CardOS but the D-Trust card has the
5649 * problem that the next created signature would be broken. */
5654 mse[i++] = 0x80; /* Algorithm reference. */
5656 mse[i++] = 0x0a; /* RSA, no padding. */
5658 mse[i++] = 0x84; /* Key reference. */
5660 mse[i++] = prkdf->key_reference;
5661 if (prkdf->is_ecc && IS_CARDOS_5(app))
5663 mse[i++] = 0x95; /* ???. */
5667 log_assert (i <= DIM(mse));
5668 err = iso7816_manage_security_env (app_get_slot (app), 0x41, 0xB8,
5671 /* Check for MSE error. */
5674 log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5678 exmode = le_value = 0;
5680 if (prkdf->keyalgo == GCRY_PK_RSA && prkdf->keynbits > 2048)
5682 exmode = 1; /* Extended length w/o a limit. */
5683 le_value = prkdf->keynbits / 8;
5686 if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
5689 if (prkdf->is_ecc && IS_CARDOS_5(app))
5691 if ((indatalen & 1) && *(const char *)indata == 0x04)
5693 /* Strip indicator byte. */
5695 indata = (const char *)indata + 1;
5697 err = iso7816_pso_csv (app_get_slot (app), exmode,
5700 outdata, outdatalen);
5704 err = iso7816_decipher (app_get_slot (app), exmode,
5707 outdata, outdatalen);
5714 /* Perform a simple verify operation for the PIN specified by
5715 * KEYIDSTR. Note that we require a key reference which is then used
5716 * to select the authentication object. Return GPG_ERR_NO_PIN if a
5717 * PIN is not required for using the private key KEYIDSTR. */
5719 do_check_pin (app_t app, ctrl_t ctrl, const char *keyidstr,
5720 gpg_error_t (*pincb)(void*, const char *, char **),
5724 prkdf_object_t prkdf; /* The private key object. */
5725 aodf_object_t aodf; /* The associated authentication object. */
5729 if (!keyidstr || !*keyidstr)
5730 return gpg_error (GPG_ERR_INV_VALUE);
5732 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5734 && gpg_err_code (err) != GPG_ERR_INV_ID
5735 && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
5738 if (err) /* Not found or invalid - assume it is the label. */
5741 for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5742 if (aodf->label && !ascii_strcasecmp (aodf->label, keyidstr))
5745 return err; /* Re-use the original error code. */
5747 else /* Find the authentication object to this private key object. */
5751 log_error ("p15: no authentication object defined for %s\n",
5753 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
5755 for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5756 if (aodf->objidlen == prkdf->authidlen
5757 && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
5759 if (!aodf) /* None found. */
5760 return gpg_error (GPG_ERR_NO_PIN);
5763 err = prepare_verify_pin (app, keyidstr, prkdf, aodf);
5765 err = verify_pin (app, pincb, pincb_arg, prkdf, aodf);
5771 /* Process the various keygrip based info requests. */
5773 do_with_keygrip (app_t app, ctrl_t ctrl, int action,
5774 const char *want_keygripstr, int capability)
5777 char *serialno = NULL;
5779 prkdf_object_t prkdf;
5781 /* First a quick check for valid parameters. */
5784 case KEYGRIP_ACTION_LOOKUP:
5785 if (!want_keygripstr)
5787 err = gpg_error (GPG_ERR_NOT_FOUND);
5791 case KEYGRIP_ACTION_SEND_DATA:
5794 case KEYGRIP_ACTION_WRITE_STATUS:
5797 err = gpg_error (GPG_ERR_INV_ARG);
5801 /* Allocate the s/n string if needed. */
5802 if (action != KEYGRIP_ACTION_LOOKUP)
5804 serialno = app_get_serialno (app);
5807 err = gpg_error_from_syserror ();
5812 for (prkdf = app->app_local->private_key_info;
5813 prkdf; prkdf = prkdf->next)
5815 if (keygrip_from_prkdf (app, prkdf))
5818 if (action == KEYGRIP_ACTION_LOOKUP)
5820 if (!strcmp (prkdf->keygrip, want_keygripstr))
5822 err = 0; /* Found */
5826 else if (!want_keygripstr || !strcmp (prkdf->keygrip, want_keygripstr))
5830 if (capability == GCRY_PK_USAGE_SIGN)
5832 if (!(prkdf->usageflags.sign || prkdf->usageflags.sign_recover
5833 || prkdf->usageflags.non_repudiation))
5836 else if (capability == GCRY_PK_USAGE_ENCR)
5838 if (!(prkdf->usageflags.decrypt || prkdf->usageflags.unwrap))
5841 else if (capability == GCRY_PK_USAGE_AUTH)
5843 if (!(prkdf->usageflags.sign || prkdf->usageflags.sign_recover))
5847 keyref = keyref_from_prkdf (app, prkdf);
5850 err = gpg_error_from_syserror ();
5854 send_keyinfo (ctrl, as_data, prkdf->keygrip, serialno, keyref);
5856 if (want_keygripstr)
5858 err = 0; /* Found */
5864 /* Return an error so that the dispatcher keeps on looping over the
5865 * other applications. For clarity we use a different error code
5866 * when listing all keys. Note that in lookup mode WANT_KEYGRIPSTR
5868 if (!want_keygripstr)
5869 err = gpg_error (GPG_ERR_TRUE);
5871 err = gpg_error (GPG_ERR_NOT_FOUND);
5880 /* Assume that EF(DIR) has been selected. Read its content and figure
5881 out the home EF of pkcs#15. Return that home DF or 0 if not found
5882 and the value at the address of BELPIC indicates whether it was
5883 found by the belpic aid. */
5884 static unsigned short
5885 read_home_df (int slot, int *r_belpic)
5888 unsigned char *buffer;
5889 const unsigned char *p, *pp;
5890 size_t buflen, n, nn;
5891 unsigned short result = 0;
5895 err = iso7816_read_binary (slot, 0, 0, &buffer, &buflen);
5898 log_error ("p15: error reading EF(DIR): %s\n", gpg_strerror (err));
5902 /* FIXME: We need to scan all records. */
5903 p = find_tlv (buffer, buflen, 0x61, &n);
5906 pp = find_tlv (p, n, 0x4f, &nn);
5907 if (pp && ((nn == sizeof pkcs15_aid && !memcmp (pp, pkcs15_aid, nn))
5908 || (*r_belpic = (nn == sizeof pkcs15be_aid
5909 && !memcmp (pp, pkcs15be_aid, nn)))))
5911 pp = find_tlv (p, n, 0x50, &nn);
5912 if (pp && opt.verbose)
5913 log_info ("p15: application label from EF(DIR) is '%.*s'\n",
5915 pp = find_tlv (p, n, 0x51, &nn);
5916 if (pp && nn == 4 && *pp == 0x3f && !pp[1])
5918 result = ((pp[2] << 8) | pp[3]);
5920 log_info ("p15: application directory is 0x%04hX\n", result);
5930 Select the PKCS#15 application on the card in SLOT.
5933 app_select_p15 (app_t app)
5935 int slot = app_get_slot (app);
5937 unsigned short def_home_df = 0;
5938 card_type_t card_type = CARD_TYPE_UNKNOWN;
5941 unsigned char *fci = NULL;
5944 rc = iso7816_select_application_ext (slot, pkcs15_aid, sizeof pkcs15_aid, 1,
5947 { /* Not found: Try to locate it from 2F00. We use direct path
5948 selection here because it seems that the Belgian eID card
5949 does only allow for that. Many other cards supports this
5950 selection method too. Note, that we don't use
5951 select_application above for the Belgian card - the call
5952 works but it seems that it does not switch to the correct DF.
5953 Using the 2f02 just works. */
5954 unsigned short path[1] = { 0x2f00 };
5956 rc = iso7816_select_path (slot, path, 1, 0);
5960 def_home_df = read_home_df (slot, &is_belpic);
5963 path[0] = def_home_df;
5964 rc = iso7816_select_path (slot, path, 1, 0);
5969 { /* Still not found: Try the default DF. */
5970 def_home_df = DEFAULT_HOME_DF;
5971 rc = iso7816_select_file (slot, def_home_df, 1);
5975 /* Determine the type of the card. The general case is to look
5976 it up from the ATR table. For the Belgian eID card we know
5977 it instantly from the AID. */
5980 card_type = CARD_TYPE_BELPIC;
5988 atr = apdu_get_atr (app_get_slot (app), &atrlen);
5990 rc = gpg_error (GPG_ERR_INV_CARD);
5993 for (i=0; card_atr_list[i].atrlen; i++)
5994 if (card_atr_list[i].atrlen == atrlen
5995 && !memcmp (card_atr_list[i].atr, atr, atrlen))
5997 card_type = card_atr_list[i].type;
6006 app->apptype = APPTYPE_P15;
6008 app->app_local = xtrycalloc (1, sizeof *app->app_local);
6009 if (!app->app_local)
6011 rc = gpg_error_from_syserror ();
6015 /* Set the home DF from the FCI returned by the select. */
6016 if (!def_home_df && fci)
6018 const unsigned char *s;
6021 s = find_tlv (fci, fcilen, 0x83, &n);
6023 def_home_df = buf16_to_ushort (s);
6025 log_error ("p15: select(AID) did not return the DF\n");
6027 app->app_local->home_df = def_home_df;
6029 /* Store the card type. FIXME: We might want to put this into
6030 the common APP structure. */
6031 app->app_local->card_type = card_type;
6033 app->app_local->card_product = CARD_PRODUCT_UNKNOWN;
6035 /* Store whether we may and should use direct path selection. */
6038 case CARD_TYPE_CARDOS_50:
6039 case CARD_TYPE_CARDOS_53:
6043 /* Use whatever has been determined above. */
6046 app->app_local->direct_path_selection = direct;
6048 /* Read basic information and thus check whether this is a real
6050 rc = read_p15_info (app);
6054 /* Special serial number munging. We need to check for a German
6055 prototype card right here because we need to access to
6056 EF(TokenInfo). We mark such a serial number by the using a
6057 prefix of FF0100. */
6058 if (APP_CARD(app)->serialnolen == 12
6059 && !memcmp (APP_CARD(app)->serialno,
6060 "\xD2\x76\0\0\0\0\0\0\0\0\0\0", 12))
6062 /* This is a German card with a silly serial number. Try to get
6063 the serial number from the EF(TokenInfo). . */
6066 /* FIXME: actually get it from EF(TokenInfo). */
6068 p = xtrymalloc (3 + APP_CARD(app)->serialnolen);
6070 rc = gpg_error (gpg_err_code_from_errno (errno));
6073 memcpy (p, "\xff\x01", 3);
6074 memcpy (p+3, APP_CARD(app)->serialno, APP_CARD(app)->serialnolen);
6075 APP_CARD(app)->serialnolen += 3;
6076 xfree (APP_CARD(app)->serialno);
6077 APP_CARD(app)->serialno = p;
6081 app->fnc.deinit = do_deinit;
6082 app->fnc.prep_reselect = NULL;
6083 app->fnc.reselect = NULL;
6084 app->fnc.learn_status = do_learn_status;
6085 app->fnc.readcert = do_readcert;
6086 app->fnc.getattr = do_getattr;
6087 app->fnc.setattr = NULL;
6088 app->fnc.genkey = NULL;
6089 app->fnc.sign = do_sign;
6090 app->fnc.auth = do_auth;
6091 app->fnc.decipher = do_decipher;
6092 app->fnc.change_pin = NULL;
6093 app->fnc.check_pin = do_check_pin;
6094 app->fnc.with_keygrip = do_with_keygrip;