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 "R&S";
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 && !strncmp (app->app_local->token_label, "D-TRUST Card V3", 15)
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),
3860 /* Get the keygrip of the private key object PRKDF. On success the
3861 * keygrip, the algo and the length are stored in the KEYGRIP,
3862 * KEYALGO, and KEYNBITS fields of the PRKDF object. */
3864 keygrip_from_prkdf (app_t app, prkdf_object_t prkdf)
3871 gcry_sexp_t s_pkey = NULL;
3873 /* Easy if we got a cached version. */
3874 if (prkdf->keygrip_valid)
3877 xfree (prkdf->common_name);
3878 prkdf->common_name = NULL;
3879 xfree (prkdf->serial_number);
3880 prkdf->serial_number = NULL;
3882 /* We could have also checked whether a public key directory file
3883 * and a matching public key for PRKDF is available. This would
3884 * make extraction of the key faster. However, this way we don't
3885 * have a way to look at extended key attributes to check gpgusage.
3886 * FIXME: Add public key lookup if no certificate was found. */
3888 /* Look for a matching certificate. A certificate matches if the id
3889 * matches the one of the private key info. If none was found we
3890 * also try to match on the label. */
3891 err = cdf_object_from_objid (app, prkdf->objidlen, prkdf->objid, &cdf);
3892 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
3893 err = cdf_object_from_label (app, prkdf->label, &cdf);
3895 err = gpg_error (GPG_ERR_NOT_FOUND);
3899 err = readcert_by_cdf (app, cdf, &der, &derlen);
3903 err = ksba_cert_new (&cert);
3905 err = ksba_cert_init_from_mem (cert, der, derlen);
3908 err = app_help_get_keygrip_string (cert, prkdf->keygrip, &s_pkey, NULL);
3909 if (!err && !prkdf->gpgusage.any)
3911 /* Try to get the CN and the SerialNumber from the certificate;
3912 * we use a very simple approach here which should work in many
3913 * cases. Eventually we should add a rfc-2253 parser into
3914 * libksba to make it easier to parse such a string.
3915 * We don't do this if this is marked as gpg key and thus
3916 * has only a dummy certificate.
3918 * First example string:
3919 * "CN=Otto Schily,O=Miniluv,C=DE"
3920 * Second example string:
3921 * "2.5.4.5=#445452323030303236333531,2.5.4.4=#4B6F6368,"
3922 * "2.5.4.42=#5765726E6572,CN=Werner Koch,OU=For testing"
3923 * " purposes only!,O=Testorganisation,C=DE"
3925 char *dn = ksba_cert_get_subject (cert, 0);
3928 char *p, *pend, *buf;
3930 p = strstr (dn, "CN=");
3931 if (p && (p==dn || p[-1] == ','))
3934 if (!(pend = strchr (p, ',')))
3935 pend = p + strlen (p);
3936 if (pend && pend > p
3937 && (prkdf->common_name = xtrymalloc ((pend - p) + 1)))
3939 memcpy (prkdf->common_name, p, pend-p);
3940 prkdf->common_name[pend-p] = 0;
3943 p = strstr (dn, "2.5.4.5=#"); /* OID of the SerialNumber */
3944 if (p && (p==dn || p[-1] == ','))
3947 if (!(pend = strchr (p, ',')))
3948 pend = p + strlen (p);
3949 if (pend && pend > p
3950 && (buf = xtrymalloc ((pend - p) + 1)))
3952 memcpy (buf, p, pend-p);
3954 if (!hex2str (buf, buf, strlen (buf)+1, NULL))
3955 xfree (buf); /* Invalid hex encoding. */
3957 prkdf->serial_number = buf;
3964 if (!err && !prkdf->keytime)
3966 ksba_isotime_t isot;
3969 ksba_cert_get_validity (cert, 0, isot);
3970 t = isotime2epoch (isot);
3971 prkdf->keytime = (t == (time_t)(-1))? 0 : (u32)t;
3972 prkdf->have_keytime = 1;
3975 if (!err && !prkdf->keyalgostr)
3976 prkdf->keyalgostr = pubkey_algo_string (s_pkey, NULL);
3978 ksba_cert_release (cert);
3982 prkdf->keyalgo = get_pk_algo_from_key (s_pkey);
3983 if (!prkdf->keyalgo)
3985 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
3989 prkdf->keynbits = gcry_pk_get_nbits (s_pkey);
3990 if (!prkdf->keynbits)
3992 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
3996 prkdf->keygrip_valid = 1; /* Yeah, got everything. */
3999 gcry_sexp_release (s_pkey);
4004 /* Return a malloced keyref string for PRKDF. Returns NULL on
4005 * malloc failure. */
4007 keyref_from_prkdf (app_t app, prkdf_object_t prkdf)
4011 buf = xtrymalloc (4 + 5 + prkdf->objidlen*2 + 1);
4014 p = stpcpy (buf, "P15");
4015 if (app->app_local->home_df != DEFAULT_HOME_DF)
4017 snprintf (p, 6, "-%04X",
4018 (unsigned int)(app->app_local->home_df & 0xffff));
4021 p = stpcpy (p, ".");
4022 bin2hex (prkdf->objid, prkdf->objidlen, p);
4027 /* Helper to do_learn_status: Send information about all known
4028 keypairs back. FIXME: much code duplication from
4031 send_keypairinfo (app_t app, ctrl_t ctrl, prkdf_object_t prkdf)
4035 for (; prkdf; prkdf = prkdf->next)
4040 buf = keyref_from_prkdf (app, prkdf);
4042 return gpg_error_from_syserror ();
4044 err = keygrip_from_prkdf (app, prkdf);
4047 log_error ("p15: error getting keygrip from ");
4048 for (j=0; j < prkdf->pathlen; j++)
4049 log_printf ("%s%04hX", j?"/":"", prkdf->path[j]);
4050 log_printf (": %s\n", gpg_strerror (err));
4056 const char *algostr;
4057 size_t usagelen = 0;
4059 if (prkdf->gpgusage.any)
4061 if (prkdf->gpgusage.sign)
4062 usage[usagelen++] = 's';
4063 if (prkdf->gpgusage.cert)
4064 usage[usagelen++] = 'c';
4065 if (prkdf->gpgusage.encr)
4066 usage[usagelen++] = 'e';
4067 if (prkdf->gpgusage.auth)
4068 usage[usagelen++] = 'a';
4072 if ((prkdf->usageflags.sign
4073 || prkdf->usageflags.sign_recover
4074 || prkdf->usageflags.non_repudiation)
4075 && (!prkdf->extusage.valid
4076 || prkdf->extusage.sign))
4077 usage[usagelen++] = 's';
4078 if ((prkdf->usageflags.sign
4079 || prkdf->usageflags.sign_recover)
4080 && (!prkdf->extusage.valid || prkdf->extusage.sign))
4081 usage[usagelen++] = 'c';
4082 if ((prkdf->usageflags.decrypt
4083 || prkdf->usageflags.unwrap)
4084 && (!prkdf->extusage.valid || prkdf->extusage.encr))
4085 usage[usagelen++] = 'e';
4086 if ((prkdf->usageflags.sign
4087 || prkdf->usageflags.sign_recover)
4088 && (!prkdf->extusage.valid || prkdf->extusage.auth))
4089 usage[usagelen++] = 'a';
4092 log_assert (strlen (prkdf->keygrip) == 40);
4093 if (prkdf->keytime && prkdf->have_keytime)
4094 snprintf (keytime, sizeof keytime, "%lu",
4095 (unsigned long)prkdf->keytime);
4097 strcpy (keytime, "-");
4099 algostr = prkdf->keyalgostr;
4101 send_status_info (ctrl, "KEYPAIRINFO",
4102 prkdf->keygrip, 2*KEYGRIP_LEN,
4105 keytime, strlen (keytime),
4106 algostr, strlen (algostr?algostr:""),
4116 /* This is the handler for the LEARN command. Note that if
4117 * APP_LEARN_FLAG_REREAD is set and this function returns an error,
4118 * the caller must deinitialize this application. */
4120 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
4124 if (flags & APP_LEARN_FLAG_REREAD)
4126 err = read_p15_info (app);
4131 if ((flags & APP_LEARN_FLAG_KEYPAIRINFO))
4135 err = do_getattr (app, ctrl, "MANUFACTURER");
4137 err = send_certinfo (app, ctrl, "100",
4138 app->app_local->certificate_info);
4140 err = send_certinfo (app, ctrl, "101",
4141 app->app_local->trusted_certificate_info);
4143 err = send_certinfo (app, ctrl, "102",
4144 app->app_local->useful_certificate_info);
4148 err = send_keypairinfo (app, ctrl, app->app_local->private_key_info);
4151 err = do_getattr (app, ctrl, "CHV-STATUS");
4153 err = do_getattr (app, ctrl, "CHV-LABEL");
4160 /* Read a certificate using the information in CDF and return the
4161 * certificate in a newly malloced buffer R_CERT and its length
4162 * R_CERTLEN. Also parses the certificate. R_CERT and R_CERTLEN may
4163 * be NULL to do just the caching. */
4165 readcert_by_cdf (app_t app, cdf_object_t cdf,
4166 unsigned char **r_cert, size_t *r_certlen)
4169 unsigned char *buffer = NULL;
4170 const unsigned char *p, *save_p;
4172 int class, tag, constructed, ndef;
4173 size_t totobjlen, objlen, hdrlen;
4182 /* First check whether it has been cached. */
4185 const unsigned char *image;
4188 if (!r_cert || !r_certlen)
4189 return 0; /* Caller does not actually want the result. */
4191 image = ksba_cert_get_image (cdf->cert, &imagelen);
4194 log_error ("p15: ksba_cert_get_image failed\n");
4195 return gpg_error (GPG_ERR_INTERNAL);
4197 *r_cert = xtrymalloc (imagelen);
4199 return gpg_error_from_syserror ();
4200 memcpy (*r_cert, image, imagelen);
4201 *r_certlen = imagelen;
4205 /* Read the entire file. fixme: This could be optimized by first
4206 reading the header to figure out how long the certificate
4208 err = select_ef_by_path (app, cdf->path, cdf->pathlen);
4212 err = iso7816_read_binary_ext (app_get_slot (app), 1, cdf->off, cdf->len,
4213 &buffer, &buflen, NULL);
4214 if (!err && (!buflen || *buffer == 0xff))
4215 err = gpg_error (GPG_ERR_NOT_FOUND);
4218 log_error ("p15: error reading certificate id=");
4219 for (i=0; i < cdf->objidlen; i++)
4220 log_printf ("%02X", cdf->objid[i]);
4221 log_printf (" at ");
4222 for (i=0; i < cdf->pathlen; i++)
4223 log_printf ("%s%04hX", i? "/":"", cdf->path[i]);
4224 log_printf (": %s\n", gpg_strerror (err));
4228 /* Check whether this is really a certificate. */
4231 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
4232 &ndef, &objlen, &hdrlen);
4236 if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed)
4238 else if ( class == CLASS_UNIVERSAL && tag == TAG_SET && constructed )
4242 err = gpg_error (GPG_ERR_INV_OBJ);
4245 totobjlen = objlen + hdrlen;
4246 log_assert (totobjlen <= buflen);
4248 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
4249 &ndef, &objlen, &hdrlen);
4254 && class == CLASS_UNIVERSAL && tag == TAG_OBJECT_ID && !constructed)
4256 /* The certificate seems to be contained in a userCertificate
4257 container. Skip this and assume the following sequence is
4261 err = gpg_error (GPG_ERR_INV_OBJ);
4267 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
4268 &ndef, &objlen, &hdrlen);
4271 if ( !(class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed) )
4273 err = gpg_error (GPG_ERR_INV_OBJ);
4276 totobjlen = objlen + hdrlen;
4277 log_assert (save_p + totobjlen <= buffer + buflen);
4278 memmove (buffer, save_p, totobjlen);
4282 /* Try to parse and cache the certificate. */
4283 err = ksba_cert_new (&cdf->cert);
4286 err = ksba_cert_init_from_mem (cdf->cert, buffer, totobjlen);
4287 if (!err) /* Call us to use the just cached cert object. */
4288 err = readcert_by_cdf (app, cdf, r_cert, r_certlen);
4291 ksba_cert_release (cdf->cert);
4298 log_error ("p15: caching certificate failed: %s\n",
4299 gpg_strerror (err));
4300 /* We return the certificate anyway so that the caller has a
4301 * chance to get an even unsupported or broken certificate. */
4302 if (r_cert && r_certlen)
4306 *r_certlen = totobjlen;
4316 /* Handler for the READCERT command.
4318 Read the certificate with id CERTID (as returned by learn_status in
4319 the CERTINFO status lines) and return it in the freshly allocated
4320 buffer to be stored at R_CERT and its length at R_CERTLEN. A error
4321 code will be returned on failure and R_CERT and R_CERTLEN will be
4324 do_readcert (app_t app, const char *certid,
4325 unsigned char **r_cert, size_t *r_certlen)
4332 err = cdf_object_from_certid (app, certid, &cdf);
4334 err = readcert_by_cdf (app, cdf, r_cert, r_certlen);
4339 /* Sort helper for an array of authentication objects. */
4341 compare_aodf_objid (const void *arg_a, const void *arg_b)
4343 const aodf_object_t a = *(const aodf_object_t *)arg_a;
4344 const aodf_object_t b = *(const aodf_object_t *)arg_b;
4347 rc = memcmp (a->objid, b->objid,
4348 a->objidlen < b->objidlen? a->objidlen : b->objidlen);
4351 if (a->objidlen < b->objidlen)
4353 else if (a->objidlen > b->objidlen)
4361 send_key_fpr_line (ctrl_t ctrl, int number, const unsigned char *fpr)
4366 bin2hex (fpr, 20, buf);
4368 *numbuf = 0; /* Don't print the key number */
4370 snprintf (numbuf, sizeof numbuf, "%d", number);
4371 send_status_info (ctrl, "KEY-FPR",
4372 numbuf, (size_t)strlen(numbuf),
4373 buf, (size_t)strlen (buf),
4378 /* If possible Emit a FPR-KEY status line for the private key object
4379 * PRKDF using NUMBER as index. */
4381 send_key_fpr (app_t app, ctrl_t ctrl, prkdf_object_t prkdf, int number)
4385 unsigned char *pk, *fixed_pk;
4386 size_t pklen, fixed_pklen;
4387 const unsigned char *m, *e, *q;
4388 size_t mlen, elen, qlen;
4389 unsigned char fpr20[20];
4391 if (cdf_object_from_objid (app, prkdf->objidlen, prkdf->objid, &cdf)
4392 && cdf_object_from_label (app, prkdf->label, &cdf))
4395 readcert_by_cdf (app, cdf, NULL, NULL);
4398 if (!prkdf->have_keytime)
4400 pk = ksba_cert_get_public_key (cdf->cert);
4403 pklen = gcry_sexp_canon_len (pk, 0, NULL, &err);
4405 if (uncompress_ecc_q_in_canon_sexp (pk, pklen, &fixed_pk, &fixed_pklen))
4412 xfree (pk); pk = NULL;
4414 pklen = fixed_pklen;
4417 switch (prkdf->keyalgo)
4420 if (!get_rsa_pk_from_canon_sexp (pk, pklen,
4421 &m, &mlen, &e, &elen)
4422 && !compute_openpgp_fpr_rsa (4,
4426 send_key_fpr_line (ctrl, number, fpr20);
4433 /* Note that NUMBER 2 indicates the encryption key. */
4434 if (!get_ecc_q_from_canon_sexp (pk, pklen, &q, &qlen)
4435 && !compute_openpgp_fpr_ecc (4,
4442 send_key_fpr_line (ctrl, number, fpr20);
4445 default: /* No Fingerprint for an unknown algo. */
4453 /* Implement the GETATTR command. This is similar to the LEARN
4454 command but returns just one value via the status interface. */
4456 do_getattr (app_t app, ctrl_t ctrl, const char *name)
4459 prkdf_object_t prkdf;
4461 if (!strcmp (name, "$AUTHKEYID")
4462 || !strcmp (name, "$ENCRKEYID")
4463 || !strcmp (name, "$SIGNKEYID"))
4467 /* We return the ID of the first private key capable of the
4468 * requested action. If any gpgusage flag has been set for the
4469 * card we consult the gpgusage flags and not the regualr usage
4472 /* FIXME: This changed: Note that we do not yet return
4473 * non_repudiation keys for $SIGNKEYID because our D-Trust
4474 * testcard uses rsaPSS, which is not supported by gpgsm and not
4475 * covered by the VS-NfD approval. */
4476 for (prkdf = app->app_local->private_key_info; prkdf;
4477 prkdf = prkdf->next)
4479 if (app->app_local->any_gpgusage)
4481 if ((name[1] == 'A' && prkdf->gpgusage.auth)
4482 || (name[1] == 'E' && prkdf->gpgusage.encr)
4483 || (name[1] == 'S' && prkdf->gpgusage.sign))
4488 if ((name[1] == 'A' && (prkdf->usageflags.sign
4489 || prkdf->usageflags.sign_recover))
4490 || (name[1] == 'E' && (prkdf->usageflags.decrypt
4491 || prkdf->usageflags.unwrap))
4492 || (name[1] == 'S' && (prkdf->usageflags.sign
4493 || prkdf->usageflags.sign_recover)))
4499 buf = keyref_from_prkdf (app, prkdf);
4501 return gpg_error_from_syserror ();
4503 send_status_info (ctrl, name, buf, strlen (buf), NULL, 0);
4508 else if (!strcmp (name, "$DISPSERIALNO"))
4510 /* For certain cards we return special IDs. There is no
4511 general rule for it so we need to decide case by case. */
4512 if (app->app_local->card_type == CARD_TYPE_BELPIC)
4514 /* The eID card has a card number printed on the front matter
4515 which seems to be a good indication. */
4516 unsigned char *buffer;
4517 const unsigned char *p;
4519 unsigned short path[] = { 0x3F00, 0xDF01, 0x4031 };
4521 err = select_ef_by_path (app, path, DIM(path) );
4523 err = iso7816_read_binary (app_get_slot (app), 0, 0,
4527 log_error ("p15: error accessing EF(ID): %s\n",
4528 gpg_strerror (err));
4532 p = find_tlv (buffer, buflen, 1, &n);
4538 memcpy (tmp+4, p+3, 7);
4540 memcpy (tmp+12, p+10, 2);
4542 send_status_info (ctrl, name, tmp, strlen (tmp), NULL, 0);
4552 /* We use the first private key object which has a serial
4553 * number set. If none was found, we parse the first
4554 * object and see whether this has then a serial number. */
4555 for (prkdf = app->app_local->private_key_info; prkdf;
4556 prkdf = prkdf->next)
4557 if (prkdf->serial_number)
4559 if (!prkdf && app->app_local->private_key_info)
4561 prkdf = app->app_local->private_key_info;
4562 keygrip_from_prkdf (app, prkdf);
4563 if (!prkdf->serial_number)
4566 sn = get_dispserialno (app, prkdf);
4567 /* Unless there is a bogus S/N in the cert, or the product
4568 * has a different strategy for the display-s/n, we should
4569 * have a suitable one from the cert now. */
4572 err = send_status_printf (ctrl, name, "%s", sn);
4577 /* No abbreviated serial number. */
4579 else if (!strcmp (name, "MANUFACTURER"))
4581 if (app->app_local->manufacturer_id
4582 && !strchr (app->app_local->manufacturer_id, '[')
4583 && app->app_local->card_product)
4584 return send_status_printf (ctrl, "MANUFACTURER", "0 %s [%s]",
4585 app->app_local->manufacturer_id,
4586 cardproduct2str (app->app_local->card_product));
4587 else if (app->app_local->manufacturer_id)
4588 return send_status_printf (ctrl, "MANUFACTURER", "0 %s",
4589 app->app_local->manufacturer_id);
4593 else if (!strcmp (name, "CHV-STATUS") || !strcmp (name, "CHV-LABEL"))
4595 int is_label = (name[4] == 'L');
4597 aodf_object_t aodfarray[16];
4603 /* Put the AODFs into an array for easier sorting. Note that we
4604 * handle onl the first 16 encountrer which should be more than
4606 for (aodf = app->app_local->auth_object_info;
4607 aodf && naodf < DIM(aodfarray); aodf = aodf->next)
4608 if (aodf->objidlen && aodf->pin_reference_valid)
4609 aodfarray[naodf++] = aodf;
4610 qsort (aodfarray, naodf, sizeof *aodfarray, compare_aodf_objid);
4612 init_membuf (&mb, 256);
4613 for (i = 0; i < naodf; i++)
4616 /* log_debug ("p15: AODF[%d] pinref=%lu id=", */
4617 /* i, aodfarray[i]->pin_reference); */
4618 /* for (j=0; j < aodfarray[i]->objidlen; j++) */
4619 /* log_printf ("%02X", aodfarray[i]->objid[j]); */
4620 /* Note that there is no need to percent escape the label
4621 * because all white space have been replaced by '_'. */
4623 put_membuf_printf (&mb, "%s%s", i? " ":"",
4624 (aodfarray[i]->label
4625 && *aodfarray[i]->label)?
4626 aodfarray[i]->label:"X");
4629 (&mb, "%s%d", i? " ":"",
4630 iso7816_verify_status (app_get_slot (app),
4631 aodfarray[i]->pin_reference));
4633 put_membuf( &mb, "", 1);
4634 p = get_membuf (&mb, NULL);
4636 return gpg_error_from_syserror ();
4637 err = send_status_direct (ctrl, is_label? "CHV-LABEL":"CHV-STATUS", p);
4641 else if (!strcmp (name, "KEY-LABEL"))
4643 /* Send KEY-LABEL lines for all private key objects. */
4645 char *idbuf, *labelbuf;
4647 for (prkdf = app->app_local->private_key_info; prkdf;
4648 prkdf = prkdf->next)
4650 idbuf = keyref_from_prkdf (app, prkdf);
4652 return gpg_error_from_syserror ();
4654 label = (prkdf->label && *prkdf->label)? prkdf->label : "-";
4655 labelbuf = percent_data_escape (0, NULL, label, strlen (label));
4659 return gpg_error_from_syserror ();
4662 send_status_info (ctrl, name,
4663 idbuf, strlen (idbuf),
4664 labelbuf, strlen(labelbuf),
4671 else if (!strcmp (name, "KEY-FPR"))
4673 /* Send KEY-FPR for the two openpgp keys. */
4674 for (prkdf = app->app_local->private_key_info; prkdf;
4675 prkdf = prkdf->next)
4677 if (app->app_local->any_gpgusage)
4679 if (prkdf->gpgusage.sign)
4684 if (prkdf->usageflags.sign || prkdf->usageflags.sign_recover)
4689 send_key_fpr (app, ctrl, prkdf, 1);
4690 for (prkdf = app->app_local->private_key_info; prkdf;
4691 prkdf = prkdf->next)
4693 if (app->app_local->any_gpgusage)
4695 if (prkdf->gpgusage.encr)
4700 if (prkdf->usageflags.decrypt || prkdf->usageflags.unwrap)
4705 send_key_fpr (app, ctrl, prkdf, 2);
4709 return gpg_error (GPG_ERR_INV_NAME);
4715 /* Micardo cards require special treatment. This is a helper for the
4716 crypto functions to manage the security environment. We expect that
4717 the key file has already been selected. FID is the one of the
4720 micardo_mse (app_t app, unsigned short fid)
4724 unsigned short refdata = 0;
4726 unsigned char msebuf[10];
4728 /* Read the KeyD file containing extra information on keys. */
4729 err = iso7816_select_file (app_get_slot (app), 0x0013, 0);
4732 log_error ("p15: error reading EF_keyD: %s\n", gpg_strerror (err));
4736 for (recno = 1, se_num = -1; ; recno++)
4738 unsigned char *buffer;
4741 const unsigned char *p, *pp;
4743 err = iso7816_read_record (app_get_slot (app), recno, 1, 0,
4745 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
4749 log_error ("p15: error reading EF_keyD record: %s\n",
4750 gpg_strerror (err));
4755 log_info (buffer, buflen, "p15: keyD record: ");
4756 log_printhex (buffer, buflen, "");
4758 p = find_tlv (buffer, buflen, 0x83, &n);
4759 if (p && n == 4 && ((p[2]<<8)|p[3]) == fid)
4761 refdata = ((p[0]<<8)|p[1]);
4762 /* Locate the SE DO and the there included sec env number. */
4763 p = find_tlv (buffer, buflen, 0x7b, &n);
4766 pp = find_tlv (p, n, 0x80, &nn);
4779 log_error ("p15: CRT for keyfile %04hX not found\n", fid);
4780 return gpg_error (GPG_ERR_NOT_FOUND);
4784 /* Restore the security environment to SE_NUM if needed */
4787 err = iso7816_manage_security_env (app_get_slot (app),
4788 0xf3, se_num, NULL, 0);
4791 log_error ("p15: restoring SE to %d failed: %s\n",
4792 se_num, gpg_strerror (err));
4797 /* Set the DST reference data. */
4801 msebuf[3] = (refdata >> 8);
4802 msebuf[4] = refdata;
4803 err = iso7816_manage_security_env (app_get_slot (app), 0x41, 0xb6, msebuf, 5);
4806 log_error ("p15: setting SE to reference file %04hX failed: %s\n",
4807 refdata, gpg_strerror (err));
4815 /* Prepare the verification of the PIN for the key PRKDF by checking
4816 * the AODF and selecting the key file. KEYREF is used for error
4817 * messages. AODF may be NULL if no verification needs to be done. */
4819 prepare_verify_pin (app_t app, const char *keyref,
4820 prkdf_object_t prkdf, aodf_object_t aodf)
4829 log_info ("p15: using AODF %04hX id=", aodf->fid);
4830 for (i=0; i < aodf->objidlen; i++)
4831 log_printf ("%02X", aodf->objid[i]);
4835 if (aodf->authid && opt.verbose)
4836 log_info ("p15: PIN is controlled by another authentication token\n");
4838 if (aodf->pinflags.integrity_protected
4839 || aodf->pinflags.confidentiality_protected)
4841 log_error ("p15: PIN verification requires"
4842 " unsupported protection method\n");
4843 return gpg_error (GPG_ERR_BAD_PIN_METHOD);
4845 if (!aodf->stored_length && aodf->pinflags.needs_padding)
4847 log_error ("p15: PIN verification requires"
4848 " padding but no length known\n");
4849 return gpg_error (GPG_ERR_INV_CARD);
4854 if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
4856 /* According to our protocol analysis we need to select a
4857 * special AID here. Before that the master file needs to be
4858 * selected. (RID A000000167 is assigned to IBM) */
4859 static char const dtrust_aid[] =
4860 { 0xA0, 0x00, 0x00, 0x01, 0x67, 0x45, 0x53, 0x49, 0x47, 0x4E };
4862 err = iso7816_select_mf (app_get_slot (app));
4864 err = iso7816_select_application (app_get_slot (app),
4865 dtrust_aid, sizeof dtrust_aid, 0);
4867 log_error ("p15: error selecting D-TRUST's AID for key %s: %s\n",
4868 keyref, gpg_strerror (err));
4872 /* Standard case: Select the key file. Note that this may
4873 * change the security environment thus we need to do it before
4874 * PIN verification. */
4875 err = select_ef_by_path (app, prkdf->path, prkdf->pathlen);
4877 log_error ("p15: error selecting file for key %s: %s\n",
4878 keyref, gpg_strerror (err));
4882 log_info ("p15: skipping EF selection for auth object '%s'\n", keyref);
4891 any_control_or_space (const char *string)
4893 const unsigned char *s;
4895 for (s = string; *string; string++)
4896 if (*s <= 0x20 || *s >= 0x7f)
4902 /* Return a malloced serial number to be shown to the user. PRKDF is
4903 * used to get it from a certificate; PRKDF may be NULL. */
4905 get_dispserialno (app_t app, prkdf_object_t prkdf)
4910 /* We prefer the SerialNumber RDN from the Subject-DN but we don't
4911 * use it if it features a percent sign (special character in pin
4912 * prompts) or has any control character. */
4913 if (app->app_local->card_product == CARD_PRODUCT_RSCS)
4915 /* We use only the right 8 hex digits. */
4916 serial = app_get_serialno (app);
4917 if (serial && (n=strlen (serial)) > 8)
4918 memmove (serial, serial + n - 8, 9);
4920 else if (prkdf && prkdf->serial_number && *prkdf->serial_number
4921 && !strchr (prkdf->serial_number, '%')
4922 && !any_control_or_space (prkdf->serial_number))
4924 serial = xtrystrdup (prkdf->serial_number);
4928 serial = app_get_serialno (app);
4934 /* Return an allocated string to be used as prompt. PRKDF may be
4935 * NULL. Returns NULL on malloc error. */
4937 make_pin_prompt (app_t app, int remaining, const char *firstline,
4938 prkdf_object_t prkdf)
4940 char *serial, *tmpbuf, *result;
4943 serial = get_dispserialno (app, prkdf);
4945 if (prkdf && prkdf->common_name)
4946 holder = prkdf->common_name;
4947 else if (app->app_local->token_label)
4948 holder = app->app_local->token_label;
4952 /* TRANSLATORS: Put a \x1f right before a colon. This can be
4953 * used by pinentry to nicely align the names and values. Keep
4954 * the %s at the start and end of the string. */
4955 result = xtryasprintf (_("%s"
4956 "Number\x1f: %s%%0A"
4965 return NULL; /* Out of core. */
4967 /* Append a "remaining attempts" info if needed. */
4968 if (remaining != -1 && remaining < 3)
4972 /* TRANSLATORS: This is the number of remaining attempts to
4973 * enter a PIN. Use %%0A (double-percent,0A) for a linefeed. */
4974 rembuf = xtryasprintf (_("Remaining attempts: %d"), remaining);
4977 tmpbuf = strconcat (firstline, "%0A%0A", result,
4978 "%0A%0A", rembuf, NULL);
4988 tmpbuf = strconcat (firstline, "%0A%0A", result, NULL);
4997 /* Given the private key object PRKDF and its authentication object
4998 * AODF ask for the PIN and verify that PIN. If AODF is NULL, no
4999 * authentication is done. */
5001 verify_pin (app_t app,
5002 gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg,
5003 prkdf_object_t prkdf, aodf_object_t aodf)
5019 pin_reference = aodf->pin_reference_valid? aodf->pin_reference : 0;
5021 if (IS_CARDOS_5 (app))
5023 /* We know that this card supports a verify status check. Note
5024 * that in contrast to PIV cards ISO7816_VERIFY_NOT_NEEDED is
5025 * not supported. Noet that we don't use the pin_verified cache
5026 * status because that is not as reliable than to ask the card
5027 * about its state. */
5028 if (prkdf) /* Clear the cache which we don't use. */
5029 prkdf->pin_verified = 0;
5031 remaining = iso7816_verify_status (app_get_slot (app), pin_reference);
5032 if (remaining == ISO7816_VERIFY_NOT_NEEDED)
5037 else if (remaining < 0)
5038 remaining = -1; /* We don't care about the concrete error. */
5039 else if (remaining < 3)
5040 log_info ("p15: PIN has %d attempts left\n", remaining);
5043 remaining = -1; /* Unknown. */
5045 /* Check whether we already verified it. */
5046 if (prkdf && (prkdf->pin_verified || verified))
5047 return 0; /* Already done. */
5050 && prkdf->usageflags.non_repudiation
5051 && (app->app_local->card_type == CARD_TYPE_BELPIC
5052 || app->app_local->card_product == CARD_PRODUCT_DTRUST))
5053 label = _("||Please enter the PIN for the key to create "
5054 "qualified signatures.");
5055 else if (aodf->pinflags.so_pin)
5056 label = _("|A|Please enter the Admin PIN");
5057 else if (aodf->pinflags.unblocking_pin)
5058 label = _("|P|Please enter the PIN Unblocking Code (PUK) "
5059 "for the standard keys.");
5061 label = _("||Please enter the PIN for the standard keys.");
5064 char *prompt = make_pin_prompt (app, remaining, label, prkdf);
5066 err = gpg_error_from_syserror ();
5068 err = pincb (pincb_arg, prompt, &pinvalue);
5073 log_info ("p15: PIN callback returned error: %s\n", gpg_strerror (err));
5077 /* We might need to cope with UTF8 things here. Not sure how
5078 min_length etc. are exactly defined, for now we take them as
5079 a plain octet count. */
5080 if (strlen (pinvalue) < aodf->min_length)
5082 log_error ("p15: PIN is too short; minimum length is %lu\n",
5084 err = gpg_error (GPG_ERR_BAD_PIN);
5086 else if (aodf->stored_length && strlen (pinvalue) > aodf->stored_length)
5088 /* This would otherwise truncate the PIN silently. */
5089 log_error ("p15: PIN is too large; maximum length is %lu\n",
5090 aodf->stored_length);
5091 err = gpg_error (GPG_ERR_BAD_PIN);
5093 else if (aodf->max_length_valid && strlen (pinvalue) > aodf->max_length)
5095 log_error ("p15: PIN is too large; maximum length is %lu\n",
5097 err = gpg_error (GPG_ERR_BAD_PIN);
5108 switch (aodf->pintype)
5111 case PIN_TYPE_ASCII_NUMERIC:
5112 for (s=pinvalue; digitp (s); s++)
5116 errstr = "Non-numeric digits found in PIN";
5117 err = gpg_error (GPG_ERR_BAD_PIN);
5122 case PIN_TYPE_HALF_NIBBLE_BCD:
5123 errstr = "PIN type Half-Nibble-BCD is not supported";
5125 case PIN_TYPE_ISO9564_1:
5126 errstr = "PIN type ISO9564-1 is not supported";
5129 errstr = "Unknown PIN type";
5134 log_error ("p15: can't verify PIN: %s\n", errstr);
5136 return err? err : gpg_error (GPG_ERR_BAD_PIN_METHOD);
5140 if (aodf->pintype == PIN_TYPE_BCD )
5145 for (ndigits=0, s=pinvalue; *s; ndigits++, s++)
5147 paddedpin = xtrymalloc (aodf->stored_length+1);
5150 err = gpg_error_from_syserror ();
5156 paddedpin[i++] = 0x20 | (ndigits & 0x0f);
5157 for (s=pinvalue; i < aodf->stored_length && *s && s[1]; s = s+2 )
5158 paddedpin[i++] = (((*s - '0') << 4) | ((s[1] - '0') & 0x0f));
5159 if (i < aodf->stored_length && *s)
5160 paddedpin[i++] = (((*s - '0') << 4)
5161 |((aodf->pad_char_valid?aodf->pad_char:0)&0x0f));
5163 if (aodf->pinflags.needs_padding)
5165 while (i < aodf->stored_length)
5166 paddedpin[i++] = aodf->pad_char_valid? aodf->pad_char : 0;
5170 pinvalue = paddedpin;
5173 else if (aodf->pinflags.needs_padding)
5177 paddedpin = xtrymalloc (aodf->stored_length+1);
5180 err = gpg_error_from_syserror ();
5184 for (i=0, s=pinvalue; i < aodf->stored_length && *s; i++, s++)
5186 /* Not sure what padding char to use if none has been set.
5187 For now we use 0x00; maybe a space would be better. */
5188 for (; i < aodf->stored_length; i++)
5189 paddedpin[i] = aodf->pad_char_valid? aodf->pad_char : 0;
5193 pinvalue = paddedpin;
5196 pinvaluelen = strlen (pinvalue);
5198 /* log_printhex (pinvalue, pinvaluelen, */
5199 /* "about to verify with ref %lu pin:", pin_reference); */
5200 err = iso7816_verify (app_get_slot (app), pin_reference,
5201 pinvalue, pinvaluelen);
5205 log_error ("p15: PIN verification failed: %s\n", gpg_strerror (err));
5209 log_info ("p15: PIN verification succeeded\n");
5211 prkdf->pin_verified = 1;
5219 /* Handler for the PKSIGN command.
5221 Create the signature and return the allocated result in OUTDATA.
5222 If a PIN is required, the PINCB will be used to ask for the PIN;
5223 that callback should return the PIN in an allocated buffer and
5224 store that as the 3rd argument. */
5226 do_sign (app_t app, ctrl_t ctrl, const char *keyidstr, int hashalgo,
5227 gpg_error_t (*pincb)(void*, const char *, char **),
5229 const void *indata, size_t indatalen,
5230 unsigned char **outdata, size_t *outdatalen )
5233 prkdf_object_t prkdf; /* The private key object. */
5234 aodf_object_t aodf; /* The associated authentication object. */
5235 int mse_done = 0; /* Set to true if the MSE has been done. */
5236 unsigned int digestlen; /* Length of the hash. */
5237 int exmode, le_value;
5238 unsigned char oidbuf[64];
5241 unsigned char *indata_buffer = NULL; /* Malloced helper. */
5245 if (!keyidstr || !*keyidstr || !indatalen)
5246 return gpg_error (GPG_ERR_INV_VALUE);
5248 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5251 if (!(prkdf->usageflags.sign
5252 || prkdf->usageflags.sign_recover
5253 || prkdf->usageflags.non_repudiation
5254 || prkdf->gpgusage.cert
5255 || prkdf->gpgusage.sign
5256 || prkdf->gpgusage.auth ))
5258 log_error ("p15: key %s may not be used for signing\n", keyidstr);
5259 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
5264 log_error ("p15: no authentication object defined for %s\n", keyidstr);
5265 /* fixme: we might want to go ahead and do without PIN
5267 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
5270 /* Find the authentication object to this private key object. */
5271 for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5272 if (aodf->objidlen == prkdf->authidlen
5273 && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
5276 log_info ("p15: no authentication for %s needed\n", keyidstr);
5278 /* We need some more info about the key - get the keygrip to
5279 * populate these fields. */
5280 err = keygrip_from_prkdf (app, prkdf);
5283 log_error ("p15: keygrip_from_prkdf failed: %s\n", gpg_strerror (err));
5288 digestlen = gcry_md_get_algo_dlen (hashalgo);
5290 /* We handle ECC separately from RSA so that we do not need to touch
5291 * working code. In particular we prepare the input data before the
5292 * verify and a possible MSE. */
5295 if (digestlen != 32 && digestlen != 48 && digestlen != 64)
5297 log_error ("p15: ECC signing not possible: dlen=%u\n", digestlen);
5298 err = gpg_error (GPG_ERR_DIGEST_ALGO);
5302 if (indatalen == digestlen)
5303 ; /* Already prepared. */
5304 else if (indatalen > digestlen)
5306 /* Assume a PKCS#1 prefix and remove it. */
5307 oidbuflen = sizeof oidbuf;
5308 err = gcry_md_get_asnoid (hashalgo, &oidbuf, &oidbuflen);
5311 log_error ("p15: no OID for hash algo %d\n", hashalgo);
5312 err = gpg_error (GPG_ERR_INTERNAL);
5315 if (indatalen != oidbuflen + digestlen
5316 || memcmp (indata, oidbuf, oidbuflen))
5318 log_error ("p15: input data too long for ECC: len=%zu\n",
5320 err = gpg_error (GPG_ERR_INV_VALUE);
5323 indata = (const char*)indata + oidbuflen;
5324 indatalen -= oidbuflen;
5328 log_error ("p15: input data too short for ECC: len=%zu\n",
5330 err = gpg_error (GPG_ERR_INV_VALUE);
5334 else /* Prepare RSA input. */
5336 unsigned int framelen;
5337 unsigned char *frame;
5340 framelen = (prkdf->keynbits+7) / 8;
5343 log_error ("p15: key length unknown"
5344 " - can't prepare PKCS#v1.5 frame\n");
5345 err = gpg_error (GPG_ERR_INV_VALUE);
5349 oidbuflen = sizeof oidbuf;
5352 /* We assume that indata already has the required
5353 * digestinfo; thus merely prepend the padding below. */
5355 else if ((err = gcry_md_get_asnoid (hashalgo, &oidbuf, &oidbuflen)))
5357 log_debug ("p15: no OID for hash algo %d\n", hashalgo);
5362 if (indatalen == digestlen)
5364 /* Plain hash in INDATA; prepend the digestinfo. */
5365 indata_buffer = xtrymalloc (oidbuflen + indatalen);
5368 err = gpg_error_from_syserror ();
5371 memcpy (indata_buffer, oidbuf, oidbuflen);
5372 memcpy (indata_buffer+oidbuflen, indata, indatalen);
5373 indata = indata_buffer;
5374 indatalen = oidbuflen + indatalen;
5376 else if (indatalen == oidbuflen + digestlen
5377 && !memcmp (indata, oidbuf, oidbuflen))
5378 ; /* We already got the correct prefix. */
5381 err = gpg_error (GPG_ERR_INV_VALUE);
5382 log_error ("p15: bad input for signing with RSA and hash %d\n",
5387 /* Now prepend the pkcs#v1.5 padding. We require at least 8
5388 * byte of padding and 3 extra bytes for the prefix and the
5389 * delimiting nul. */
5390 if (!indatalen || indatalen + 8 + 4 > framelen)
5392 err = gpg_error (GPG_ERR_INV_VALUE);
5393 log_error ("p15: input does not fit into a %u bit PKCS#v1.5 frame\n",
5397 frame = xtrymalloc (framelen);
5400 err = gpg_error_from_syserror ();
5403 if (app->app_local->card_type == CARD_TYPE_BELPIC)
5405 /* This card wants only the plain hash w/o any prefix. */
5406 /* FIXME: We may want to remove this code because it is unlikely
5407 * that such cards are still in use. */
5408 memcpy (frame, indata, indatalen);
5409 framelen = indatalen;
5415 frame[n++] = 1; /* Block type. */
5416 i = framelen - indatalen - 3 ;
5417 memset (frame+n, 0xff, i);
5419 frame[n++] = 0; /* Delimiter. */
5420 memcpy (frame+n, indata, indatalen);
5422 log_assert (n == framelen);
5424 /* And now put it into the indata_buffer. */
5425 xfree (indata_buffer);
5426 indata_buffer = frame;
5427 indata = indata_buffer;
5428 indatalen = framelen;
5431 /* Prepare PIN verification. This is split so that we can do
5432 * MSE operation for some task after having selected the key file but
5433 * before sending the verify APDU. */
5434 err = prepare_verify_pin (app, keyidstr, prkdf, aodf);
5438 /* Due to the fact that the non-repudiation signature on a BELPIC
5439 card requires a verify immediately before the DSO we set the
5440 MSE before we do the verification. Other cards might also allow
5441 this but I don't want to break anything, thus we do it only
5442 for the BELPIC card here.
5443 FIXME: see comment above about these cards. */
5444 if (app->app_local->card_type == CARD_TYPE_BELPIC)
5446 unsigned char mse[5];
5448 mse[0] = 4; /* Length of the template. */
5449 mse[1] = 0x80; /* Algorithm reference tag. */
5450 if (hashalgo == MD_USER_TLS_MD5SHA1)
5451 mse[2] = 0x01; /* Let card do pkcs#1 0xFF padding. */
5453 mse[2] = 0x02; /* RSASSA-PKCS1-v1.5 using SHA1. */
5454 mse[3] = 0x84; /* Private key reference tag. */
5455 mse[4] = prkdf->key_reference_valid? prkdf->key_reference : 0x82;
5457 err = iso7816_manage_security_env (app_get_slot (app),
5464 log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5468 /* Now that we have all the information available run the actual PIN
5470 err = verify_pin (app, pincb, pincb_arg, prkdf, aodf);
5474 /* Manage security environment needs to be tweaked for certain cards. */
5477 else if (app->app_local->card_type == CARD_TYPE_TCOS)
5479 /* TCOS creates signatures always using the local key 0. MSE
5482 else if (app->app_local->card_type == CARD_TYPE_MICARDO)
5484 if (!prkdf->pathlen)
5485 err = gpg_error (GPG_ERR_BUG);
5487 err = micardo_mse (app, prkdf->path[prkdf->pathlen-1]);
5489 else if (prkdf->key_reference_valid)
5491 unsigned char mse[3];
5493 mse[0] = 0x84; /* Select asym. key. */
5495 mse[2] = prkdf->key_reference;
5497 err = iso7816_manage_security_env (app_get_slot (app),
5503 log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5507 if (prkdf->keyalgo == GCRY_PK_RSA && prkdf->keynbits > 2048)
5510 le_value = prkdf->keynbits / 8;
5518 err = iso7816_compute_ds (app_get_slot (app),
5519 exmode, indata, indatalen,
5520 le_value, outdata, outdatalen);
5523 xfree (indata_buffer);
5528 /* Handler for the PKAUTH command.
5530 This is basically the same as the PKSIGN command but we first check
5531 that the requested key is suitable for authentication; that is, it
5532 must match the criteria used for the attribute $AUTHKEYID. See
5533 do_sign for calling conventions; there is no HASHALGO, though. */
5535 do_auth (app_t app, ctrl_t ctrl, const char *keyidstr,
5536 gpg_error_t (*pincb)(void*, const char *, char **),
5538 const void *indata, size_t indatalen,
5539 unsigned char **outdata, size_t *outdatalen )
5542 prkdf_object_t prkdf;
5545 if (!keyidstr || !*keyidstr)
5546 return gpg_error (GPG_ERR_INV_VALUE);
5548 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5551 if (!(prkdf->usageflags.sign || prkdf->gpgusage.auth))
5553 log_error ("p15: key %s may not be used for authentication\n", keyidstr);
5554 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
5557 algo = indatalen == 36? MD_USER_TLS_MD5SHA1 : GCRY_MD_SHA1;
5558 return do_sign (app, ctrl, keyidstr, algo, pincb, pincb_arg,
5559 indata, indatalen, outdata, outdatalen);
5563 /* Handler for the PKDECRYPT command. Decrypt the data in INDATA and
5564 * return the allocated result in OUTDATA. If a PIN is required the
5565 * PINCB will be used to ask for the PIN; it should return the PIN in
5566 * an allocated buffer and put it into PIN. */
5568 do_decipher (app_t app, ctrl_t ctrl, const char *keyidstr,
5569 gpg_error_t (*pincb)(void*, const char *, char **),
5571 const void *indata, size_t indatalen,
5572 unsigned char **outdata, size_t *outdatalen,
5573 unsigned int *r_info)
5576 prkdf_object_t prkdf; /* The private key object. */
5577 aodf_object_t aodf; /* The associated authentication object. */
5578 int exmode, le_value, padind;
5583 if (!keyidstr || !*keyidstr)
5584 return gpg_error (GPG_ERR_INV_VALUE);
5585 if (!indatalen || !indata || !outdatalen || !outdata)
5586 return gpg_error (GPG_ERR_INV_ARG);
5588 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5591 if (!(prkdf->usageflags.decrypt
5592 || prkdf->usageflags.unwrap
5593 || prkdf->gpgusage.encr ))
5595 log_error ("p15: key %s may not be used for decryption\n", keyidstr);
5596 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
5599 /* Find the authentication object to this private key object. */
5602 log_error ("p15: no authentication object defined for %s\n", keyidstr);
5603 /* fixme: we might want to go ahead and do without PIN
5605 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
5607 for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5608 if (aodf->objidlen == prkdf->authidlen
5609 && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
5612 log_info ("p15: no authentication for %s needed\n", keyidstr);
5614 /* We need some more info about the key - get the keygrip to
5615 * populate these fields. */
5616 err = keygrip_from_prkdf (app, prkdf);
5619 log_error ("p15: keygrip_from_prkdf failed: %s\n", gpg_strerror (err));
5623 /* Verify the PIN. */
5624 err = prepare_verify_pin (app, keyidstr, prkdf, aodf);
5626 err = verify_pin (app, pincb, pincb_arg, prkdf, aodf);
5630 if (prkdf->is_ecc && IS_CARDOS_5(app))
5633 err = iso7816_manage_security_env (app_get_slot (app), 0xF3, 0x01,
5637 log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5643 /* The next is guess work for CardOS. */
5644 if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
5646 /* From analyzing an USB trace of a Windows signing application
5647 * we see that the SE is simply reset to 0x14. It seems to be
5648 * sufficient to do this for decryption; signing still works
5649 * with the standard code despite that our trace showed that
5650 * there the SE is restored to 0x09. Note that the special
5651 * D-Trust AID is in any case select by prepare_verify_pin.
5653 * Hey, D-Trust please hand over the specs so that you can
5654 * actually sell your cards and we can properly implement it;
5655 * other vendors understand this and do not demand ridiculous
5656 * paper work or complicated procedures to get samples. */
5657 err = iso7816_manage_security_env (app_get_slot (app),
5658 0xF3, 0x14, NULL, 0);
5661 else if (prkdf->key_reference_valid)
5663 unsigned char mse[9];
5666 /* Note: This works with CardOS but the D-Trust card has the
5667 * problem that the next created signature would be broken. */
5672 mse[i++] = 0x80; /* Algorithm reference. */
5674 mse[i++] = 0x0a; /* RSA, no padding. */
5676 mse[i++] = 0x84; /* Key reference. */
5678 mse[i++] = prkdf->key_reference;
5679 if (prkdf->is_ecc && IS_CARDOS_5(app))
5681 mse[i++] = 0x95; /* ???. */
5685 log_assert (i <= DIM(mse));
5686 err = iso7816_manage_security_env (app_get_slot (app), 0x41, 0xB8,
5689 /* Check for MSE error. */
5692 log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5696 exmode = le_value = 0;
5698 if (prkdf->keyalgo == GCRY_PK_RSA && prkdf->keynbits > 2048)
5700 exmode = 1; /* Extended length w/o a limit. */
5701 le_value = prkdf->keynbits / 8;
5704 if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
5707 if (prkdf->is_ecc && IS_CARDOS_5(app))
5709 if ((indatalen & 1) && *(const char *)indata == 0x04)
5711 /* Strip indicator byte. */
5713 indata = (const char *)indata + 1;
5715 err = iso7816_pso_csv (app_get_slot (app), exmode,
5718 outdata, outdatalen);
5722 err = iso7816_decipher (app_get_slot (app), exmode,
5725 outdata, outdatalen);
5732 /* Perform a simple verify operation for the PIN specified by
5733 * KEYIDSTR. Note that we require a key reference which is then used
5734 * to select the authentication object. Return GPG_ERR_NO_PIN if a
5735 * PIN is not required for using the private key KEYIDSTR. */
5737 do_check_pin (app_t app, ctrl_t ctrl, const char *keyidstr,
5738 gpg_error_t (*pincb)(void*, const char *, char **),
5742 prkdf_object_t prkdf; /* The private key object. */
5743 aodf_object_t aodf; /* The associated authentication object. */
5747 if (!keyidstr || !*keyidstr)
5748 return gpg_error (GPG_ERR_INV_VALUE);
5750 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5752 && gpg_err_code (err) != GPG_ERR_INV_ID
5753 && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
5756 if (err) /* Not found or invalid - assume it is the label. */
5759 for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5760 if (aodf->label && !ascii_strcasecmp (aodf->label, keyidstr))
5763 return err; /* Re-use the original error code. */
5765 else /* Find the authentication object to this private key object. */
5769 log_error ("p15: no authentication object defined for %s\n",
5771 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
5773 for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5774 if (aodf->objidlen == prkdf->authidlen
5775 && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
5777 if (!aodf) /* None found. */
5778 return gpg_error (GPG_ERR_NO_PIN);
5781 err = prepare_verify_pin (app, keyidstr, prkdf, aodf);
5783 err = verify_pin (app, pincb, pincb_arg, prkdf, aodf);
5789 /* Process the various keygrip based info requests. */
5791 do_with_keygrip (app_t app, ctrl_t ctrl, int action,
5792 const char *want_keygripstr, int capability)
5795 char *serialno = NULL;
5797 prkdf_object_t prkdf;
5799 /* First a quick check for valid parameters. */
5802 case KEYGRIP_ACTION_LOOKUP:
5803 if (!want_keygripstr)
5805 err = gpg_error (GPG_ERR_NOT_FOUND);
5809 case KEYGRIP_ACTION_SEND_DATA:
5812 case KEYGRIP_ACTION_WRITE_STATUS:
5815 err = gpg_error (GPG_ERR_INV_ARG);
5819 /* Allocate the s/n string if needed. */
5820 if (action != KEYGRIP_ACTION_LOOKUP)
5822 serialno = app_get_serialno (app);
5825 err = gpg_error_from_syserror ();
5830 for (prkdf = app->app_local->private_key_info;
5831 prkdf; prkdf = prkdf->next)
5833 if (keygrip_from_prkdf (app, prkdf))
5836 if (action == KEYGRIP_ACTION_LOOKUP)
5838 if (!strcmp (prkdf->keygrip, want_keygripstr))
5840 err = 0; /* Found */
5844 else if (!want_keygripstr || !strcmp (prkdf->keygrip, want_keygripstr))
5848 if (capability == GCRY_PK_USAGE_SIGN)
5850 if (!(prkdf->usageflags.sign || prkdf->usageflags.sign_recover
5851 || prkdf->usageflags.non_repudiation))
5854 else if (capability == GCRY_PK_USAGE_ENCR)
5856 if (!(prkdf->usageflags.decrypt || prkdf->usageflags.unwrap))
5859 else if (capability == GCRY_PK_USAGE_AUTH)
5861 if (!(prkdf->usageflags.sign || prkdf->usageflags.sign_recover))
5865 keyref = keyref_from_prkdf (app, prkdf);
5868 err = gpg_error_from_syserror ();
5872 send_keyinfo (ctrl, as_data, prkdf->keygrip, serialno, keyref);
5874 if (want_keygripstr)
5876 err = 0; /* Found */
5882 /* Return an error so that the dispatcher keeps on looping over the
5883 * other applications. For clarity we use a different error code
5884 * when listing all keys. Note that in lookup mode WANT_KEYGRIPSTR
5886 if (!want_keygripstr)
5887 err = gpg_error (GPG_ERR_TRUE);
5889 err = gpg_error (GPG_ERR_NOT_FOUND);
5898 /* Assume that EF(DIR) has been selected. Read its content and figure
5899 out the home EF of pkcs#15. Return that home DF or 0 if not found
5900 and the value at the address of BELPIC indicates whether it was
5901 found by the belpic aid. */
5902 static unsigned short
5903 read_home_df (int slot, int *r_belpic)
5906 unsigned char *buffer;
5907 const unsigned char *p, *pp;
5908 size_t buflen, n, nn;
5909 unsigned short result = 0;
5913 err = iso7816_read_binary (slot, 0, 0, &buffer, &buflen);
5916 log_error ("p15: error reading EF(DIR): %s\n", gpg_strerror (err));
5920 /* FIXME: We need to scan all records. */
5921 p = find_tlv (buffer, buflen, 0x61, &n);
5924 pp = find_tlv (p, n, 0x4f, &nn);
5925 if (pp && ((nn == sizeof pkcs15_aid && !memcmp (pp, pkcs15_aid, nn))
5926 || (*r_belpic = (nn == sizeof pkcs15be_aid
5927 && !memcmp (pp, pkcs15be_aid, nn)))))
5929 pp = find_tlv (p, n, 0x50, &nn);
5930 if (pp && opt.verbose)
5931 log_info ("p15: application label from EF(DIR) is '%.*s'\n",
5933 pp = find_tlv (p, n, 0x51, &nn);
5934 if (pp && nn == 4 && *pp == 0x3f && !pp[1])
5936 result = ((pp[2] << 8) | pp[3]);
5938 log_info ("p15: application directory is 0x%04hX\n", result);
5948 Select the PKCS#15 application on the card in SLOT.
5951 app_select_p15 (app_t app)
5953 int slot = app_get_slot (app);
5955 unsigned short def_home_df = 0;
5956 card_type_t card_type = CARD_TYPE_UNKNOWN;
5959 unsigned char *fci = NULL;
5962 rc = iso7816_select_application_ext (slot, pkcs15_aid, sizeof pkcs15_aid, 1,
5965 { /* Not found: Try to locate it from 2F00. We use direct path
5966 selection here because it seems that the Belgian eID card
5967 does only allow for that. Many other cards supports this
5968 selection method too. Note, that we don't use
5969 select_application above for the Belgian card - the call
5970 works but it seems that it does not switch to the correct DF.
5971 Using the 2f02 just works. */
5972 unsigned short path[1] = { 0x2f00 };
5974 rc = iso7816_select_path (slot, path, 1, 0);
5978 def_home_df = read_home_df (slot, &is_belpic);
5981 path[0] = def_home_df;
5982 rc = iso7816_select_path (slot, path, 1, 0);
5987 { /* Still not found: Try the default DF. */
5988 def_home_df = DEFAULT_HOME_DF;
5989 rc = iso7816_select_file (slot, def_home_df, 1);
5993 /* Determine the type of the card. The general case is to look
5994 it up from the ATR table. For the Belgian eID card we know
5995 it instantly from the AID. */
5998 card_type = CARD_TYPE_BELPIC;
6006 atr = apdu_get_atr (app_get_slot (app), &atrlen);
6008 rc = gpg_error (GPG_ERR_INV_CARD);
6011 for (i=0; card_atr_list[i].atrlen; i++)
6012 if (card_atr_list[i].atrlen == atrlen
6013 && !memcmp (card_atr_list[i].atr, atr, atrlen))
6015 card_type = card_atr_list[i].type;
6024 app->apptype = APPTYPE_P15;
6026 app->app_local = xtrycalloc (1, sizeof *app->app_local);
6027 if (!app->app_local)
6029 rc = gpg_error_from_syserror ();
6033 /* Set the home DF from the FCI returned by the select. */
6034 if (!def_home_df && fci)
6036 const unsigned char *s;
6039 s = find_tlv (fci, fcilen, 0x83, &n);
6041 def_home_df = buf16_to_ushort (s);
6043 log_error ("p15: select(AID) did not return the DF\n");
6045 app->app_local->home_df = def_home_df;
6047 /* Store the card type. FIXME: We might want to put this into
6048 the common APP structure. */
6049 app->app_local->card_type = card_type;
6051 app->app_local->card_product = CARD_PRODUCT_UNKNOWN;
6053 /* Store whether we may and should use direct path selection. */
6056 case CARD_TYPE_CARDOS_50:
6057 case CARD_TYPE_CARDOS_53:
6061 /* Use whatever has been determined above. */
6064 app->app_local->direct_path_selection = direct;
6066 /* Read basic information and thus check whether this is a real
6068 rc = read_p15_info (app);
6072 /* Special serial number munging. We need to check for a German
6073 prototype card right here because we need to access to
6074 EF(TokenInfo). We mark such a serial number by the using a
6075 prefix of FF0100. */
6076 if (APP_CARD(app)->serialnolen == 12
6077 && !memcmp (APP_CARD(app)->serialno,
6078 "\xD2\x76\0\0\0\0\0\0\0\0\0\0", 12))
6080 /* This is a German card with a silly serial number. Try to get
6081 the serial number from the EF(TokenInfo). . */
6084 /* FIXME: actually get it from EF(TokenInfo). */
6086 p = xtrymalloc (3 + APP_CARD(app)->serialnolen);
6088 rc = gpg_error (gpg_err_code_from_errno (errno));
6091 memcpy (p, "\xff\x01", 3);
6092 memcpy (p+3, APP_CARD(app)->serialno, APP_CARD(app)->serialnolen);
6093 APP_CARD(app)->serialnolen += 3;
6094 xfree (APP_CARD(app)->serialno);
6095 APP_CARD(app)->serialno = p;
6099 app->fnc.deinit = do_deinit;
6100 app->fnc.prep_reselect = NULL;
6101 app->fnc.reselect = NULL;
6102 app->fnc.learn_status = do_learn_status;
6103 app->fnc.readcert = do_readcert;
6104 app->fnc.getattr = do_getattr;
6105 app->fnc.setattr = NULL;
6106 app->fnc.genkey = NULL;
6107 app->fnc.sign = do_sign;
6108 app->fnc.auth = do_auth;
6109 app->fnc.decipher = do_decipher;
6110 app->fnc.change_pin = NULL;
6111 app->fnc.check_pin = do_check_pin;
6112 app->fnc.with_keygrip = do_with_keygrip;