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_AET, /* A.E.T. Europe JCOP card. */
78 CARD_TYPE_BELPIC /* Belgian eID card specs. */
82 /* The OS of card as specified by card_type_t is not always
83 * sufficient. Thus we also distinguish the actual product build upon
88 CARD_PRODUCT_RSCS, /* Rohde&Schwarz Cybersecurity */
89 CARD_PRODUCT_DTRUST, /* D-Trust GmbH (bundesdruckerei.de) */
90 CARD_PRODUCT_GENUA /* GeNUA mbH */
95 /* A list card types with ATRs noticed with these cards. */
96 #define X(a) ((unsigned char const *)(a))
100 unsigned char const *atr;
102 } card_atr_list[] = {
103 { 19, X("\x3B\xBA\x13\x00\x81\x31\x86\x5D\x00\x64\x05\x0A\x02\x01\x31\x80"
105 CARD_TYPE_TCOS }, /* SLE44 */
106 { 19, X("\x3B\xBA\x14\x00\x81\x31\x86\x5D\x00\x64\x05\x14\x02\x02\x31\x80"
108 CARD_TYPE_TCOS }, /* SLE66S */
109 { 19, X("\x3B\xBA\x96\x00\x81\x31\x86\x5D\x00\x64\x05\x60\x02\x03\x31\x80"
111 CARD_TYPE_TCOS }, /* SLE66P */
112 { 27, X("\x3B\xFF\x94\x00\xFF\x80\xB1\xFE\x45\x1F\x03\x00\x68\xD2\x76\x00"
113 "\x00\x28\xFF\x05\x1E\x31\x80\x00\x90\x00\x23"),
114 CARD_TYPE_MICARDO }, /* German BMI card */
115 { 19, X("\x3B\x6F\x00\xFF\x00\x68\xD2\x76\x00\x00\x28\xFF\x05\x1E\x31\x80"
117 CARD_TYPE_MICARDO }, /* German BMI card (ATR due to reader problem) */
118 { 26, X("\x3B\xFE\x94\x00\xFF\x80\xB1\xFA\x45\x1F\x03\x45\x73\x74\x45\x49"
119 "\x44\x20\x76\x65\x72\x20\x31\x2E\x30\x43"),
120 CARD_TYPE_MICARDO }, /* EstEID (Estonian Big Brother card) */
121 { 11, X("\x3b\xd2\x18\x00\x81\x31\xfe\x58\xc9\x01\x14"),
122 CARD_TYPE_CARDOS_50 }, /* CardOS 5.0 */
123 { 11, X("\x3b\xd2\x18\x00\x81\x31\xfe\x58\xc9\x03\x16"),
124 CARD_TYPE_CARDOS_53 }, /* CardOS 5.3 */
125 { 24, X("\x3b\xfe\x18\x00\x00\x80\x31\xfe\x45\x53\x43\x45"
126 "\x36\x30\x2d\x43\x44\x30\x38\x31\x2d\x6e\x46\xa9"),
133 /* Macro to test for CardOS 5.0 and 5.3. */
134 #define IS_CARDOS_5(a) ((a)->app_local->card_type == CARD_TYPE_CARDOS_50 \
135 || (a)->app_local->card_type == CARD_TYPE_CARDOS_53)
137 /* The default PKCS-15 home DF */
138 #define DEFAULT_HOME_DF 0x5015
140 /* The AID of PKCS15. */
141 static char const pkcs15_aid[] = { 0xA0, 0, 0, 0, 0x63,
142 0x50, 0x4B, 0x43, 0x53, 0x2D, 0x31, 0x35 };
144 /* The Belgian eID variant - they didn't understood why a shared AID
145 is useful for a standard. Oh well. */
146 static char const pkcs15be_aid[] = { 0xA0, 0, 0, 0x01, 0x77,
147 0x50, 0x4B, 0x43, 0x53, 0x2D, 0x31, 0x35 };
150 /* The PIN types as defined in pkcs#15 v1.1 */
154 PIN_TYPE_ASCII_NUMERIC = 1,
156 PIN_TYPE_HALF_NIBBLE_BCD = 3,
157 PIN_TYPE_ISO9564_1 = 4
160 /* The AuthenticationTypes as defined in pkcs#15 v1.1 (6.8.1) */
164 AUTH_TYPE_BIOMETRIC = 0,
165 AUTH_TYPE_AUTHKEY = 1,
166 AUTH_TYPE_EXTERNAL = 2,
169 /* A bit array with for the key usage flags from the
170 commonKeyAttributes. */
171 struct keyusage_flags_s
173 unsigned int encrypt: 1;
174 unsigned int decrypt: 1;
175 unsigned int sign: 1;
176 unsigned int sign_recover: 1;
177 unsigned int wrap: 1;
178 unsigned int unwrap: 1;
179 unsigned int verify: 1;
180 unsigned int verify_recover: 1;
181 unsigned int derive: 1;
182 unsigned int non_repudiation: 1;
184 typedef struct keyusage_flags_s keyusage_flags_t;
187 /* A bit array with for the key access flags from the
188 commonKeyAttributes. */
189 struct keyaccess_flags_s
191 unsigned int any:1; /* Any access flag set. */
192 unsigned int sensitive:1;
193 unsigned int extractable:1;
194 unsigned int always_sensitive:1;
195 unsigned int never_extractable:1;
196 unsigned int local:1;
198 typedef struct keyaccess_flags_s keyaccess_flags_t;
201 /* A bit array with for the gpg usage flags. */
202 struct gpgusage_flags_s
204 unsigned int any:1; /* Any of the next flags are set. */
205 unsigned int cert:1; /* 1.3.6.1.4.1.11591.2.6.1 */
206 unsigned int sign:1; /* 1.3.6.1.4.1.11591.2.6.2 */
207 unsigned int encr:1; /* 1.3.6.1.4.1.11591.2.6.3 */
208 unsigned int auth:1; /* 1.3.6.1.4.1.11591.2.6.4 */
210 typedef struct gpgusage_flags_s gpgusage_flags_t;
213 /* This is an object to store information about a Certificate
214 Directory File (CDF) in a format suitable for further processing by
215 us. To keep memory management, simple we use a linked list of
216 items; i.e. one such object represents one certificate and the list
220 /* Link to next item when used in a linked list. */
221 struct cdf_object_s *next;
223 /* Flags to indicate whether fields are valid. */
224 unsigned int have_off:1;
226 /* Length and allocated buffer with the Id of this object.
227 * This field is used for X.509 in PKCS#11 to make it easier to
228 * match a private key with a certificate. */
230 unsigned char *objid;
232 /* Length and allocated buffer with the authId of this object or
233 NULL if no authID is known. */
235 unsigned char *authid;
237 /* NULL or the malloced label of this object. */
240 /* To avoid reading and parsing a certificate more than once, we
241 * cache the ksba object. */
244 /* The offset and length of the object. They are only valid if
245 HAVE_OFF is true and set to 0 if HAVE_OFF is false. */
246 unsigned long off, len;
248 /* The length of the path as given in the CDF and the path itself.
249 path[0] is the top DF (usually 0x3f00). The path will never be
252 unsigned short path[1];
254 typedef struct cdf_object_s *cdf_object_t;
257 /* This is an object to store information about a Private Key
258 Directory File (PrKDF) in a format suitable for further processing
259 by us. To keep memory management, simple we use a linked list of
260 items; i.e. one such object represents one certificate and the list
262 struct prkdf_object_s
264 /* Link to next item when used in a linked list. */
265 struct prkdf_object_s *next;
267 /* Flags to indicate whether fields are valid. */
268 unsigned int keygrip_valid:1;
269 unsigned int key_reference_valid:1;
270 unsigned int have_off:1;
271 unsigned int have_keytime:1;
273 /* Flag indicating that the corresponding PIN has already been
274 * verified. Note that for cards which are able to return the
275 * verification stus, this flag is not used. */
276 unsigned int pin_verified:1;
278 /* PKCS#15 info whether this is an EC key. Default is RSA. Note
279 * that there is also a KEYALGO field which is derived from the
280 * publick key via Libgcrypt. */
281 unsigned int is_ecc:1;
283 /* The key's usage flags. */
284 keyusage_flags_t usageflags;
286 /* The key's access flags. */
287 keyaccess_flags_t accessflags;
289 /* Extended key usage flags. Only used if .valid is set. This
290 * information is computed from an associated certificate15. */
292 unsigned int valid:1;
298 /* OpenPGP key features for this key. This is taken from special
299 * extended key usage flags different from those tracked in EXTUSAGE
300 * above. There is also no valid flag as in EXTUSAGE. */
301 gpgusage_flags_t gpgusage;
303 /* The keygrip of the key. This is used as a cache. */
304 char keygrip[2*KEYGRIP_LEN+1];
306 /* A malloced algorithm string or NULL if not known. */
309 /* The Gcrypt algo identifier for the key. It is valid if the
310 * keygrip is also valid. See also is_ecc above. */
313 /* The length of the key in bits (e.g. for RSA the length of the
314 * modulus). It is valid if the keygrip is also valid. */
315 unsigned int keynbits;
317 /* The creation time of the key or 0 if not known. */
320 /* Malloced CN from the Subject-DN of the corresponding certificate
321 * or NULL if not known. */
324 /* Malloced SerialNumber from the Subject-DN of the corresponding
325 * certificate or NULL if not known. */
328 /* KDF/KEK parameter for OpenPGP's ECDH. First byte is zero if not
330 unsigned char ecdh_kdf[4];
332 /* Length and allocated buffer with the Id of this object. */
334 unsigned char *objid;
336 /* Length and allocated buffer with the authId of this object or
337 NULL if no authID is known. */
339 unsigned char *authid;
341 /* NULL or the malloced label of this object. */
344 /* The keyReference and a flag telling whether it is valid. */
345 unsigned long key_reference;
347 /* The offset and length of the object. They are only valid if
348 * HAVE_OFF is true otherwise they are set to 0. */
349 unsigned long off, len;
351 /* The length of the path as given in the PrKDF and the path itself.
352 path[0] is the top DF (usually 0x3f00). */
354 unsigned short path[1];
356 typedef struct prkdf_object_s *prkdf_object_t;
357 typedef struct prkdf_object_s *pukdf_object_t;
360 /* This is an object to store information about a Authentication
361 Object Directory File (AODF) in a format suitable for further
362 processing by us. To keep memory management, simple we use a linked
363 list of items; i.e. one such object represents one authentication
364 object and the list the entire AOKDF. */
367 /* Link to next item when used in a linked list. */
368 struct aodf_object_s *next;
370 /* Flags to indicate whether fields are valid. */
371 unsigned int have_off:1;
373 /* Length and allocated buffer with the Id of this object. */
375 unsigned char *objid;
377 /* Length and allocated buffer with the authId of this object or
378 NULL if no authID is known. */
380 unsigned char *authid;
382 /* NULL or the malloced label of this object. */
385 /* The file ID of this AODF. */
388 /* The type of this authentication object. */
389 auth_type_t auth_type;
391 /* Info used for AUTH_TYPE_PIN: */
396 unsigned int case_sensitive: 1;
397 unsigned int local: 1;
398 unsigned int change_disabled: 1;
399 unsigned int unblock_disabled: 1;
400 unsigned int initialized: 1;
401 unsigned int needs_padding: 1;
402 unsigned int unblocking_pin: 1;
403 unsigned int so_pin: 1;
404 unsigned int disable_allowed: 1;
405 unsigned int integrity_protected: 1;
406 unsigned int confidentiality_protected: 1;
407 unsigned int exchange_ref_data: 1;
413 /* The minimum length of a PIN. */
414 unsigned long min_length;
416 /* The stored length of a PIN. */
417 unsigned long stored_length;
419 /* The maximum length of a PIN and a flag telling whether it is valid. */
420 unsigned long max_length;
421 int max_length_valid;
423 /* The pinReference and a flag telling whether it is valid. */
424 unsigned long pin_reference;
425 int pin_reference_valid;
427 /* The padChar and a flag telling whether it is valid. */
431 /* The offset and length of the object. They are only valid if
432 HAVE_OFF is true and set to 0 if HAVE_OFF is false. */
433 unsigned long off, len;
435 /* The length of the path as given in the Aodf and the path itself.
436 path[0] is the top DF (usually 0x3f00). PATH is optional and thus
437 may be NULL. Malloced.*/
439 unsigned short *path;
441 /* Info used for AUTH_TYPE_AUTHKEY: */
444 typedef struct aodf_object_s *aodf_object_t;
447 /* Context local to this application. */
450 /* The home DF. Note, that we don't yet support a multilevel
451 hierarchy. Thus we assume this is directly below the MF. */
452 unsigned short home_df;
454 /* The type of the card's OS. */
455 card_type_t card_type;
457 /* The vendor's product. */
458 card_product_t card_product;
460 /* Flag indicating that extended_mode is not supported. */
461 unsigned int no_extended_mode : 1;
463 /* Flag indicating whether we may use direct path selection. */
464 unsigned int direct_path_selection : 1;
466 /* Flag indicating whether the card has any key with a gpgusage set. */
467 unsigned int any_gpgusage : 1;
469 /* Structure with the EFIDs of the objects described in the ODF
473 unsigned short private_keys;
474 unsigned short public_keys;
475 unsigned short trusted_public_keys;
476 unsigned short secret_keys;
477 unsigned short certificates;
478 unsigned short trusted_certificates;
479 unsigned short useful_certificates;
480 unsigned short data_objects;
481 unsigned short auth_objects;
484 /* The PKCS#15 serialnumber from EF(TokenInfo) or NULL. Malloced. */
485 unsigned char *serialno;
488 /* The manufacturerID from the TokenInfo EF. Malloced or NULL. */
489 char *manufacturer_id;
491 /* The label from the TokenInfo EF. Malloced or NULL. */
494 /* The tokenflags from the TokenInfo EF. Malloced or NULL. */
495 unsigned char *tokenflags;
496 unsigned int tokenflagslen;
498 /* Information on all certificates. */
499 cdf_object_t certificate_info;
500 /* Information on all trusted certificates. */
501 cdf_object_t trusted_certificate_info;
502 /* Information on all useful certificates. */
503 cdf_object_t useful_certificate_info;
505 /* Information on all public keys. */
506 prkdf_object_t public_key_info;
508 /* Information on all private keys. */
509 pukdf_object_t private_key_info;
511 /* Information on all authentication objects. */
512 aodf_object_t auth_object_info;
517 /*** Local prototypes. ***/
518 static gpg_error_t select_ef_by_path (app_t app, const unsigned short *path,
520 static gpg_error_t keygrip_from_prkdf (app_t app, prkdf_object_t prkdf);
521 static gpg_error_t readcert_by_cdf (app_t app, cdf_object_t cdf,
522 unsigned char **r_cert, size_t *r_certlen);
523 static char *get_dispserialno (app_t app, prkdf_object_t prkdf);
524 static gpg_error_t do_getattr (app_t app, ctrl_t ctrl, const char *name);
529 cardtype2str (card_type_t cardtype)
533 case CARD_TYPE_UNKNOWN: return "";
534 case CARD_TYPE_TCOS: return "TCOS";
535 case CARD_TYPE_MICARDO: return "Micardo";
536 case CARD_TYPE_CARDOS_50: return "CardOS 5.0";
537 case CARD_TYPE_CARDOS_53: return "CardOS 5.3";
538 case CARD_TYPE_BELPIC: return "Belgian eID";
539 case CARD_TYPE_AET: return "AET";
545 cardproduct2str (card_product_t cardproduct)
549 case CARD_PRODUCT_UNKNOWN: return "";
550 case CARD_PRODUCT_RSCS: return "R&S";
551 case CARD_PRODUCT_DTRUST: return "D-Trust";
552 case CARD_PRODUCT_GENUA: return "GeNUA";
557 /* Release the CDF object A */
559 release_cdflist (cdf_object_t a)
563 cdf_object_t tmp = a->next;
573 /* Release the PrKDF object A. */
575 release_prkdflist (prkdf_object_t a)
579 prkdf_object_t tmp = a->next;
580 xfree (a->keyalgostr);
581 xfree (a->common_name);
582 xfree (a->serial_number);
592 release_pukdflist (pukdf_object_t a)
594 release_prkdflist (a);
597 /* Release just one aodf object. */
599 release_aodf_object (aodf_object_t a)
611 /* Release the AODF list A. */
613 release_aodflist (aodf_object_t a)
617 aodf_object_t tmp = a->next;
618 release_aodf_object (a);
625 release_lists (app_t app)
627 release_cdflist (app->app_local->certificate_info);
628 app->app_local->certificate_info = NULL;
629 release_cdflist (app->app_local->trusted_certificate_info);
630 app->app_local->trusted_certificate_info = NULL;
631 release_cdflist (app->app_local->useful_certificate_info);
632 app->app_local->useful_certificate_info = NULL;
633 release_pukdflist (app->app_local->public_key_info);
634 app->app_local->public_key_info = NULL;
635 release_prkdflist (app->app_local->private_key_info);
636 app->app_local->private_key_info = NULL;
637 release_aodflist (app->app_local->auth_object_info);
638 app->app_local->auth_object_info = NULL;
643 release_tokeninfo (app_t app)
645 xfree (app->app_local->manufacturer_id);
646 app->app_local->manufacturer_id = NULL;
647 xfree (app->app_local->token_label);
648 app->app_local->token_label = NULL;
649 xfree (app->app_local->tokenflags);
650 app->app_local->tokenflags = NULL;
651 xfree (app->app_local->serialno);
652 app->app_local->serialno = NULL;
656 /* Release all local resources. */
658 do_deinit (app_t app)
660 if (app && app->app_local)
663 release_tokeninfo (app);
664 xfree (app->app_local);
665 app->app_local = NULL;
670 /* Do a select and a read for the file with EFID. EFID_DESC is a
671 desctription of the EF to be used with error messages. On success
672 BUFFER and BUFLEN contain the entire content of the EF. The caller
673 must free BUFFER only on success. If EFID is 0 no seelct is done. */
675 select_and_read_binary (app_t app, unsigned short efid, const char *efid_desc,
676 unsigned char **buffer, size_t *buflen)
683 err = select_ef_by_path (app, &efid, 1);
686 log_error ("p15: error selecting %s (0x%04X): %s\n",
687 efid_desc, efid, gpg_strerror (err));
692 err = iso7816_read_binary_ext (app_get_slot (app),
693 0, 0, 0, buffer, buflen, &sw);
695 log_error ("p15: error reading %s (0x%04X): %s (sw=%04X)\n",
696 efid_desc, efid, gpg_strerror (err), sw);
701 /* If EFID is not 0 do a select and then read the record RECNO.
702 * EFID_DESC is a description of the EF to be used with error
703 * messages. On success BUFFER and BUFLEN contain the entire content
704 * of the EF. The caller must free BUFFER only on success. */
706 select_and_read_record (app_t app, unsigned short efid, int recno,
707 const char *efid_desc,
708 unsigned char **buffer, size_t *buflen, int *r_sw)
718 err = select_ef_by_path (app, &efid, 1);
721 log_error ("p15: error selecting %s (0x%04X): %s\n",
722 efid_desc, efid, gpg_strerror (err));
729 err = iso7816_read_record_ext (app_get_slot (app),
730 recno, 1, 0, buffer, buflen, &sw);
733 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
735 else if (err && sw == SW_FILE_STRUCT)
738 log_error ("p15: error reading %s (0x%04X) record %d: %s (sw=%04X)\n",
739 efid_desc, efid, recno, gpg_strerror (err), sw);
744 /* On CardOS with a Linear TLV file structure the records starts
745 * with some tag (often the record number) followed by the length
746 * byte for this record. Detect and remove this prefix. */
747 if (*buflen > 2 && (*buffer)[0] != 0x30 && (*buffer)[1] == *buflen - 2)
749 memmove (*buffer, *buffer + 2, *buflen - 2);
750 *buflen = *buflen - 2;
757 /* This function calls select file to read a file using a complete
758 path which may or may not start at the master file (MF). */
760 select_ef_by_path (app_t app, const unsigned short *path, size_t pathlen)
766 return gpg_error (GPG_ERR_INV_VALUE);
768 /* log_debug ("%s: path=", __func__); */
769 /* for (j=0; j < pathlen; j++) */
770 /* log_printf ("%s%04hX", j? "/":"", path[j]); */
771 /* log_printf ("%s\n",app->app_local->direct_path_selection?" (direct)":"");*/
773 if (app->app_local->direct_path_selection)
775 if (pathlen && *path == 0x3f00 )
778 err = iso7816_select_mf (app_get_slot (app));
780 err = iso7816_select_path (app_get_slot (app), path+1, pathlen-1,
784 err = iso7816_select_path (app_get_slot (app), path, pathlen,
785 app->app_local->home_df);
788 log_error ("p15: error selecting path ");
792 else if (pathlen > 1 && path[0] == 0x3fff)
794 err = iso7816_select_file (app_get_slot (app), 0x3f00, 0);
797 log_error ("p15: error selecting part %d from path ", 0);
802 for (i=0; i < pathlen; i++)
804 err = iso7816_select_file (app_get_slot (app),
805 path[i], (i+1 == pathlen)? 2 : 1);
808 log_error ("p15: error selecting part %d from path ", i);
815 if (pathlen && *path != 0x3f00 )
816 log_error ("p15: warning: relative path select not yet implemented\n");
818 /* FIXME: Use home_df. */
819 for (i=0; i < pathlen; i++)
821 err = iso7816_select_file (app_get_slot (app),
822 path[i], !(i+1 == pathlen));
825 log_error ("p15: error selecting part %d from path ", i);
833 if (pathlen && *path != 0x3f00 )
834 log_printf ("3F00/");
836 log_printf ("%04hX/", app->app_local->home_df);
837 for (j=0; j < pathlen; j++)
838 log_printf ("%s%04hX", j? "/":"", path[j]);
839 log_printf (": %s\n", gpg_strerror (err));
844 /* Parse a cert Id string (or a key Id string) and return the binary
845 object Id string in a newly allocated buffer stored at R_OBJID and
846 R_OBJIDLEN. On Error NULL will be stored there and an error code
847 returned. On success caller needs to free the buffer at R_OBJID. */
849 parse_certid (app_t app, const char *certid,
850 unsigned char **r_objid, size_t *r_objidlen)
855 unsigned char *objid;
861 if (certid[0] != 'P' && strlen (certid) == 40) /* This is a keygrip. */
863 prkdf_object_t prkdf;
865 for (prkdf = app->app_local->private_key_info;
866 prkdf; prkdf = prkdf->next)
867 if (!keygrip_from_prkdf (app, prkdf)
868 && !strcmp (certid, prkdf->keygrip))
870 if (!prkdf || !prkdf->objidlen || !prkdf->objid)
871 return gpg_error (GPG_ERR_NOT_FOUND);
872 objidlen = prkdf->objidlen;
873 objid = xtrymalloc (objidlen);
875 return gpg_error_from_syserror ();
876 memcpy (objid, prkdf->objid, prkdf->objidlen);
878 else /* This is a usual keyref. */
880 if (app->app_local->home_df != DEFAULT_HOME_DF)
881 snprintf (tmpbuf, sizeof tmpbuf, "P15-%04X.",
882 (unsigned int)(app->app_local->home_df & 0xffff));
884 strcpy (tmpbuf, "P15.");
885 if (strncmp (certid, tmpbuf, strlen (tmpbuf)) )
887 if (!strncmp (certid, "P15.", 4)
888 || (!strncmp (certid, "P15-", 4)
889 && hexdigitp (certid+4)
890 && hexdigitp (certid+5)
891 && hexdigitp (certid+6)
892 && hexdigitp (certid+7)
893 && certid[8] == '.'))
894 return gpg_error (GPG_ERR_NOT_FOUND);
895 return gpg_error (GPG_ERR_INV_ID);
897 certid += strlen (tmpbuf);
898 for (s=certid, objidlen=0; hexdigitp (s); s++, objidlen++)
900 if (*s || !objidlen || (objidlen%2))
901 return gpg_error (GPG_ERR_INV_ID);
903 objid = xtrymalloc (objidlen);
905 return gpg_error_from_syserror ();
906 for (s=certid, i=0; i < objidlen; i++, s+=2)
907 objid[i] = xtoi_2 (s);
911 *r_objidlen = objidlen;
916 /* Find a certificate object by its object ID and store a pointer to
919 cdf_object_from_objid (app_t app, size_t objidlen, const unsigned char *objid,
924 for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
925 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
928 for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
929 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
932 for (cdf = app->app_local->useful_certificate_info; cdf; cdf = cdf->next)
933 if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
936 return gpg_error (GPG_ERR_NOT_FOUND);
942 /* Find a certificate object by its label and store a pointer to it at
945 cdf_object_from_label (app_t app, const char *label, cdf_object_t *r_cdf)
950 return gpg_error (GPG_ERR_NOT_FOUND);
952 for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
953 if (cdf->label && !strcmp (cdf->label, label))
956 for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
957 if (cdf->label && !strcmp (cdf->label, label))
960 for (cdf = app->app_local->useful_certificate_info; cdf; cdf = cdf->next)
961 if (cdf->label && !strcmp (cdf->label, label))
964 return gpg_error (GPG_ERR_NOT_FOUND);
970 /* Find a certificate object by the certificate ID CERTID and store a
971 * pointer to it at R_CDF. */
973 cdf_object_from_certid (app_t app, const char *certid, cdf_object_t *r_cdf)
977 unsigned char *objid;
979 prkdf_object_t prkdf;
981 err = parse_certid (app, certid, &objid, &objidlen);
985 err = cdf_object_from_objid (app, objidlen, objid, &cdf);
986 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
988 /* Try again by finding the certid in the prkdf and matching by
990 for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
991 if (prkdf->objidlen == objidlen
992 && !memcmp (prkdf->objid, objid, objidlen))
995 err = cdf_object_from_label (app, prkdf->label, &cdf);
1005 /* Find a private key object by the key Id string KEYIDSTR and store a
1006 pointer to it at R_PRKDF. */
1008 prkdf_object_from_keyidstr (app_t app, const char *keyidstr,
1009 prkdf_object_t *r_prkdf)
1013 unsigned char *objid;
1014 prkdf_object_t prkdf;
1016 err = parse_certid (app, keyidstr, &objid, &objidlen);
1020 for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
1021 if (prkdf->objidlen == objidlen && !memcmp (prkdf->objid, objid, objidlen))
1025 return gpg_error (GPG_ERR_NOT_FOUND);
1033 /* Read and parse the Object Directory File and store away the
1034 pointers. ODF_FID shall contain the FID of the ODF.
1036 Example of such a file:
1038 A0 06 30 04 04 02 60 34 = Private Keys
1039 A4 06 30 04 04 02 60 35 = Certificates
1040 A5 06 30 04 04 02 60 36 = Trusted Certificates
1041 A7 06 30 04 04 02 60 37 = Data Objects
1042 A8 06 30 04 04 02 60 38 = Auth Objects
1044 These are all PathOrObjects using the path CHOICE element. The
1045 paths are octet strings of length 2. Using this Path CHOICE
1046 element is recommended, so we only implement that for now.
1049 read_ef_odf (app_t app, unsigned short odf_fid)
1052 unsigned char *buffer, *p;
1054 unsigned short value;
1056 unsigned short home_df = 0;
1059 app->app_local->odf.private_keys = 0;
1060 app->app_local->odf.public_keys = 0;
1061 app->app_local->odf.trusted_public_keys = 0;
1062 app->app_local->odf.secret_keys = 0;
1063 app->app_local->odf.certificates = 0;
1064 app->app_local->odf.trusted_certificates = 0;
1065 app->app_local->odf.useful_certificates = 0;
1066 app->app_local->odf.data_objects = 0;
1067 app->app_local->odf.auth_objects = 0;
1069 err = select_and_read_binary (app, odf_fid, "ODF",
1076 log_error ("p15: error: ODF too short\n");
1078 return gpg_error (GPG_ERR_INV_OBJ);
1081 home_df = app->app_local->home_df;
1083 while (buflen && *p && *p != 0xff)
1086 && (p[0] & 0xf0) == 0xA0
1087 && !memcmp (p+1, "\x06\x30\x04\x04\x02", 5) )
1091 else if ( buflen >= 12
1092 && (p[0] & 0xf0) == 0xA0
1093 && !memcmp (p+1, "\x0a\x30\x08\x04\x06\x3F\x00", 7)
1094 && (!home_df || home_df == ((p[8]<<8)|p[9])) )
1096 /* FIXME: Is this hack still required? */
1097 /* If we do not know the home DF, we take it from the first
1098 * ODF object. Here are sample values:
1099 * a0 0a 30 08 0406 3f00 5015 4401
1100 * a1 0a 30 08 0406 3f00 5015 4411
1101 * a4 0a 30 08 0406 3f00 5015 4441
1102 * a5 0a 30 08 0406 3f00 5015 4451
1103 * a8 0a 30 08 0406 3f00 5015 4481
1107 home_df = ((p[8]<<8)|p[9]);
1108 app->app_local->home_df = home_df;
1109 log_info ("p15: application directory detected as 0x%04hX\n",
1111 /* We assume that direct path selection is possible. */
1112 app->app_local->direct_path_selection = 1;
1115 /* We only allow a full path if all files are at the same
1116 level and below the home directory. To extend this we
1117 would need to make use of new data type capable of
1118 keeping a full path. */
1123 log_printhex (p, buflen, "p15: ODF format not supported:");
1125 return gpg_error (GPG_ERR_INV_OBJ);
1127 switch ((p[0] & 0x0f))
1129 case 0: value = app->app_local->odf.private_keys; break;
1130 case 1: value = app->app_local->odf.public_keys; break;
1131 case 2: value = app->app_local->odf.trusted_public_keys; break;
1132 case 3: value = app->app_local->odf.secret_keys; break;
1133 case 4: value = app->app_local->odf.certificates; break;
1134 case 5: value = app->app_local->odf.trusted_certificates; break;
1135 case 6: value = app->app_local->odf.useful_certificates; break;
1136 case 7: value = app->app_local->odf.data_objects; break;
1137 case 8: value = app->app_local->odf.auth_objects; break;
1138 default: value = 0; break;
1142 log_error ("p15: duplicate object type %d in ODF ignored\n",
1146 value = ((p[offset] << 8) | p[offset+1]);
1147 switch ((p[0] & 0x0f))
1149 case 0: app->app_local->odf.private_keys = value; break;
1150 case 1: app->app_local->odf.public_keys = value; break;
1151 case 2: app->app_local->odf.trusted_public_keys = value; break;
1152 case 3: app->app_local->odf.secret_keys = value; break;
1153 case 4: app->app_local->odf.certificates = value; break;
1154 case 5: app->app_local->odf.trusted_certificates = value; break;
1155 case 6: app->app_local->odf.useful_certificates = value; break;
1156 case 7: app->app_local->odf.data_objects = value; break;
1157 case 8: app->app_local->odf.auth_objects = value; break;
1159 log_error ("p15: unknown object type %d in ODF ignored\n",
1164 if (buflen < offset)
1172 /* Print a warning if non-null garbage is left over. */
1173 for (n=0; n < buflen && !p[n]; n++)
1177 log_info ("p15: warning: garbage detected at end of ODF: ");
1178 log_printhex (p, buflen, "");
1187 /* Helper for the read_ef_foo functions to read the first record or
1188 * the entire data. */
1190 read_first_record (app_t app, unsigned short fid, const char *fid_desc,
1191 unsigned char **r_buffer, size_t *r_buflen,
1192 int *r_use_read_record)
1199 *r_use_read_record = 0;
1202 return gpg_error (GPG_ERR_NO_DATA); /* No such file. */
1204 if (IS_CARDOS_5 (app))
1206 *r_use_read_record = 1;
1207 err = select_and_read_record (app, fid, 1, fid_desc,
1208 r_buffer, r_buflen, &sw);
1209 if (err && sw == SW_FILE_STRUCT)
1211 *r_use_read_record = 0;
1212 err = select_and_read_binary (app, 0, fid_desc, r_buffer, r_buflen);
1216 err = select_and_read_binary (app, fid, fid_desc, r_buffer, r_buflen);
1218 /* We get a not_found state in read_record mode if the select
1219 * succeeded but reading the record failed. Map that to no_data
1220 * which is what the caller of the read_ef_foo functions expect. */
1221 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1222 err = gpg_error (GPG_ERR_NO_DATA);
1228 /* Parse the BIT STRING with the keyUsageFlags from the
1229 CommonKeyAttributes. */
1231 parse_keyusage_flags (const unsigned char *der, size_t derlen,
1232 keyusage_flags_t *usageflags)
1234 unsigned int bits, mask;
1235 int i, unused, full;
1237 memset (usageflags, 0, sizeof *usageflags);
1239 return gpg_error (GPG_ERR_INV_OBJ);
1241 unused = *der++; derlen--;
1242 if ((!derlen && unused) || unused/8 > derlen)
1243 return gpg_error (GPG_ERR_ENCODING_PROBLEM);
1244 full = derlen - (unused+7)/8;
1247 for (i=1; unused; i <<= 1, unused--)
1253 bits = *der++; derlen--;
1264 if ((bits & 0x80)) usageflags->encrypt = 1;
1265 if ((bits & 0x40)) usageflags->decrypt = 1;
1266 if ((bits & 0x20)) usageflags->sign = 1;
1267 if ((bits & 0x10)) usageflags->sign_recover = 1;
1268 if ((bits & 0x08)) usageflags->wrap = 1;
1269 if ((bits & 0x04)) usageflags->unwrap = 1;
1270 if ((bits & 0x02)) usageflags->verify = 1;
1271 if ((bits & 0x01)) usageflags->verify_recover = 1;
1276 bits = *der++; derlen--;
1286 if ((bits & 0x80)) usageflags->derive = 1;
1287 if ((bits & 0x40)) usageflags->non_repudiation = 1;
1294 dump_keyusage_flags (keyusage_flags_t usageflags)
1298 log_info ("p15: usage=");
1299 if (usageflags.encrypt)
1300 log_printf ("%sencrypt", s), s = ",";
1301 if (usageflags.decrypt)
1302 log_printf ("%sdecrypt", s), s = ",";
1303 if (usageflags.sign )
1304 log_printf ("%ssign", s), s = ",";
1305 if (usageflags.sign_recover)
1306 log_printf ("%ssign_recover", s), s = ",";
1307 if (usageflags.wrap )
1308 log_printf ("%swrap", s), s = ",";
1309 if (usageflags.unwrap )
1310 log_printf ("%sunwrap", s), s = ",";
1311 if (usageflags.verify )
1312 log_printf ("%sverify", s), s = ",";
1313 if (usageflags.verify_recover)
1314 log_printf ("%sverify_recover", s), s = ",";
1315 if (usageflags.derive )
1316 log_printf ("%sderive", s), s = ",";
1317 if (usageflags.non_repudiation)
1318 log_printf ("%snon_repudiation", s), s = ",";
1323 dump_keyaccess_flags (keyaccess_flags_t accessflags)
1327 log_info ("p15: access=");
1328 if (accessflags.sensitive)
1329 log_printf ("%ssensitive", s), s = ",";
1330 if (accessflags.extractable)
1331 log_printf ("%sextractable", s), s = ",";
1332 if (accessflags.always_sensitive)
1333 log_printf ("%salways_sensitive", s), s = ",";
1334 if (accessflags.never_extractable)
1335 log_printf ("%snever_extractable", s), s = ",";
1336 if (accessflags.local)
1337 log_printf ("%slocal", s), s = ",";
1342 dump_gpgusage_flags (gpgusage_flags_t gpgusage)
1346 log_info ("p15: gpgusage=");
1348 log_printf ("%scert", s), s = ",";
1350 log_printf ("%ssign", s), s = ",";
1352 log_printf ("%sencr", s), s = ",";
1354 log_printf ("%sauth", s), s = ",";
1358 /* Parse the BIT STRING with the keyAccessFlags from the
1359 CommonKeyAttributes. */
1361 parse_keyaccess_flags (const unsigned char *der, size_t derlen,
1362 keyaccess_flags_t *accessflags)
1364 unsigned int bits, mask;
1365 int i, unused, full;
1367 memset (accessflags, 0, sizeof *accessflags);
1369 return gpg_error (GPG_ERR_INV_OBJ);
1371 unused = *der++; derlen--;
1372 if ((!derlen && unused) || unused/8 > derlen)
1373 return gpg_error (GPG_ERR_ENCODING_PROBLEM);
1374 full = derlen - (unused+7)/8;
1377 for (i=1; unused; i <<= 1, unused--)
1383 bits = *der++; derlen--;
1394 if ((bits & 0x10)) accessflags->local = 1;
1395 if ((bits & 0x08)) accessflags->never_extractable = 1;
1396 if ((bits & 0x04)) accessflags->always_sensitive = 1;
1397 if ((bits & 0x02)) accessflags->extractable = 1;
1398 if ((bits & 0x01)) accessflags->sensitive = 1;
1400 accessflags->any = 1;
1405 /* Parse the commonObjectAttributes and store a malloced authid at
1406 * (r_authid,r_authidlen). (NULL,0) is stored on error or if no
1407 * authid is found. IF R_LABEL is not NULL the label is stored there
1408 * as a malloced string (spaces are replaced by underscores).
1411 * 2 30 17: SEQUENCE { -- commonObjectAttributes
1412 * 4 0C 8: UTF8String 'SK.CH.DS' -- label
1413 * 14 03 2: BIT STRING 6 unused bits
1415 * 18 04 1: OCTET STRING --authid
1420 parse_common_obj_attr (unsigned char const **buffer, size_t *size,
1421 unsigned char **r_authid, size_t *r_authidlen,
1426 int class, tag, constructed, ndef;
1427 size_t objlen, hdrlen, nnn;
1428 const unsigned char *ppp;
1438 err = parse_ber_header (buffer, size, &class, &tag, &constructed,
1439 &ndef, &objlen, &hdrlen);
1440 if (!err && (objlen > *size || tag != TAG_SEQUENCE))
1441 err = gpg_error (GPG_ERR_INV_OBJ);
1450 /* Search the optional AuthId. */
1453 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1454 &ndef, &objlen, &hdrlen);
1455 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1456 err = gpg_error (GPG_ERR_INV_OBJ);
1460 if (tag == TAG_UTF8_STRING)
1464 *r_label = xtrymalloc (objlen + 1);
1467 err = gpg_error_from_syserror ();
1470 memcpy (*r_label, ppp, objlen);
1471 (*r_label)[objlen] = 0;
1472 /* We don't want spaces in the labels due to the properties
1474 for (p = *r_label; *p; p++)
1475 if (ascii_isspace (*p))
1483 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1484 &ndef, &objlen, &hdrlen);
1485 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1486 err = gpg_error (GPG_ERR_INV_OBJ);
1490 if (tag == TAG_BIT_STRING)
1492 ppp += objlen; /* Skip the CommonObjectFlags. */
1496 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1497 &ndef, &objlen, &hdrlen);
1498 if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
1499 err = gpg_error (GPG_ERR_INV_OBJ);
1503 if (tag == TAG_OCTET_STRING && objlen)
1505 *r_authid = xtrymalloc (objlen);
1508 err = gpg_error_from_syserror ();
1511 memcpy (*r_authid, ppp, objlen);
1512 *r_authidlen = objlen;
1516 if (ignore_eof && gpg_err_code (err) == GPG_ERR_EOF)
1519 log_error ("p15: error parsing commonObjectAttributes at %d: %s\n",
1520 where, gpg_strerror (err));
1532 /* Parse the commonKeyAttributes. On success store the objid at
1533 * (R_OBJID/R_OBJIDLEN), sets the key usage flags at USAGEFLAGS and
1534 * the optiona key refrence at R_KEY_REFERENCE. The latter is only
1535 * valid if true is also stored at R_KEY_REFERENCE_VALID.
1539 * 21 30 12: SEQUENCE { -- commonKeyAttributes
1540 * 23 04 1: OCTET STRING
1542 * 26 03 3: BIT STRING 6 unused bits
1543 * : '1000000000'B (bit 9)
1544 * 31 02 2: INTEGER 80 -- keyReference (optional)
1548 parse_common_key_attr (unsigned char const **buffer, size_t *size,
1549 unsigned char **r_objid, size_t *r_objidlen,
1550 keyusage_flags_t *usageflags,
1551 keyaccess_flags_t *accessflags,
1552 unsigned long *r_key_reference,
1553 int *r_key_reference_valid)
1557 int class, tag, constructed, ndef;
1558 size_t objlen, hdrlen, nnn;
1559 const unsigned char *ppp;
1562 const unsigned char *objid = NULL;
1564 unsigned long key_reference = 0;
1565 int key_reference_valid = 0;
1569 memset (usageflags, 0, sizeof *usageflags);
1570 memset (accessflags, 0, sizeof *accessflags);
1571 *r_key_reference_valid = 0;
1574 err = parse_ber_header (buffer, size, &class, &tag, &constructed,
1575 &ndef, &objlen, &hdrlen);
1576 if (!err && (objlen > *size || tag != TAG_SEQUENCE))
1577 err = gpg_error (GPG_ERR_INV_OBJ);
1588 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1589 &ndef, &objlen, &hdrlen);
1590 if (!err && (objlen > nnn
1591 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
1592 err = gpg_error (GPG_ERR_INV_OBJ);
1601 /* Get the KeyUsageFlags. */
1603 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1604 &ndef, &objlen, &hdrlen);
1605 if (!err && (objlen > nnn
1606 || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
1607 err = gpg_error (GPG_ERR_INV_OBJ);
1611 err = parse_keyusage_flags (ppp, objlen, usageflags);
1617 ignore_eof = 1; /* Remaining items are optional. */
1619 /* Find the keyReference */
1621 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1622 &ndef, &objlen, &hdrlen);
1623 if (!err && objlen > nnn)
1624 err = gpg_error (GPG_ERR_INV_OBJ);
1628 if (class == CLASS_UNIVERSAL && tag == TAG_BOOLEAN)
1630 /* Skip the native element. */
1634 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1635 &ndef, &objlen, &hdrlen);
1636 if (!err && objlen > nnn)
1637 err = gpg_error (GPG_ERR_INV_OBJ);
1641 if (class == CLASS_UNIVERSAL && tag == TAG_BIT_STRING)
1643 /* These are the keyAccessFlags. */
1644 err = parse_keyaccess_flags (ppp, objlen, accessflags);
1650 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
1651 &ndef, &objlen, &hdrlen);
1652 if (!err && objlen > nnn)
1653 err = gpg_error (GPG_ERR_INV_OBJ);
1657 if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
1659 /* This is the keyReference. */
1660 for (ul=0; objlen; objlen--)
1663 ul |= (*ppp++) & 0xff;
1667 key_reference_valid = 1;
1671 if (ignore_eof && gpg_err_code (err) == GPG_ERR_EOF)
1676 if (!objid || !objidlen)
1677 err = gpg_error (GPG_ERR_INV_OBJ);
1680 *r_objid = xtrymalloc (objidlen);
1682 err = gpg_error_from_syserror ();
1685 memcpy (*r_objid, objid, objidlen);
1686 *r_objidlen = objidlen;
1690 if (!err && key_reference_valid)
1692 *r_key_reference = key_reference;
1693 *r_key_reference_valid = 1;
1697 log_error ("p15: error parsing commonKeyAttributes at %d: %s\n",
1698 where, gpg_strerror (err));
1704 /* Read and parse the Private Key Directory Files.
1708 * SEQUENCE { -- commonObjectAttributes
1709 * UTF8String 'SK.CH.DS'
1710 * BIT STRING 6 unused bits
1711 * '01'B (bit 0) -- flags: non-modifiable,private
1712 * OCTET STRING --authid
1715 * SEQUENCE { -- commonKeyAttributes
1718 * BIT STRING 6 unused bits
1719 * '1000000000'B (bit 9) -- keyusage: non-repudiation
1720 * INTEGER 80 -- keyReference (optional)
1722 * [1] { -- keyAttributes
1723 * SEQUENCE { -- privateRSAKeyAttributes
1724 * SEQUENCE { -- objectValue
1725 * OCTET STRING --path
1728 * INTEGER 1024 -- modulus
1733 * Sample part for EC objects:
1734 * [1] { -- keyAttributes
1735 * [1] { -- privateECkeyAttributes
1736 * SEQUENCE { -- objectValue
1738 * OCTET STRING 50 72 4B 03
1740 * INTEGER 33 -- Not in PKCS#15v1.1, need to buy 7816-15?
1745 read_ef_prkdf (app_t app, unsigned short fid, prkdf_object_t *result)
1748 unsigned char *buffer;
1750 const unsigned char *p;
1751 size_t n, objlen, hdrlen;
1752 int class, tag, constructed, ndef;
1753 prkdf_object_t prkdflist = NULL;
1756 unsigned char *authid = NULL;
1757 size_t authidlen = 0;
1758 unsigned char *objid = NULL;
1759 size_t objidlen = 0;
1763 err = read_first_record (app, fid, "PrKDF", &buffer, &buflen, &record_mode);
1770 /* Loop over the records. We stop as soon as we detect a new record
1771 starting with 0x00 or 0xff as these values are commonly used to
1772 pad data blocks and are no valid ASN.1 encoding. Note the
1773 special handling for record mode at the end of the loop. */
1774 while (n && *p && *p != 0xff)
1776 const unsigned char *pp;
1779 const char *errstr = NULL;
1780 prkdf_object_t prkdf = NULL;
1782 keyusage_flags_t usageflags;
1783 keyaccess_flags_t accessflags;
1784 unsigned long key_reference = 0;
1785 int key_reference_valid = 0;
1789 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
1790 &ndef, &objlen, &hdrlen);
1793 else if (objlen > n)
1794 err = gpg_error (GPG_ERR_INV_OBJ);
1795 else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
1796 ; /* PrivateRSAKeyAttributes */
1797 else if (class == CLASS_CONTEXT)
1801 case 0: is_ecc = 1; break; /* PrivateECKeyAttributes */
1802 case 1: errstr = "DH key objects are not supported"; break;
1803 case 2: errstr = "DSA key objects are not supported"; break;
1804 case 3: errstr = "KEA key objects are not supported"; break;
1805 default: errstr = "unknown privateKeyObject"; break;
1812 err = gpg_error (GPG_ERR_INV_OBJ);
1818 log_error ("p15: error parsing PrKDF record: %s\n",
1819 gpg_strerror (err));
1828 /* Parse the commonObjectAttributes. */
1832 err = parse_common_obj_attr (&pp, &nn, &authid, &authidlen, &label);
1836 /* Parse the commonKeyAttributes. */
1839 err = parse_common_key_attr (&pp, &nn,
1841 &usageflags, &accessflags,
1842 &key_reference, &key_reference_valid);
1847 /* Skip commonPrivateKeyAttributes. */
1849 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1850 &ndef, &objlen, &hdrlen);
1851 if (!err && objlen > nn)
1852 err = gpg_error (GPG_ERR_INV_OBJ);
1855 if (class == CLASS_CONTEXT && tag == 0)
1861 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1862 &ndef, &objlen, &hdrlen);
1864 /* Parse the keyAttributes. */
1865 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
1866 err = gpg_error (GPG_ERR_INV_OBJ);
1872 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1873 &ndef, &objlen, &hdrlen);
1876 else if (!err && objlen > nn)
1877 err = gpg_error (GPG_ERR_INV_OBJ);
1878 else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
1879 ; /* A typeAttribute always starts with a sequence. */
1881 err = gpg_error (GPG_ERR_INV_OBJ);
1887 /* Check that the reference is a Path object. */
1889 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1890 &ndef, &objlen, &hdrlen);
1891 if (!err && objlen > nn)
1892 err = gpg_error (GPG_ERR_INV_OBJ);
1895 if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
1897 errstr = "unsupported reference type";
1902 /* Parse the Path object. */
1904 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1905 &ndef, &objlen, &hdrlen);
1906 if (!err && objlen > nn)
1907 err = gpg_error (GPG_ERR_INV_OBJ);
1911 /* Make sure that the next element is a non zero path and of
1912 even length (FID are two bytes each). */
1913 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
1914 || !objlen || (objlen & 1) )
1916 errstr = "invalid path reference";
1920 /* Create a new PrKDF list item. */
1921 prkdf = xtrycalloc (1, (sizeof *prkdf
1922 - sizeof(unsigned short)
1923 + objlen/2 * sizeof(unsigned short)));
1926 err = gpg_error_from_syserror ();
1929 prkdf->is_ecc = is_ecc;
1931 prkdf->objidlen = objidlen;
1932 prkdf->objid = objid;
1936 prkdf->authidlen = authidlen;
1937 prkdf->authid = authid;
1942 prkdf->label = label;
1946 prkdf->pathlen = objlen/2;
1947 for (i=0; i < prkdf->pathlen; i++, pp += 2, nn -= 2)
1948 prkdf->path[i] = ((pp[0] << 8) | pp[1]);
1950 prkdf->usageflags = usageflags;
1951 prkdf->accessflags = accessflags;
1952 prkdf->key_reference = key_reference;
1953 prkdf->key_reference_valid = key_reference_valid;
1957 /* An index and length follows. */
1958 prkdf->have_off = 1;
1960 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1961 &ndef, &objlen, &hdrlen);
1962 if (!err && (objlen > nn
1963 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
1964 err = gpg_error (GPG_ERR_INV_OBJ);
1968 for (ul=0; objlen; objlen--)
1971 ul |= (*pp++) & 0xff;
1977 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
1978 &ndef, &objlen, &hdrlen);
1979 if (!err && (objlen > nn
1980 || class != CLASS_CONTEXT || tag != 0))
1981 err = gpg_error (GPG_ERR_INV_OBJ);
1985 for (ul=0; objlen; objlen--)
1988 ul |= (*pp++) & 0xff;
1994 /* The info is printed later in read_p15_info because we also
1995 * want to look at the certificates. */
1997 /* Put it into the list. */
1998 prkdf->next = prkdflist;
2001 goto next_record; /* Ready with this record. */
2004 log_error ("p15: error parsing PrKDF record at %d: %s - skipped\n",
2005 where, errstr? errstr : gpg_strerror (err));
2008 xfree (prkdf->objid);
2009 xfree (prkdf->authid);
2010 xfree (prkdf->label);
2016 /* If the card uses a record oriented file structure, read the
2017 * next record. Otherwise we keep on parsing the current buffer. */
2021 xfree (buffer); buffer = NULL;
2022 err = select_and_read_record (app, 0, recno, "PrKDF",
2023 &buffer, &buflen, NULL);
2025 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2032 } /* End looping over all records. */
2040 release_prkdflist (prkdflist);
2042 *result = prkdflist;
2047 /* Read and parse the Public Keys Directory File. */
2049 read_ef_pukdf (app_t app, unsigned short fid, pukdf_object_t *result)
2052 unsigned char *buffer;
2054 const unsigned char *p;
2055 size_t n, objlen, hdrlen;
2056 int class, tag, constructed, ndef;
2057 pukdf_object_t pukdflist = NULL;
2060 unsigned char *authid = NULL;
2061 size_t authidlen = 0;
2062 unsigned char *objid = NULL;
2063 size_t objidlen = 0;
2067 err = read_first_record (app, fid, "PuKDF", &buffer, &buflen, &record_mode);
2074 /* Loop over the records. We stop as soon as we detect a new record
2075 * starting with 0x00 or 0xff as these values are commonly used to
2076 * pad data blocks and are no valid ASN.1 encoding. Note the
2077 * special handling for record mode at the end of the loop. */
2078 while (n && *p && *p != 0xff)
2080 const unsigned char *pp;
2083 const char *errstr = NULL;
2084 pukdf_object_t pukdf = NULL;
2086 keyusage_flags_t usageflags;
2087 keyaccess_flags_t accessflags;
2088 unsigned long key_reference = 0;
2089 int key_reference_valid = 0;
2092 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2093 &ndef, &objlen, &hdrlen);
2096 else if (objlen > n)
2097 err = gpg_error (GPG_ERR_INV_OBJ);
2098 else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
2099 ; /* PublicRSAKeyAttributes */
2100 else if (class == CLASS_CONTEXT)
2104 case 0: break; /* EC key object */
2105 case 1: errstr = "DH key objects are not supported"; break;
2106 case 2: errstr = "DSA key objects are not supported"; break;
2107 case 3: errstr = "KEA key objects are not supported"; break;
2108 default: errstr = "unknown publicKeyObject"; break;
2115 err = gpg_error (GPG_ERR_INV_OBJ);
2121 log_error ("p15: error parsing PuKDF record: %s\n",
2122 gpg_strerror (err));
2131 /* Parse the commonObjectAttributes. */
2135 err = parse_common_obj_attr (&pp, &nn, &authid, &authidlen, &label);
2139 /* Parse the commonKeyAttributes. */
2142 err = parse_common_key_attr (&pp, &nn,
2144 &usageflags, &accessflags,
2145 &key_reference, &key_reference_valid);
2150 /* Parse the subClassAttributes. */
2152 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2153 &ndef, &objlen, &hdrlen);
2154 if (!err && objlen > nn)
2155 err = gpg_error (GPG_ERR_INV_OBJ);
2158 if (class == CLASS_CONTEXT && tag == 0)
2160 /* Skip this CommonPublicKeyAttribute. */
2165 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2166 &ndef, &objlen, &hdrlen);
2168 /* We expect a typeAttribute. */
2169 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
2170 err = gpg_error (GPG_ERR_INV_OBJ);
2172 goto parse_error; /* No typeAttribute. */
2176 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2177 &ndef, &objlen, &hdrlen);
2180 else if (!err && objlen > nn)
2181 err = gpg_error (GPG_ERR_INV_OBJ);
2182 else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
2183 ; /* A typeAttribute always starts with a sequence. */
2185 err = gpg_error (GPG_ERR_INV_OBJ);
2191 /* Check that the reference is a Path object. */
2193 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2194 &ndef, &objlen, &hdrlen);
2195 if (!err && objlen > nn)
2196 err = gpg_error (GPG_ERR_INV_OBJ);
2199 if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
2201 errstr = "unsupported reference type";
2206 /* Parse the Path object. */
2208 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2209 &ndef, &objlen, &hdrlen);
2210 if (!err && objlen > nn)
2211 err = gpg_error (GPG_ERR_INV_OBJ);
2215 /* Make sure that the next element is a non zero path and of
2216 even length (FID are two bytes each). */
2217 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
2218 || !objlen || (objlen & 1) )
2220 errstr = "invalid path reference";
2224 /* Create a new PuKDF list item. */
2225 pukdf = xtrycalloc (1, (sizeof *pukdf
2226 - sizeof(unsigned short)
2227 + objlen/2 * sizeof(unsigned short)));
2230 err = gpg_error_from_syserror ();
2233 pukdf->objidlen = objidlen;
2234 pukdf->objid = objid;
2238 pukdf->authidlen = authidlen;
2239 pukdf->authid = authid;
2244 pukdf->label = label;
2248 pukdf->pathlen = objlen/2;
2249 for (i=0; i < pukdf->pathlen; i++, pp += 2, nn -= 2)
2250 pukdf->path[i] = ((pp[0] << 8) | pp[1]);
2252 pukdf->usageflags = usageflags;
2253 pukdf->accessflags = accessflags;
2254 pukdf->key_reference = key_reference;
2255 pukdf->key_reference_valid = key_reference_valid;
2259 /* An index and length follows. */
2260 pukdf->have_off = 1;
2262 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2263 &ndef, &objlen, &hdrlen);
2264 if (!err && (objlen > nn
2265 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
2266 err = gpg_error (GPG_ERR_INV_OBJ);
2270 for (ul=0; objlen; objlen--)
2273 ul |= (*pp++) & 0xff;
2279 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2280 &ndef, &objlen, &hdrlen);
2281 if (!err && (objlen > nn
2282 || class != CLASS_CONTEXT || tag != 0))
2283 err = gpg_error (GPG_ERR_INV_OBJ);
2287 for (ul=0; objlen; objlen--)
2290 ul |= (*pp++) & 0xff;
2299 log_info ("p15: PuKDF %04hX: id=", fid);
2300 for (i=0; i < pukdf->objidlen; i++)
2301 log_printf ("%02X", pukdf->objid[i]);
2303 log_printf (" (%s)", pukdf->label);
2304 log_info ("p15: path=");
2305 for (i=0; i < pukdf->pathlen; i++)
2306 log_printf ("%s%04hX", i?"/":"",pukdf->path[i]);
2307 if (pukdf->have_off)
2308 log_printf ("[%lu/%lu]", pukdf->off, pukdf->len);
2311 log_printf (" authid=");
2312 for (i=0; i < pukdf->authidlen; i++)
2313 log_printf ("%02X", pukdf->authid[i]);
2315 if (pukdf->key_reference_valid)
2316 log_printf (" keyref=0x%02lX", pukdf->key_reference);
2317 if (pukdf->accessflags.any)
2318 dump_keyaccess_flags (pukdf->accessflags);
2319 dump_keyusage_flags (pukdf->usageflags);
2323 /* Put it into the list. */
2324 pukdf->next = pukdflist;
2327 goto next_record; /* Ready with this record. */
2330 log_error ("p15: error parsing PuKDF record at %d: %s - skipped\n",
2331 where, errstr? errstr : gpg_strerror (err));
2334 xfree (pukdf->objid);
2335 xfree (pukdf->authid);
2336 xfree (pukdf->label);
2342 /* If the card uses a record oriented file structure, read the
2343 * next record. Otherwise we keep on parsing the current buffer. */
2347 xfree (buffer); buffer = NULL;
2348 err = select_and_read_record (app, 0, recno, "PuKDF",
2349 &buffer, &buflen, NULL);
2351 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2358 } /* End looping over all records. */
2366 release_pukdflist (pukdflist);
2368 *result = pukdflist;
2373 /* Read and parse the Certificate Directory Files identified by FID.
2374 On success a newlist of CDF object gets stored at RESULT and the
2375 caller is then responsible of releasing this list. On error a
2376 error code is returned and RESULT won't get changed. */
2378 read_ef_cdf (app_t app, unsigned short fid, int cdftype, cdf_object_t *result)
2381 unsigned char *buffer;
2383 const unsigned char *p;
2384 size_t n, objlen, hdrlen;
2385 int class, tag, constructed, ndef;
2386 cdf_object_t cdflist = NULL;
2389 unsigned char *authid = NULL;
2390 size_t authidlen = 0;
2394 err = read_first_record (app, fid, "CDF", &buffer, &buflen, &record_mode);
2401 /* Loop over the records. We stop as soon as we detect a new record
2402 starting with 0x00 or 0xff as these values are commonly used to
2403 pad data blocks and are no valid ASN.1 encoding. Note the
2404 special handling for record mode at the end of the loop. */
2405 while (n && *p && *p != 0xff)
2407 const unsigned char *pp;
2410 const char *errstr = NULL;
2411 cdf_object_t cdf = NULL;
2413 const unsigned char *objid;
2416 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2417 &ndef, &objlen, &hdrlen);
2418 if (!err && (objlen > n || tag != TAG_SEQUENCE))
2419 err = gpg_error (GPG_ERR_INV_OBJ);
2422 log_error ("p15: error parsing CDF record: %s\n", gpg_strerror (err));
2430 /* Parse the commonObjectAttributes. */
2434 err = parse_common_obj_attr (&pp, &nn, &authid, &authidlen, &label);
2438 /* Parse the commonCertificateAttributes. */
2440 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2441 &ndef, &objlen, &hdrlen);
2442 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
2443 err = gpg_error (GPG_ERR_INV_OBJ);
2447 const unsigned char *ppp = pp;
2448 size_t nnn = objlen;
2455 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
2456 &ndef, &objlen, &hdrlen);
2457 if (!err && (objlen > nnn
2458 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
2459 err = gpg_error (GPG_ERR_INV_OBJ);
2466 /* Parse the certAttribute. */
2468 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2469 &ndef, &objlen, &hdrlen);
2470 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
2471 err = gpg_error (GPG_ERR_INV_OBJ);
2477 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2478 &ndef, &objlen, &hdrlen);
2479 if (!err && (objlen > nn
2480 || class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE))
2481 err = gpg_error (GPG_ERR_INV_OBJ);
2486 /* Check that the reference is a Path object. */
2488 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2489 &ndef, &objlen, &hdrlen);
2490 if (!err && objlen > nn)
2491 err = gpg_error (GPG_ERR_INV_OBJ);
2494 if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
2496 errstr = "unsupported reference type";
2501 /* Parse the Path object. */
2503 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2504 &ndef, &objlen, &hdrlen);
2505 if (!err && objlen > nn)
2506 err = gpg_error (GPG_ERR_INV_OBJ);
2510 /* Make sure that the next element is a non zero path and of
2511 even length (FID are two bytes each). */
2512 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
2513 || !objlen || (objlen & 1) )
2515 errstr = "invalid path reference";
2518 /* Create a new CDF list item. */
2519 cdf = xtrycalloc (1, (sizeof *cdf
2520 - sizeof(unsigned short)
2521 + objlen/2 * sizeof(unsigned short)));
2524 err = gpg_error_from_syserror ();
2529 cdf->authidlen = authidlen;
2530 cdf->authid = authid;
2539 cdf->objidlen = objidlen;
2540 cdf->objid = xtrymalloc (objidlen);
2543 err = gpg_error_from_syserror ();
2547 memcpy (cdf->objid, objid, objidlen);
2549 cdf->pathlen = objlen/2;
2550 for (i=0; i < cdf->pathlen; i++, pp += 2, nn -= 2)
2551 cdf->path[i] = ((pp[0] << 8) | pp[1]);
2555 /* An index and length follows. */
2558 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2559 &ndef, &objlen, &hdrlen);
2560 if (!err && (objlen > nn
2561 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
2562 err = gpg_error (GPG_ERR_INV_OBJ);
2566 for (ul=0; objlen; objlen--)
2569 ul |= (*pp++) & 0xff;
2575 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2576 &ndef, &objlen, &hdrlen);
2577 if (!err && (objlen > nn
2578 || class != CLASS_CONTEXT || tag != 0))
2579 err = gpg_error (GPG_ERR_INV_OBJ);
2583 for (ul=0; objlen; objlen--)
2586 ul |= (*pp++) & 0xff;
2594 log_info ("p15: CDF-%c %04hX: id=", cdftype, fid);
2595 for (i=0; i < cdf->objidlen; i++)
2596 log_printf ("%02X", cdf->objid[i]);
2598 log_printf (" (%s)", cdf->label);
2599 log_info ("p15: path=");
2600 for (i=0; i < cdf->pathlen; i++)
2601 log_printf ("%s%04hX", i?"/":"", cdf->path[i]);
2603 log_printf ("[%lu/%lu]", cdf->off, cdf->len);
2606 log_printf (" authid=");
2607 for (i=0; i < cdf->authidlen; i++)
2608 log_printf ("%02X", cdf->authid[i]);
2613 /* Put it into the list. */
2614 cdf->next = cdflist;
2617 goto next_record; /* Ready with this record. */
2620 log_error ("p15: error parsing CDF record at %d: %s - skipped\n",
2621 where, errstr? errstr : gpg_strerror (err));
2628 /* If the card uses a record oriented file structure, read the
2629 * next record. Otherwise we keep on parsing the current buffer. */
2633 xfree (buffer); buffer = NULL;
2634 err = select_and_read_record (app, 0, recno, "CDF",
2635 &buffer, &buflen, NULL);
2637 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2644 } /* End loop over all records. */
2651 release_cdflist (cdflist);
2660 * SEQUENCE { -- CommonObjectAttributes
2661 * UTF8String 'specific PIN for DS'
2662 * BIT STRING 0 unused bits
2665 * SEQUENCE { -- CommonAuthenticationObjectAttributes
2670 * [1] { -- typeAttributes
2671 * SEQUENCE { -- PinAttributes
2672 * BIT STRING 0 unused bits
2673 * '0000100000110010'B -- local,initialized,needs-padding
2674 * -- exchangeRefData
2675 * ENUMERATED 1 -- ascii-numeric
2676 * INTEGER 6 -- minLength
2677 * INTEGER 6 -- storedLength
2678 * INTEGER 8 -- maxLength
2680 * 02 -- pinReference
2681 * GeneralizedTime 19/04/2002 12:12 GMT -- lastPinChange
2684 * 3F 00 40 16 -- path to DF of PIN
2690 * Or for an authKey:
2692 * [1] { -- typeAttributes
2693 * SEQUENCE { -- AuthKeyAttributes
2694 * BOOLEAN TRUE -- derivedKey
2695 * OCTET STRING 02 -- authKeyId
2700 /* Read and parse an Authentication Object Directory File identified
2701 by FID. On success a newlist of AODF objects gets stored at RESULT
2702 and the caller is responsible of releasing this list. On error a
2703 error code is returned and RESULT won't get changed. */
2705 read_ef_aodf (app_t app, unsigned short fid, aodf_object_t *result)
2708 unsigned char *buffer;
2710 const unsigned char *p;
2711 size_t n, objlen, hdrlen;
2712 int class, tag, constructed, ndef;
2713 aodf_object_t aodflist = NULL;
2718 err = read_first_record (app, fid, "AODF", &buffer, &buflen, &record_mode);
2725 /* Loop over the records. We stop as soon as we detect a new record
2726 starting with 0x00 or 0xff as these values are commonly used to
2727 pad data blocks and are no valid ASN.1 encoding. Note the
2728 special handling for record mode at the end of the loop. */
2729 while (n && *p && *p != 0xff)
2731 const unsigned char *pp;
2734 const char *errstr = NULL;
2735 auth_type_t auth_type;
2736 aodf_object_t aodf = NULL;
2741 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
2742 &ndef, &objlen, &hdrlen);
2745 else if (objlen > n)
2746 err = gpg_error (GPG_ERR_INV_OBJ);
2747 else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
2748 auth_type = AUTH_TYPE_PIN; /* PinAttributes */
2749 else if (class == CLASS_CONTEXT && tag == 1 )
2750 auth_type = AUTH_TYPE_AUTHKEY; /* AuthKeyAttributes */
2751 else if (class == CLASS_CONTEXT)
2755 case 0: errstr = "biometric auth types are not supported"; break;
2756 case 2: errstr = "external auth type are not supported"; break;
2757 default: errstr = "unknown privateKeyObject"; break;
2763 err = gpg_error (GPG_ERR_INV_OBJ);
2769 log_error ("p15: error parsing AODF record: %s\n",
2770 gpg_strerror (err));
2778 /* Allocate memory for a new AODF list item. */
2779 aodf = xtrycalloc (1, sizeof *aodf);
2783 aodf->auth_type = auth_type;
2785 /* Parse the commonObjectAttributes. */
2787 err = parse_common_obj_attr (&pp, &nn, &aodf->authid, &aodf->authidlen,
2792 /* Parse the CommonAuthenticationObjectAttributes. */
2794 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2795 &ndef, &objlen, &hdrlen);
2796 if (!err && (objlen > nn || tag != TAG_SEQUENCE))
2797 err = gpg_error (GPG_ERR_INV_OBJ);
2801 const unsigned char *ppp = pp;
2802 size_t nnn = objlen;
2809 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
2810 &ndef, &objlen, &hdrlen);
2811 if (!err && (objlen > nnn
2812 || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
2813 err = gpg_error (GPG_ERR_INV_OBJ);
2817 aodf->objidlen = objlen;
2818 aodf->objid = xtrymalloc (objlen);
2821 memcpy (aodf->objid, ppp, objlen);
2824 /* Parse the typeAttributes. */
2826 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2827 &ndef, &objlen, &hdrlen);
2828 if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
2829 err = gpg_error (GPG_ERR_INV_OBJ);
2835 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2836 &ndef, &objlen, &hdrlen);
2839 else if (!err && objlen > nn)
2840 err = gpg_error (GPG_ERR_INV_OBJ);
2841 else if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE)
2844 err = gpg_error (GPG_ERR_INV_OBJ);
2850 if (auth_type == AUTH_TYPE_PIN)
2854 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2855 &ndef, &objlen, &hdrlen);
2856 if (!err && (objlen > nn || !objlen
2857 || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
2858 err = gpg_error (GPG_ERR_INV_OBJ);
2863 unsigned int bits, mask;
2866 unused = *pp++; nn--; objlen--;
2867 if ((!objlen && unused) || unused/8 > objlen)
2869 err = gpg_error (GPG_ERR_ENCODING_PROBLEM);
2872 full = objlen - (unused+7)/8;
2875 for (i=1; unused; i <<= 1, unused--)
2878 /* The first octet */
2882 bits = *pp++; nn--; objlen--;
2891 if ((bits & 0x80)) /* ASN.1 bit 0. */
2892 aodf->pinflags.case_sensitive = 1;
2893 if ((bits & 0x40)) /* ASN.1 bit 1. */
2894 aodf->pinflags.local = 1;
2896 aodf->pinflags.change_disabled = 1;
2898 aodf->pinflags.unblock_disabled = 1;
2900 aodf->pinflags.initialized = 1;
2902 aodf->pinflags.needs_padding = 1;
2904 aodf->pinflags.unblocking_pin = 1;
2906 aodf->pinflags.so_pin = 1;
2907 /* The second octet. */
2911 bits = *pp++; nn--; objlen--;
2920 aodf->pinflags.disable_allowed = 1;
2922 aodf->pinflags.integrity_protected = 1;
2924 aodf->pinflags.confidentiality_protected = 1;
2926 aodf->pinflags.exchange_ref_data = 1;
2927 /* Skip remaining bits. */
2934 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2935 &ndef, &objlen, &hdrlen);
2936 if (!err && (objlen > nn
2937 || class != CLASS_UNIVERSAL || tag != TAG_ENUMERATED))
2938 err = gpg_error (GPG_ERR_INV_OBJ);
2939 if (!err && objlen > sizeof (ul))
2940 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
2944 for (ul=0; objlen; objlen--)
2947 ul |= (*pp++) & 0xff;
2954 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2955 &ndef, &objlen, &hdrlen);
2956 if (!err && (objlen > nn
2957 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
2958 err = gpg_error (GPG_ERR_INV_OBJ);
2959 if (!err && objlen > sizeof (ul))
2960 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
2963 for (ul=0; objlen; objlen--)
2966 ul |= (*pp++) & 0xff;
2969 aodf->min_length = ul;
2973 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2974 &ndef, &objlen, &hdrlen);
2975 if (!err && (objlen > nn
2976 || class != CLASS_UNIVERSAL || tag != TAG_INTEGER))
2977 err = gpg_error (GPG_ERR_INV_OBJ);
2978 if (!err && objlen > sizeof (ul))
2979 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
2982 for (ul=0; objlen; objlen--)
2985 ul |= (*pp++) & 0xff;
2988 aodf->stored_length = ul;
2990 /* optional maxLength */
2992 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
2993 &ndef, &objlen, &hdrlen);
2994 if (gpg_err_code (err) == GPG_ERR_EOF)
2996 if (!err && objlen > nn)
2997 err = gpg_error (GPG_ERR_INV_OBJ);
3000 if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
3002 if (objlen > sizeof (ul))
3004 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
3007 for (ul=0; objlen; objlen--)
3010 ul |= (*pp++) & 0xff;
3013 aodf->max_length = ul;
3014 aodf->max_length_valid = 1;
3017 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
3018 &ndef, &objlen, &hdrlen);
3019 if (gpg_err_code (err) == GPG_ERR_EOF)
3021 if (!err && objlen > nn)
3022 err = gpg_error (GPG_ERR_INV_OBJ);
3027 /* Optional pinReference. */
3028 if (class == CLASS_CONTEXT && tag == 0)
3030 if (objlen > sizeof (ul))
3032 err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING);
3035 for (ul=0; objlen; objlen--)
3038 ul |= (*pp++) & 0xff;
3041 aodf->pin_reference = ul;
3042 aodf->pin_reference_valid = 1;
3045 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
3046 &ndef, &objlen, &hdrlen);
3047 if (gpg_err_code (err) == GPG_ERR_EOF)
3049 if (!err && objlen > nn)
3050 err = gpg_error (GPG_ERR_INV_OBJ);
3055 /* Optional padChar. */
3056 if (class == CLASS_UNIVERSAL && tag == TAG_OCTET_STRING)
3060 errstr = "padChar is not of size(1)";
3063 aodf->pad_char = *pp++; nn--;
3064 aodf->pad_char_valid = 1;
3067 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
3068 &ndef, &objlen, &hdrlen);
3069 if (gpg_err_code (err) == GPG_ERR_EOF)
3071 if (!err && objlen > nn)
3072 err = gpg_error (GPG_ERR_INV_OBJ);
3077 /* Skip optional lastPinChange. */
3078 if (class == CLASS_UNIVERSAL && tag == TAG_GENERALIZED_TIME)
3084 err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
3085 &ndef, &objlen, &hdrlen);
3086 if (gpg_err_code (err) == GPG_ERR_EOF)
3088 if (!err && objlen > nn)
3089 err = gpg_error (GPG_ERR_INV_OBJ);
3094 /* Optional Path object. */
3095 if (class == CLASS_UNIVERSAL || tag == TAG_SEQUENCE)
3097 const unsigned char *ppp = pp;
3098 size_t nnn = objlen;
3104 err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
3105 &ndef, &objlen, &hdrlen);
3106 if (!err && objlen > nnn)
3107 err = gpg_error (GPG_ERR_INV_OBJ);
3111 /* Make sure that the next element has a path of even
3112 * length (FIDs are two bytes each). */
3113 if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
3116 errstr = "invalid path reference";
3120 aodf->pathlen = objlen/2;
3121 aodf->path = xtrycalloc (aodf->pathlen, sizeof *aodf->path);
3124 for (i=0; i < aodf->pathlen; i++, ppp += 2, nnn -= 2)
3125 aodf->path[i] = ((ppp[0] << 8) | ppp[1]);
3129 /* An index and length follows. */
3132 err = parse_ber_header (&ppp, &nnn, &class, &tag,
3134 &ndef, &objlen, &hdrlen);
3135 if (!err && (objlen > nnn
3136 || class != CLASS_UNIVERSAL
3137 || tag != TAG_INTEGER))
3138 err = gpg_error (GPG_ERR_INV_OBJ);
3142 for (ul=0; objlen; objlen--)
3145 ul |= (*ppp++) & 0xff;
3151 err = parse_ber_header (&ppp, &nnn, &class, &tag,
3153 &ndef, &objlen, &hdrlen);
3154 if (!err && (objlen > nnn
3155 || class != CLASS_CONTEXT || tag != 0))
3156 err = gpg_error (GPG_ERR_INV_OBJ);
3160 for (ul=0; objlen; objlen--)
3163 ul |= (*ppp++) & 0xff;
3170 else if (auth_type == AUTH_TYPE_AUTHKEY)
3175 /* Ignore further objects which might be there due to future
3176 extensions of pkcs#15. */
3179 if (gpg_err_code (err) == GPG_ERR_EOF)
3183 log_info ("p15: AODF %04hX: id=", fid);
3184 for (i=0; i < aodf->objidlen; i++)
3185 log_printf ("%02X", aodf->objid[i]);
3187 log_printf (" (%s)", aodf->label);
3190 aodf->auth_type == AUTH_TYPE_PIN? "pin" :
3191 aodf->auth_type == AUTH_TYPE_AUTHKEY? "authkey" : "?");
3194 log_printf (" path=");
3195 for (i=0; i < aodf->pathlen; i++)
3196 log_printf ("%s%04hX", i?"/":"",aodf->path[i]);
3198 log_printf ("[%lu/%lu]", aodf->off, aodf->len);
3202 log_printf (" authid=");
3203 for (i=0; i < aodf->authidlen; i++)
3204 log_printf ("%02X", aodf->authid[i]);
3206 if (aodf->auth_type == AUTH_TYPE_PIN)
3208 if (aodf->pin_reference_valid)
3209 log_printf (" pinref=0x%02lX", aodf->pin_reference);
3210 log_printf (" min=%lu", aodf->min_length);
3211 log_printf (" stored=%lu", aodf->stored_length);
3212 if (aodf->max_length_valid)
3213 log_printf (" max=%lu", aodf->max_length);
3214 if (aodf->pad_char_valid)
3215 log_printf (" pad=0x%02x", aodf->pad_char);
3217 log_info ("p15: flags=");
3219 if (aodf->pinflags.case_sensitive)
3220 log_printf ("%scase_sensitive", s), s = ",";
3221 if (aodf->pinflags.local)
3222 log_printf ("%slocal", s), s = ",";
3223 if (aodf->pinflags.change_disabled)
3224 log_printf ("%schange_disabled", s), s = ",";
3225 if (aodf->pinflags.unblock_disabled)
3226 log_printf ("%sunblock_disabled", s), s = ",";
3227 if (aodf->pinflags.initialized)
3228 log_printf ("%sinitialized", s), s = ",";
3229 if (aodf->pinflags.needs_padding)
3230 log_printf ("%sneeds_padding", s), s = ",";
3231 if (aodf->pinflags.unblocking_pin)
3232 log_printf ("%sunblocking_pin", s), s = ",";
3233 if (aodf->pinflags.so_pin)
3234 log_printf ("%sso_pin", s), s = ",";
3235 if (aodf->pinflags.disable_allowed)
3236 log_printf ("%sdisable_allowed", s), s = ",";
3237 if (aodf->pinflags.integrity_protected)
3238 log_printf ("%sintegrity_protected", s), s = ",";
3239 if (aodf->pinflags.confidentiality_protected)
3240 log_printf ("%sconfidentiality_protected", s), s = ",";
3241 if (aodf->pinflags.exchange_ref_data)
3242 log_printf ("%sexchange_ref_data", s), s = ",";
3247 switch (aodf->pintype)
3249 case PIN_TYPE_BCD: s2 = "bcd"; break;
3250 case PIN_TYPE_ASCII_NUMERIC: s2 = "ascii-numeric"; break;
3251 case PIN_TYPE_UTF8: s2 = "utf8"; break;
3252 case PIN_TYPE_HALF_NIBBLE_BCD: s2 = "half-nibble-bcd"; break;
3253 case PIN_TYPE_ISO9564_1: s2 = "iso9564-1"; break;
3255 sprintf (numbuf, "%lu", (unsigned long)aodf->pintype);
3258 log_printf ("%stype=%s", s, s2); s = ",";
3261 else if (aodf->auth_type == AUTH_TYPE_AUTHKEY)
3267 /* Put it into the list. */
3268 aodf->next = aodflist;
3271 goto next_record; /* Ready with this record. */
3274 err = gpg_error_from_syserror ();
3275 release_aodf_object (aodf);
3279 log_error ("p15: error parsing AODF record at %d: %s - skipped\n",
3280 where, errstr? errstr : gpg_strerror (err));
3282 release_aodf_object (aodf);
3285 /* If the card uses a record oriented file structure, read the
3286 * next record. Otherwise we keep on parsing the current buffer. */
3290 xfree (buffer); buffer = NULL;
3291 err = select_and_read_record (app, 0, recno, "AODF",
3292 &buffer, &buflen, NULL);
3294 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
3301 } /* End looping over all records. */
3306 release_aodflist (aodflist);
3313 /* Print the BIT STRING with the tokenflags from the TokenInfo. */
3315 print_tokeninfo_tokenflags (const unsigned char *der, size_t derlen)
3317 unsigned int bits, mask;
3318 int i, unused, full;
3323 log_printf (" [invalid object]");
3327 unused = *der++; derlen--;
3328 if ((!derlen && unused) || unused/8 > derlen)
3330 log_printf (" [wrong encoding]");
3333 full = derlen - (unused+7)/8;
3336 for (i=1; unused; i <<= 1, unused--)
3342 bits = *der++; derlen--;
3353 if ((bits & 0x80)) log_printf (" readonly");
3354 if ((bits & 0x40)) log_printf (" loginRequired");
3355 if ((bits & 0x20)) log_printf (" prnGeneration");
3356 if ((bits & 0x10)) log_printf (" eidCompliant");
3357 if ((bits & 0x08)) other = 1;
3358 if ((bits & 0x04)) other = 1;
3359 if ((bits & 0x02)) other = 1;
3360 if ((bits & 0x01)) other = 1;
3367 log_printf (" [unknown]");
3372 /* Read and parse the EF(TokenInfo).
3374 * TokenInfo ::= SEQUENCE {
3375 * version INTEGER {v1(0)} (v1,...),
3376 * serialNumber OCTET STRING,
3377 * manufacturerID Label OPTIONAL,
3378 * label [0] Label OPTIONAL,
3379 * tokenflags TokenFlags,
3380 * seInfo SEQUENCE OF SecurityEnvironmentInfo OPTIONAL,
3381 * recordInfo [1] RecordInfo OPTIONAL,
3382 * supportedAlgorithms [2] SEQUENCE OF AlgorithmInfo OPTIONAL,
3384 * issuerId [3] Label OPTIONAL,
3385 * holderId [4] Label OPTIONAL,
3386 * lastUpdate [5] LastUpdate OPTIONAL,
3387 * preferredLanguage PrintableString OPTIONAL -- In accordance with
3389 * } (CONSTRAINED BY { -- Each AlgorithmInfo.reference value must be unique --})
3391 * TokenFlags ::= BIT STRING {
3393 * loginRequired (1),
3394 * prnGeneration (2),
3400 * 30 31 02 01 00 04 04 05 45 36 9F 0C 0C 44 2D 54 01......E6...D-T
3401 * 72 75 73 74 20 47 6D 62 48 80 14 4F 66 66 69 63 rust GmbH..Offic
3402 * 65 20 69 64 65 6E 74 69 74 79 20 63 61 72 64 03 e identity card.
3403 * 02 00 40 20 63 61 72 64 03 02 00 40 00 00 00 00 ..@ card...@....
3404 * 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
3408 * 5 4: OCTET STRING 05 45 36 9F
3409 * 11 12: UTF8String 'D-Trust GmbH'
3410 * 25 20: [0] 'Office identity card'
3412 * : '00000010'B (bit 1)
3413 * : Error: Spurious zero bits in bitstring.
3417 read_ef_tokeninfo (app_t app)
3420 unsigned char *buffer = NULL;
3422 const unsigned char *p;
3423 size_t n, objlen, hdrlen;
3424 int class, tag, constructed, ndef;
3427 release_tokeninfo (app);
3428 app->app_local->card_product = CARD_PRODUCT_UNKNOWN;
3430 err = select_and_read_binary (app, 0x5032, "TokenInfo", &buffer, &buflen);
3437 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3438 &ndef, &objlen, &hdrlen);
3439 if (!err && (objlen > n || tag != TAG_SEQUENCE))
3440 err = gpg_error (GPG_ERR_INV_OBJ);
3443 log_error ("p15: error parsing TokenInfo: %s\n", gpg_strerror (err));
3450 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3451 &ndef, &objlen, &hdrlen);
3452 if (!err && (objlen > n || tag != TAG_INTEGER))
3453 err = gpg_error (GPG_ERR_INV_OBJ);
3457 for (ul=0; objlen; objlen--)
3460 ul |= (*p++) & 0xff;
3465 log_error ("p15: invalid version %lu in TokenInfo\n", ul);
3466 err = gpg_error (GPG_ERR_INV_OBJ);
3471 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3472 &ndef, &objlen, &hdrlen);
3473 if (!err && (objlen > n || tag != TAG_OCTET_STRING || !objlen))
3474 err = gpg_error (GPG_ERR_INV_OBJ);
3478 xfree (app->app_local->serialno);
3479 app->app_local->serialno = xtrymalloc (objlen);
3480 if (!app->app_local->serialno)
3482 err = gpg_error_from_syserror ();
3485 memcpy (app->app_local->serialno, p, objlen);
3486 app->app_local->serialnolen = objlen;
3490 /* Is there an optional manufacturerID? */
3491 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3492 &ndef, &objlen, &hdrlen);
3493 if (!err && (objlen > n || !objlen))
3494 err = gpg_error (GPG_ERR_INV_OBJ);
3497 if (class == CLASS_UNIVERSAL && tag == TAG_UTF8_STRING)
3499 app->app_local->manufacturer_id = percent_data_escape (0, NULL,
3504 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3505 &ndef, &objlen, &hdrlen);
3506 if (!err && (objlen > n || !objlen))
3507 err = gpg_error (GPG_ERR_INV_OBJ);
3511 if (class == CLASS_CONTEXT && tag == 0)
3513 app->app_local->token_label = percent_data_escape (0, NULL, p, objlen);
3518 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
3519 &ndef, &objlen, &hdrlen);
3520 if (!err && (objlen > n || !objlen))
3521 err = gpg_error (GPG_ERR_INV_OBJ);
3525 /* The next is the mandatory tokenflags object. */
3526 if (class == CLASS_UNIVERSAL && tag == TAG_BIT_STRING)
3528 app->app_local->tokenflagslen = objlen;
3529 app->app_local->tokenflags = xtrymalloc (objlen);
3530 if (!app->app_local->tokenflags)
3532 err = gpg_error_from_syserror ();
3535 memcpy (app->app_local->tokenflags, p, objlen);
3547 /* Get all the basic information from the pkcs#15 card, check the
3548 structure and initialize our local context. This is used once at
3549 application initialization. */
3551 read_p15_info (app_t app)
3554 prkdf_object_t prkdf;
3557 err = read_ef_tokeninfo (app);
3560 /* If we don't have a serial number yet but the TokenInfo provides
3562 if (!APP_CARD(app)->serialno && app->app_local->serialno)
3564 APP_CARD(app)->serialno = app->app_local->serialno;
3565 APP_CARD(app)->serialnolen = app->app_local->serialnolen;
3566 app->app_local->serialno = NULL;
3567 app->app_local->serialnolen = 0;
3568 err = app_munge_serialno (APP_CARD(app));
3573 release_lists (app);
3575 if (IS_CARDOS_5 (app)
3576 && app->app_local->manufacturer_id
3577 && !ascii_strcasecmp (app->app_local->manufacturer_id, "GeNUA mbH"))
3579 if (!app->app_local->card_product)
3580 app->app_local->card_product = CARD_PRODUCT_GENUA;
3583 /* Read the ODF so that we know the location of all directory
3585 /* Fixme: We might need to get a non-standard ODF FID from TokenInfo. */
3586 err = read_ef_odf (app, 0x5031);
3590 /* Read certificate information. */
3591 log_assert (!app->app_local->certificate_info);
3592 log_assert (!app->app_local->trusted_certificate_info);
3593 log_assert (!app->app_local->useful_certificate_info);
3594 err = read_ef_cdf (app, app->app_local->odf.certificates, 'c',
3595 &app->app_local->certificate_info);
3596 if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
3597 err = read_ef_cdf (app, app->app_local->odf.trusted_certificates, 't',
3598 &app->app_local->trusted_certificate_info);
3599 if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
3600 err = read_ef_cdf (app, app->app_local->odf.useful_certificates, 'u',
3601 &app->app_local->useful_certificate_info);
3602 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
3607 /* Read information about public keys. */
3608 log_assert (!app->app_local->public_key_info);
3609 err = read_ef_pukdf (app, app->app_local->odf.public_keys,
3610 &app->app_local->public_key_info);
3611 if (!err || gpg_err_code (err) == GPG_ERR_NO_DATA)
3612 err = read_ef_pukdf (app, app->app_local->odf.trusted_public_keys,
3613 &app->app_local->public_key_info);
3614 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
3619 /* Read information about private keys. */
3620 log_assert (!app->app_local->private_key_info);
3621 err = read_ef_prkdf (app, app->app_local->odf.private_keys,
3622 &app->app_local->private_key_info);
3623 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
3628 /* Read information about authentication objects. */
3629 log_assert (!app->app_local->auth_object_info);
3630 err = read_ef_aodf (app, app->app_local->odf.auth_objects,
3631 &app->app_local->auth_object_info);
3632 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
3636 /* See whether we can extend the private key information using
3637 * information from certificates. We use only the first matching
3638 * certificate; if we want to change this strategy we should walk
3639 * over the certificates and then find the corresponsing private key
3641 app->app_local->any_gpgusage = 0;
3642 for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
3650 log_printhex (prkdf->objid, prkdf->objidlen, "p15: prkdf id=");
3651 if (cdf_object_from_objid (app, prkdf->objidlen, prkdf->objid, &cdf)
3652 && cdf_object_from_label (app, prkdf->label, &cdf))
3653 continue; /* No matching certificate. */
3654 if (!cdf->cert) /* Read and parse the certificate. */
3655 readcert_by_cdf (app, cdf, NULL, NULL);
3657 continue; /* Unsupported or broken certificate. */
3662 const unsigned char *der;
3663 size_t off, derlen, objlen, hdrlen;
3664 int class, tag, constructed, ndef;
3666 for (i=0; !(err = ksba_cert_get_extension
3667 (cdf->cert, i, &oid, NULL, &off, &derlen)); i++)
3668 if (!strcmp (oid, "1.3.6.1.4.1.11591.2.2.10") )
3670 if (!err && (der = ksba_cert_get_image (cdf->cert, NULL)))
3673 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
3674 &ndef, &objlen, &hdrlen);
3675 if (!err && (objlen > derlen || tag != TAG_OCTET_STRING || ndef))
3676 err = gpg_error (GPG_ERR_INV_OBJ);
3681 log_printhex (der, derlen, "p15: OpenPGP KDF parms:");
3682 /* Store them if they match the known OpenPGP format. */
3683 if (derlen == 4 && der[0] == 3 && der[1] == 1)
3684 memcpy (prkdf->ecdh_kdf, der, 4);
3690 if (ksba_cert_get_ext_key_usages (cdf->cert, &extusage))
3691 continue; /* No extended key usage attribute. */
3694 log_debug ("p15: ExtKeyUsages: %s\n", extusage);
3696 while (p && (pend=strchr (p, ':')))
3699 if ( *pend == 'C' ) /* Look only at critical usages. */
3701 prkdf->extusage.valid = 1;
3703 if (!strcmp (p, oid_kp_codeSigning)
3704 || !strcmp (p, oid_kp_timeStamping)
3705 || !strcmp (p, oid_kp_ocspSigning)
3706 || !strcmp (p, oid_kp_ms_documentSigning)
3707 || !strcmp (p, oid_kp_ms_old_documentSigning))
3708 prkdf->extusage.sign = 1;
3709 else if (!strcmp (p, oid_kp_emailProtection))
3710 prkdf->extusage.encr = 1;
3711 else if (!strcmp (p, oid_kp_serverAuth)
3712 || !strcmp (p, oid_kp_clientAuth)
3713 || !strcmp (p, oid_kp_ms_smartcardLogon))
3714 prkdf->extusage.auth = 1;
3715 else if (!strcmp (p, oid_kp_anyExtendedKeyUsage))
3717 prkdf->extusage.sign = 1;
3718 prkdf->extusage.encr = 1;
3719 prkdf->extusage.auth = 1;
3727 /* Now check the gpg Usage. Here we don't care about
3728 * critical or non-critical here. */
3730 ; /* No more need to look for other caps. */
3731 else if (!strcmp (p, oid_kp_gpgUsageCert))
3733 prkdf->gpgusage.cert = 1;
3734 prkdf->gpgusage.any = 1;
3735 app->app_local->any_gpgusage = 1;
3737 else if (!strcmp (p, oid_kp_gpgUsageSign))
3739 prkdf->gpgusage.sign = 1;
3740 prkdf->gpgusage.any = 1;
3741 app->app_local->any_gpgusage = 1;
3743 else if (!strcmp (p, oid_kp_gpgUsageEncr))
3745 prkdf->gpgusage.encr = 1;
3746 prkdf->gpgusage.any = 1;
3747 app->app_local->any_gpgusage = 1;
3749 else if (!strcmp (p, oid_kp_gpgUsageAuth))
3751 prkdf->gpgusage.auth = 1;
3752 prkdf->gpgusage.any = 1;
3753 app->app_local->any_gpgusage = 1;
3756 /* Skip to next item. */
3757 if ((p = strchr (pend, '\n')))
3763 /* See whether we can figure out something about the card. */
3764 if (!app->app_local->card_product
3765 && app->app_local->manufacturer_id
3766 && !strcmp (app->app_local->manufacturer_id, "www.atos.net/cardos")
3767 && IS_CARDOS_5 (app))
3769 /* This is a modern CARDOS card. */
3771 for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
3773 if (prkdf->label && !strcmp (prkdf->label, "IdentityKey")
3774 && prkdf->key_reference_valid && prkdf->key_reference == 1
3777 else if (prkdf->label && !strcmp (prkdf->label, "TransportKey")
3778 && prkdf->key_reference_valid && prkdf->key_reference==2
3783 app->app_local->card_product = CARD_PRODUCT_RSCS;
3786 if (!app->app_local->card_product
3787 && app->app_local->token_label
3788 && !strncmp (app->app_local->token_label, "D-TRUST Card V3", 15)
3789 && app->app_local->card_type == CARD_TYPE_CARDOS_50)
3791 app->app_local->card_product = CARD_PRODUCT_DTRUST;
3795 /* Now print the info about the PrKDF. */
3801 const char *cardstr;
3803 for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
3805 log_info ("p15: PrKDF %04hX: id=", app->app_local->odf.private_keys);
3806 for (i=0; i < prkdf->objidlen; i++)
3807 log_printf ("%02X", prkdf->objid[i]);
3809 log_printf (" (%s)", prkdf->label);
3810 log_info ("p15: path=");
3811 for (i=0; i < prkdf->pathlen; i++)
3812 log_printf ("%s%04hX", i?"/":"",prkdf->path[i]);
3813 if (prkdf->have_off)
3814 log_printf ("[%lu/%lu]", prkdf->off, prkdf->len);
3817 log_printf (" authid=");
3818 for (i=0; i < prkdf->authidlen; i++)
3819 log_printf ("%02X", prkdf->authid[i]);
3821 if (prkdf->key_reference_valid)
3822 log_printf (" keyref=0x%02lX", prkdf->key_reference);
3823 log_printf (" type=%s", prkdf->is_ecc? "ecc":"rsa");
3824 if (prkdf->accessflags.any)
3825 dump_keyaccess_flags (prkdf->accessflags);
3826 dump_keyusage_flags (prkdf->usageflags);
3827 if (prkdf->extusage.valid)
3828 log_info ("p15: extusage=%s%s%s%s%s",
3829 prkdf->extusage.sign? "sign":"",
3830 (prkdf->extusage.sign
3831 && prkdf->extusage.encr)?",":"",
3832 prkdf->extusage.encr? "encr":"",
3833 ((prkdf->extusage.sign || prkdf->extusage.encr)
3834 && prkdf->extusage.auth)?",":"",
3835 prkdf->extusage.auth? "auth":"");
3836 if (prkdf->gpgusage.any)
3837 dump_gpgusage_flags (prkdf->gpgusage);
3842 log_info ("p15: TokenInfo:\n");
3843 if (app->app_local->serialno)
3845 log_info ("p15: serialNumber .: ");
3846 log_printhex (app->app_local->serialno, app->app_local->serialnolen,
3849 else if (APP_CARD(app)->serialno)
3851 log_info ("p15: serialNumber .: ");
3852 log_printhex (APP_CARD(app)->serialno, APP_CARD(app)->serialnolen,
3856 if (app->app_local->manufacturer_id)
3857 log_info ("p15: manufacturerID: %s\n",
3858 app->app_local->manufacturer_id);
3859 if (app->app_local->card_product)
3861 cardstr = cardproduct2str (app->app_local->card_product);
3862 log_info ("p15: product ......: %d%s%s%s\n",
3863 app->app_local->card_product,
3864 *cardstr? " (":"", cardstr, *cardstr? ")":"");
3866 if (app->app_local->token_label)
3867 log_info ("p15: label ........: %s\n", app->app_local->token_label);
3868 if (app->app_local->tokenflags)
3870 log_info ("p15: tokenflags ...:");
3871 print_tokeninfo_tokenflags (app->app_local->tokenflags,
3872 app->app_local->tokenflagslen);
3876 log_info ("p15: atr ..........: ");
3877 atr = apdu_get_atr (app_get_slot (app), &atrlen);
3879 log_printf ("[error]\n");
3882 log_printhex (atr, atrlen, "");
3886 cardstr = cardtype2str (app->app_local->card_type);
3887 log_info ("p15: cardtype .....: %d%s%s%s\n",
3888 app->app_local->card_type,
3889 *cardstr? " (":"", cardstr, *cardstr? ")":"");
3896 /* Helper to do_learn_status: Send information about all certificates
3897 listed in CERTINFO back. Use CERTTYPE as type of the
3900 send_certinfo (app_t app, ctrl_t ctrl, const char *certtype,
3901 cdf_object_t certinfo)
3903 for (; certinfo; certinfo = certinfo->next)
3909 buf = xtrymalloc (9 + certinfo->objidlen*2 + 1);
3911 return gpg_error_from_syserror ();
3912 p = stpcpy (buf, "P15");
3913 if (app->app_local->home_df != DEFAULT_HOME_DF)
3915 snprintf (p, 6, "-%04X",
3916 (unsigned int)(app->app_local->home_df & 0xffff));
3919 p = stpcpy (p, ".");
3920 bin2hex (certinfo->objid, certinfo->objidlen, p);
3922 label = (certinfo->label && *certinfo->label)? certinfo->label : "-";
3923 labelbuf = percent_data_escape (0, NULL, label, strlen (label));
3927 return gpg_error_from_syserror ();
3930 send_status_info (ctrl, "CERTINFO",
3931 certtype, strlen (certtype),
3933 labelbuf, strlen (labelbuf),
3942 /* Get the keygrip of the private key object PRKDF. On success the
3943 * keygrip, the algo and the length are stored in the KEYGRIP,
3944 * KEYALGO, and KEYNBITS fields of the PRKDF object. */
3946 keygrip_from_prkdf (app_t app, prkdf_object_t prkdf)
3953 gcry_sexp_t s_pkey = NULL;
3955 /* Easy if we got a cached version. */
3956 if (prkdf->keygrip_valid)
3959 xfree (prkdf->common_name);
3960 prkdf->common_name = NULL;
3961 xfree (prkdf->serial_number);
3962 prkdf->serial_number = NULL;
3964 /* We could have also checked whether a public key directory file
3965 * and a matching public key for PRKDF is available. This would
3966 * make extraction of the key faster. However, this way we don't
3967 * have a way to look at extended key attributes to check gpgusage.
3968 * FIXME: Add public key lookup if no certificate was found. */
3970 /* Look for a matching certificate. A certificate matches if the id
3971 * matches the one of the private key info. If none was found we
3972 * also try to match on the label. */
3973 err = cdf_object_from_objid (app, prkdf->objidlen, prkdf->objid, &cdf);
3974 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
3975 err = cdf_object_from_label (app, prkdf->label, &cdf);
3977 err = gpg_error (GPG_ERR_NOT_FOUND);
3981 err = readcert_by_cdf (app, cdf, &der, &derlen);
3985 err = ksba_cert_new (&cert);
3987 err = ksba_cert_init_from_mem (cert, der, derlen);
3990 err = app_help_get_keygrip_string (cert, prkdf->keygrip, &s_pkey, NULL);
3991 if (!err && !prkdf->gpgusage.any)
3993 /* Try to get the CN and the SerialNumber from the certificate;
3994 * we use a very simple approach here which should work in many
3995 * cases. Eventually we should add a rfc-2253 parser into
3996 * libksba to make it easier to parse such a string.
3997 * We don't do this if this is marked as gpg key and thus
3998 * has only a dummy certificate.
4000 * First example string:
4001 * "CN=Otto Schily,O=Miniluv,C=DE"
4002 * Second example string:
4003 * "2.5.4.5=#445452323030303236333531,2.5.4.4=#4B6F6368,"
4004 * "2.5.4.42=#5765726E6572,CN=Werner Koch,OU=For testing"
4005 * " purposes only!,O=Testorganisation,C=DE"
4007 char *dn = ksba_cert_get_subject (cert, 0);
4010 char *p, *pend, *buf;
4012 p = strstr (dn, "CN=");
4013 if (p && (p==dn || p[-1] == ','))
4016 if (!(pend = strchr (p, ',')))
4017 pend = p + strlen (p);
4018 if (pend && pend > p
4019 && (prkdf->common_name = xtrymalloc ((pend - p) + 1)))
4021 memcpy (prkdf->common_name, p, pend-p);
4022 prkdf->common_name[pend-p] = 0;
4025 p = strstr (dn, "2.5.4.5=#"); /* OID of the SerialNumber */
4026 if (p && (p==dn || p[-1] == ','))
4029 if (!(pend = strchr (p, ',')))
4030 pend = p + strlen (p);
4031 if (pend && pend > p
4032 && (buf = xtrymalloc ((pend - p) + 1)))
4034 memcpy (buf, p, pend-p);
4036 if (!hex2str (buf, buf, strlen (buf)+1, NULL))
4037 xfree (buf); /* Invalid hex encoding. */
4039 prkdf->serial_number = buf;
4046 if (!err && !prkdf->keytime)
4048 ksba_isotime_t isot;
4051 ksba_cert_get_validity (cert, 0, isot);
4052 t = isotime2epoch (isot);
4053 prkdf->keytime = (t == (time_t)(-1))? 0 : (u32)t;
4054 prkdf->have_keytime = 1;
4057 if (!err && !prkdf->keyalgostr)
4058 prkdf->keyalgostr = pubkey_algo_string (s_pkey, NULL);
4060 ksba_cert_release (cert);
4064 prkdf->keyalgo = get_pk_algo_from_key (s_pkey);
4065 if (!prkdf->keyalgo)
4067 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
4071 prkdf->keynbits = gcry_pk_get_nbits (s_pkey);
4072 if (!prkdf->keynbits)
4074 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
4078 prkdf->keygrip_valid = 1; /* Yeah, got everything. */
4081 gcry_sexp_release (s_pkey);
4086 /* Return a malloced keyref string for PRKDF. Returns NULL on
4087 * malloc failure. */
4089 keyref_from_prkdf (app_t app, prkdf_object_t prkdf)
4093 buf = xtrymalloc (4 + 5 + prkdf->objidlen*2 + 1);
4096 p = stpcpy (buf, "P15");
4097 if (app->app_local->home_df != DEFAULT_HOME_DF)
4099 snprintf (p, 6, "-%04X",
4100 (unsigned int)(app->app_local->home_df & 0xffff));
4103 p = stpcpy (p, ".");
4104 bin2hex (prkdf->objid, prkdf->objidlen, p);
4109 /* Helper to do_learn_status: Send information about all known
4110 keypairs back. FIXME: much code duplication from
4113 send_keypairinfo (app_t app, ctrl_t ctrl, prkdf_object_t prkdf)
4117 for (; prkdf; prkdf = prkdf->next)
4122 buf = keyref_from_prkdf (app, prkdf);
4124 return gpg_error_from_syserror ();
4126 err = keygrip_from_prkdf (app, prkdf);
4129 log_error ("p15: error getting keygrip from ");
4130 for (j=0; j < prkdf->pathlen; j++)
4131 log_printf ("%s%04hX", j?"/":"", prkdf->path[j]);
4132 log_printf (": %s\n", gpg_strerror (err));
4138 const char *algostr;
4139 size_t usagelen = 0;
4141 if (prkdf->gpgusage.any)
4143 if (prkdf->gpgusage.sign)
4144 usage[usagelen++] = 's';
4145 if (prkdf->gpgusage.cert)
4146 usage[usagelen++] = 'c';
4147 if (prkdf->gpgusage.encr)
4148 usage[usagelen++] = 'e';
4149 if (prkdf->gpgusage.auth)
4150 usage[usagelen++] = 'a';
4154 if ((prkdf->usageflags.sign
4155 || prkdf->usageflags.sign_recover
4156 || prkdf->usageflags.non_repudiation)
4157 && (!prkdf->extusage.valid
4158 || prkdf->extusage.sign))
4159 usage[usagelen++] = 's';
4160 if ((prkdf->usageflags.sign
4161 || prkdf->usageflags.sign_recover)
4162 && (!prkdf->extusage.valid || prkdf->extusage.sign))
4163 usage[usagelen++] = 'c';
4164 if ((prkdf->usageflags.decrypt
4165 || prkdf->usageflags.unwrap)
4166 && (!prkdf->extusage.valid || prkdf->extusage.encr))
4167 usage[usagelen++] = 'e';
4168 if ((prkdf->usageflags.sign
4169 || prkdf->usageflags.sign_recover)
4170 && (!prkdf->extusage.valid || prkdf->extusage.auth))
4171 usage[usagelen++] = 'a';
4174 log_assert (strlen (prkdf->keygrip) == 40);
4175 if (prkdf->keytime && prkdf->have_keytime)
4176 snprintf (keytime, sizeof keytime, "%lu",
4177 (unsigned long)prkdf->keytime);
4179 strcpy (keytime, "-");
4181 algostr = prkdf->keyalgostr;
4183 send_status_info (ctrl, "KEYPAIRINFO",
4184 prkdf->keygrip, 2*KEYGRIP_LEN,
4187 keytime, strlen (keytime),
4188 algostr, strlen (algostr?algostr:""),
4198 /* This is the handler for the LEARN command. Note that if
4199 * APP_LEARN_FLAG_REREAD is set and this function returns an error,
4200 * the caller must deinitialize this application. */
4202 do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
4206 if (flags & APP_LEARN_FLAG_REREAD)
4208 err = read_p15_info (app);
4213 if ((flags & APP_LEARN_FLAG_KEYPAIRINFO))
4217 err = do_getattr (app, ctrl, "MANUFACTURER");
4219 err = send_certinfo (app, ctrl, "100",
4220 app->app_local->certificate_info);
4222 err = send_certinfo (app, ctrl, "101",
4223 app->app_local->trusted_certificate_info);
4225 err = send_certinfo (app, ctrl, "102",
4226 app->app_local->useful_certificate_info);
4230 err = send_keypairinfo (app, ctrl, app->app_local->private_key_info);
4233 err = do_getattr (app, ctrl, "CHV-STATUS");
4235 err = do_getattr (app, ctrl, "CHV-LABEL");
4242 /* Read a certificate using the information in CDF and return the
4243 * certificate in a newly malloced buffer R_CERT and its length
4244 * R_CERTLEN. Also parses the certificate. R_CERT and R_CERTLEN may
4245 * be NULL to do just the caching. */
4247 readcert_by_cdf (app_t app, cdf_object_t cdf,
4248 unsigned char **r_cert, size_t *r_certlen)
4251 unsigned char *buffer = NULL;
4252 const unsigned char *p, *save_p;
4254 int class, tag, constructed, ndef;
4255 size_t totobjlen, objlen, hdrlen;
4264 /* First check whether it has been cached. */
4267 const unsigned char *image;
4270 if (!r_cert || !r_certlen)
4271 return 0; /* Caller does not actually want the result. */
4273 image = ksba_cert_get_image (cdf->cert, &imagelen);
4276 log_error ("p15: ksba_cert_get_image failed\n");
4277 return gpg_error (GPG_ERR_INTERNAL);
4279 *r_cert = xtrymalloc (imagelen);
4281 return gpg_error_from_syserror ();
4282 memcpy (*r_cert, image, imagelen);
4283 *r_certlen = imagelen;
4289 log_info ("p15: Reading CDF: id=");
4290 for (i=0; i < cdf->objidlen; i++)
4291 log_printf ("%02X", cdf->objid[i]);
4293 log_printf (" (%s)", cdf->label);
4294 log_info ("p15: path=");
4295 for (i=0; i < cdf->pathlen; i++)
4296 log_printf ("%s%04hX", i?"/":"", cdf->path[i]);
4298 log_printf ("[%lu/%lu]", cdf->off, cdf->len);
4301 log_printf (" authid=");
4302 for (i=0; i < cdf->authidlen; i++)
4303 log_printf ("%02X", cdf->authid[i]);
4308 /* Read the entire file. fixme: This could be optimized by first
4309 reading the header to figure out how long the certificate
4311 err = select_ef_by_path (app, cdf->path, cdf->pathlen);
4315 if (app->app_local->no_extended_mode || !cdf->len)
4316 err = iso7816_read_binary_ext (app_get_slot (app), 0, cdf->off, 0,
4317 &buffer, &buflen, NULL);
4319 err = iso7816_read_binary_ext (app_get_slot (app), 1, cdf->off, cdf->len,
4320 &buffer, &buflen, NULL);
4321 if (!err && (!buflen || *buffer == 0xff))
4322 err = gpg_error (GPG_ERR_NOT_FOUND);
4325 log_error ("p15: error reading certificate id=");
4326 for (i=0; i < cdf->objidlen; i++)
4327 log_printf ("%02X", cdf->objid[i]);
4328 log_printf (" at ");
4329 for (i=0; i < cdf->pathlen; i++)
4330 log_printf ("%s%04hX", i? "/":"", cdf->path[i]);
4331 log_printf (": %s\n", gpg_strerror (err));
4335 /* Check whether this is really a certificate. */
4338 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
4339 &ndef, &objlen, &hdrlen);
4343 if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed)
4345 else if ( class == CLASS_UNIVERSAL && tag == TAG_SET && constructed )
4349 err = gpg_error (GPG_ERR_INV_OBJ);
4352 totobjlen = objlen + hdrlen;
4353 log_assert (totobjlen <= buflen);
4355 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
4356 &ndef, &objlen, &hdrlen);
4361 && class == CLASS_UNIVERSAL && tag == TAG_OBJECT_ID && !constructed)
4363 /* The certificate seems to be contained in a userCertificate
4364 container. Skip this and assume the following sequence is
4368 err = gpg_error (GPG_ERR_INV_OBJ);
4374 err = parse_ber_header (&p, &n, &class, &tag, &constructed,
4375 &ndef, &objlen, &hdrlen);
4378 if ( !(class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed) )
4380 err = gpg_error (GPG_ERR_INV_OBJ);
4383 totobjlen = objlen + hdrlen;
4384 log_assert (save_p + totobjlen <= buffer + buflen);
4385 memmove (buffer, save_p, totobjlen);
4389 /* Try to parse and cache the certificate. */
4390 err = ksba_cert_new (&cdf->cert);
4393 err = ksba_cert_init_from_mem (cdf->cert, buffer, totobjlen);
4394 if (!err) /* Call us to use the just cached cert object. */
4395 err = readcert_by_cdf (app, cdf, r_cert, r_certlen);
4398 ksba_cert_release (cdf->cert);
4405 log_error ("p15: caching certificate failed: %s\n",
4406 gpg_strerror (err));
4407 /* We return the certificate anyway so that the caller has a
4408 * chance to get an even unsupported or broken certificate. */
4409 if (r_cert && r_certlen)
4413 *r_certlen = totobjlen;
4423 /* Handler for the READCERT command.
4425 Read the certificate with id CERTID (as returned by learn_status in
4426 the CERTINFO status lines) and return it in the freshly allocated
4427 buffer to be stored at R_CERT and its length at R_CERTLEN. A error
4428 code will be returned on failure and R_CERT and R_CERTLEN will be
4431 do_readcert (app_t app, const char *certid,
4432 unsigned char **r_cert, size_t *r_certlen)
4439 err = cdf_object_from_certid (app, certid, &cdf);
4441 err = readcert_by_cdf (app, cdf, r_cert, r_certlen);
4446 /* Sort helper for an array of authentication objects. */
4448 compare_aodf_objid (const void *arg_a, const void *arg_b)
4450 const aodf_object_t a = *(const aodf_object_t *)arg_a;
4451 const aodf_object_t b = *(const aodf_object_t *)arg_b;
4454 rc = memcmp (a->objid, b->objid,
4455 a->objidlen < b->objidlen? a->objidlen : b->objidlen);
4458 if (a->objidlen < b->objidlen)
4460 else if (a->objidlen > b->objidlen)
4468 send_key_fpr_line (ctrl_t ctrl, int number, const unsigned char *fpr)
4473 bin2hex (fpr, 20, buf);
4475 *numbuf = 0; /* Don't print the key number */
4477 snprintf (numbuf, sizeof numbuf, "%d", number);
4478 send_status_info (ctrl, "KEY-FPR",
4479 numbuf, (size_t)strlen(numbuf),
4480 buf, (size_t)strlen (buf),
4485 /* If possible Emit a FPR-KEY status line for the private key object
4486 * PRKDF using NUMBER as index. */
4488 send_key_fpr (app_t app, ctrl_t ctrl, prkdf_object_t prkdf, int number)
4492 unsigned char *pk, *fixed_pk;
4493 size_t pklen, fixed_pklen;
4494 const unsigned char *m, *e, *q;
4495 size_t mlen, elen, qlen;
4496 unsigned char fpr20[20];
4498 if (cdf_object_from_objid (app, prkdf->objidlen, prkdf->objid, &cdf)
4499 && cdf_object_from_label (app, prkdf->label, &cdf))
4502 readcert_by_cdf (app, cdf, NULL, NULL);
4505 if (!prkdf->have_keytime)
4507 pk = ksba_cert_get_public_key (cdf->cert);
4510 pklen = gcry_sexp_canon_len (pk, 0, NULL, &err);
4512 if (uncompress_ecc_q_in_canon_sexp (pk, pklen, &fixed_pk, &fixed_pklen))
4519 xfree (pk); pk = NULL;
4521 pklen = fixed_pklen;
4524 switch (prkdf->keyalgo)
4527 if (!get_rsa_pk_from_canon_sexp (pk, pklen,
4528 &m, &mlen, &e, &elen)
4529 && !compute_openpgp_fpr_rsa (4,
4533 send_key_fpr_line (ctrl, number, fpr20);
4540 /* Note that NUMBER 2 indicates the encryption key. */
4541 if (!get_ecc_q_from_canon_sexp (pk, pklen, &q, &qlen)
4542 && !compute_openpgp_fpr_ecc (4,
4549 send_key_fpr_line (ctrl, number, fpr20);
4552 default: /* No Fingerprint for an unknown algo. */
4560 /* Implement the GETATTR command. This is similar to the LEARN
4561 command but returns just one value via the status interface. */
4563 do_getattr (app_t app, ctrl_t ctrl, const char *name)
4566 prkdf_object_t prkdf;
4568 if (!strcmp (name, "$AUTHKEYID")
4569 || !strcmp (name, "$ENCRKEYID")
4570 || !strcmp (name, "$SIGNKEYID"))
4574 /* We return the ID of the first private key capable of the
4575 * requested action. If any gpgusage flag has been set for the
4576 * card we consult the gpgusage flags and not the regualr usage
4579 /* FIXME: This changed: Note that we do not yet return
4580 * non_repudiation keys for $SIGNKEYID because our D-Trust
4581 * testcard uses rsaPSS, which is not supported by gpgsm and not
4582 * covered by the VS-NfD approval. */
4583 for (prkdf = app->app_local->private_key_info; prkdf;
4584 prkdf = prkdf->next)
4586 if (app->app_local->any_gpgusage)
4588 if ((name[1] == 'A' && prkdf->gpgusage.auth)
4589 || (name[1] == 'E' && prkdf->gpgusage.encr)
4590 || (name[1] == 'S' && prkdf->gpgusage.sign))
4595 if ((name[1] == 'A' && (prkdf->usageflags.sign
4596 || prkdf->usageflags.sign_recover))
4597 || (name[1] == 'E' && (prkdf->usageflags.decrypt
4598 || prkdf->usageflags.unwrap))
4599 || (name[1] == 'S' && (prkdf->usageflags.sign
4600 || prkdf->usageflags.sign_recover)))
4606 buf = keyref_from_prkdf (app, prkdf);
4608 return gpg_error_from_syserror ();
4610 send_status_info (ctrl, name, buf, strlen (buf), NULL, 0);
4615 else if (!strcmp (name, "$DISPSERIALNO"))
4617 /* For certain cards we return special IDs. There is no
4618 general rule for it so we need to decide case by case. */
4619 if (app->app_local->card_type == CARD_TYPE_BELPIC)
4621 /* The eID card has a card number printed on the front matter
4622 which seems to be a good indication. */
4623 unsigned char *buffer;
4624 const unsigned char *p;
4626 unsigned short path[] = { 0x3F00, 0xDF01, 0x4031 };
4628 err = select_ef_by_path (app, path, DIM(path) );
4630 err = iso7816_read_binary (app_get_slot (app), 0, 0,
4634 log_error ("p15: error accessing EF(ID): %s\n",
4635 gpg_strerror (err));
4639 p = find_tlv (buffer, buflen, 1, &n);
4645 memcpy (tmp+4, p+3, 7);
4647 memcpy (tmp+12, p+10, 2);
4649 send_status_info (ctrl, name, tmp, strlen (tmp), NULL, 0);
4659 /* We use the first private key object which has a serial
4660 * number set. If none was found, we parse the first
4661 * object and see whether this has then a serial number. */
4662 for (prkdf = app->app_local->private_key_info; prkdf;
4663 prkdf = prkdf->next)
4664 if (prkdf->serial_number)
4666 if (!prkdf && app->app_local->private_key_info)
4668 prkdf = app->app_local->private_key_info;
4669 keygrip_from_prkdf (app, prkdf);
4670 if (!prkdf->serial_number)
4673 sn = get_dispserialno (app, prkdf);
4674 /* Unless there is a bogus S/N in the cert, or the product
4675 * has a different strategy for the display-s/n, we should
4676 * have a suitable one from the cert now. */
4679 err = send_status_printf (ctrl, name, "%s", sn);
4684 /* No abbreviated serial number. */
4686 else if (!strcmp (name, "MANUFACTURER"))
4688 if (app->app_local->manufacturer_id
4689 && !strchr (app->app_local->manufacturer_id, '[')
4690 && app->app_local->card_product)
4691 return send_status_printf (ctrl, "MANUFACTURER", "0 %s [%s]",
4692 app->app_local->manufacturer_id,
4693 cardproduct2str (app->app_local->card_product));
4694 else if (app->app_local->manufacturer_id)
4695 return send_status_printf (ctrl, "MANUFACTURER", "0 %s",
4696 app->app_local->manufacturer_id);
4700 else if (!strcmp (name, "CHV-STATUS") || !strcmp (name, "CHV-LABEL"))
4702 int is_label = (name[4] == 'L');
4704 aodf_object_t aodfarray[16];
4710 /* Put the AODFs into an array for easier sorting. Note that we
4711 * handle onl the first 16 encountrer which should be more than
4713 for (aodf = app->app_local->auth_object_info;
4714 aodf && naodf < DIM(aodfarray); aodf = aodf->next)
4715 if (aodf->objidlen && aodf->pin_reference_valid)
4716 aodfarray[naodf++] = aodf;
4717 qsort (aodfarray, naodf, sizeof *aodfarray, compare_aodf_objid);
4719 init_membuf (&mb, 256);
4720 for (i = 0; i < naodf; i++)
4723 /* log_debug ("p15: AODF[%d] pinref=%lu id=", */
4724 /* i, aodfarray[i]->pin_reference); */
4725 /* for (j=0; j < aodfarray[i]->objidlen; j++) */
4726 /* log_printf ("%02X", aodfarray[i]->objid[j]); */
4727 /* Note that there is no need to percent escape the label
4728 * because all white space have been replaced by '_'. */
4730 put_membuf_printf (&mb, "%s%s", i? " ":"",
4731 (aodfarray[i]->label
4732 && *aodfarray[i]->label)?
4733 aodfarray[i]->label:"X");
4736 (&mb, "%s%d", i? " ":"",
4737 iso7816_verify_status (app_get_slot (app),
4738 aodfarray[i]->pin_reference));
4740 put_membuf( &mb, "", 1);
4741 p = get_membuf (&mb, NULL);
4743 return gpg_error_from_syserror ();
4744 err = send_status_direct (ctrl, is_label? "CHV-LABEL":"CHV-STATUS", p);
4748 else if (!strcmp (name, "KEY-LABEL"))
4750 /* Send KEY-LABEL lines for all private key objects. */
4752 char *idbuf, *labelbuf;
4754 for (prkdf = app->app_local->private_key_info; prkdf;
4755 prkdf = prkdf->next)
4757 idbuf = keyref_from_prkdf (app, prkdf);
4759 return gpg_error_from_syserror ();
4761 label = (prkdf->label && *prkdf->label)? prkdf->label : "-";
4762 labelbuf = percent_data_escape (0, NULL, label, strlen (label));
4766 return gpg_error_from_syserror ();
4769 send_status_info (ctrl, name,
4770 idbuf, strlen (idbuf),
4771 labelbuf, strlen(labelbuf),
4778 else if (!strcmp (name, "KEY-FPR"))
4780 /* Send KEY-FPR for the two openpgp keys. */
4781 for (prkdf = app->app_local->private_key_info; prkdf;
4782 prkdf = prkdf->next)
4784 if (app->app_local->any_gpgusage)
4786 if (prkdf->gpgusage.sign)
4791 if (prkdf->usageflags.sign || prkdf->usageflags.sign_recover)
4796 send_key_fpr (app, ctrl, prkdf, 1);
4797 for (prkdf = app->app_local->private_key_info; prkdf;
4798 prkdf = prkdf->next)
4800 if (app->app_local->any_gpgusage)
4802 if (prkdf->gpgusage.encr)
4807 if (prkdf->usageflags.decrypt || prkdf->usageflags.unwrap)
4812 send_key_fpr (app, ctrl, prkdf, 2);
4816 return gpg_error (GPG_ERR_INV_NAME);
4822 /* Micardo cards require special treatment. This is a helper for the
4823 crypto functions to manage the security environment. We expect that
4824 the key file has already been selected. FID is the one of the
4827 micardo_mse (app_t app, unsigned short fid)
4831 unsigned short refdata = 0;
4833 unsigned char msebuf[10];
4835 /* Read the KeyD file containing extra information on keys. */
4836 err = iso7816_select_file (app_get_slot (app), 0x0013, 0);
4839 log_error ("p15: error reading EF_keyD: %s\n", gpg_strerror (err));
4843 for (recno = 1, se_num = -1; ; recno++)
4845 unsigned char *buffer;
4848 const unsigned char *p, *pp;
4850 err = iso7816_read_record (app_get_slot (app), recno, 1, 0,
4852 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
4856 log_error ("p15: error reading EF_keyD record: %s\n",
4857 gpg_strerror (err));
4862 log_info (buffer, buflen, "p15: keyD record: ");
4863 log_printhex (buffer, buflen, "");
4865 p = find_tlv (buffer, buflen, 0x83, &n);
4866 if (p && n == 4 && ((p[2]<<8)|p[3]) == fid)
4868 refdata = ((p[0]<<8)|p[1]);
4869 /* Locate the SE DO and the there included sec env number. */
4870 p = find_tlv (buffer, buflen, 0x7b, &n);
4873 pp = find_tlv (p, n, 0x80, &nn);
4886 log_error ("p15: CRT for keyfile %04hX not found\n", fid);
4887 return gpg_error (GPG_ERR_NOT_FOUND);
4891 /* Restore the security environment to SE_NUM if needed */
4894 err = iso7816_manage_security_env (app_get_slot (app),
4895 0xf3, se_num, NULL, 0);
4898 log_error ("p15: restoring SE to %d failed: %s\n",
4899 se_num, gpg_strerror (err));
4904 /* Set the DST reference data. */
4908 msebuf[3] = (refdata >> 8);
4909 msebuf[4] = refdata;
4910 err = iso7816_manage_security_env (app_get_slot (app), 0x41, 0xb6, msebuf, 5);
4913 log_error ("p15: setting SE to reference file %04hX failed: %s\n",
4914 refdata, gpg_strerror (err));
4922 /* Prepare the verification of the PIN for the key PRKDF by checking
4923 * the AODF and selecting the key file. KEYREF is used for error
4924 * messages. AODF may be NULL if no verification needs to be done. */
4926 prepare_verify_pin (app_t app, const char *keyref,
4927 prkdf_object_t prkdf, aodf_object_t aodf)
4936 log_info ("p15: using AODF %04hX id=", aodf->fid);
4937 for (i=0; i < aodf->objidlen; i++)
4938 log_printf ("%02X", aodf->objid[i]);
4942 if (aodf->authid && opt.verbose)
4943 log_info ("p15: PIN is controlled by another authentication token\n");
4945 if (aodf->pinflags.integrity_protected
4946 || aodf->pinflags.confidentiality_protected)
4948 log_error ("p15: PIN verification requires"
4949 " unsupported protection method\n");
4950 return gpg_error (GPG_ERR_BAD_PIN_METHOD);
4952 if (!aodf->stored_length && aodf->pinflags.needs_padding)
4954 log_error ("p15: PIN verification requires"
4955 " padding but no length known\n");
4956 return gpg_error (GPG_ERR_INV_CARD);
4961 if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
4963 /* According to our protocol analysis we need to select a
4964 * special AID here. Before that the master file needs to be
4965 * selected. (RID A000000167 is assigned to IBM) */
4966 static char const dtrust_aid[] =
4967 { 0xA0, 0x00, 0x00, 0x01, 0x67, 0x45, 0x53, 0x49, 0x47, 0x4E };
4969 err = iso7816_select_mf (app_get_slot (app));
4971 err = iso7816_select_application (app_get_slot (app),
4972 dtrust_aid, sizeof dtrust_aid, 0);
4974 log_error ("p15: error selecting D-TRUST's AID for key %s: %s\n",
4975 keyref, gpg_strerror (err));
4979 /* Standard case: Select the key file. Note that this may
4980 * change the security environment thus we need to do it before
4981 * PIN verification. */
4982 err = select_ef_by_path (app, prkdf->path, prkdf->pathlen);
4984 log_error ("p15: error selecting file for key %s: %s\n",
4985 keyref, gpg_strerror (err));
4989 log_info ("p15: skipping EF selection for auth object '%s'\n", keyref);
4998 any_control_or_space (const char *string)
5000 const unsigned char *s;
5002 for (s = string; *s; s++)
5003 if (*s <= 0x20 || *s >= 0x7f)
5009 any_control_or_space_mem (const void *buffer, size_t buflen)
5011 const unsigned char *s;
5013 for (s = buffer; buflen; s++, buflen--)
5014 if (*s <= 0x20 || *s >= 0x7f)
5020 /* Return a malloced serial number to be shown to the user. PRKDF is
5021 * used to get it from a certificate; PRKDF may be NULL. */
5023 get_dispserialno (app_t app, prkdf_object_t prkdf)
5026 const unsigned char *s;
5030 /* We prefer the SerialNumber RDN from the Subject-DN but we don't
5031 * use it if it features a percent sign (special character in pin
5032 * prompts) or has any control character. For some cards we use a
5033 * different strategy. */
5034 if (app->app_local->card_product == CARD_PRODUCT_RSCS)
5036 /* We use only the right 8 hex digits. */
5037 serial = app_get_serialno (app);
5038 if (serial && (n=strlen (serial)) > 8)
5039 memmove (serial, serial + n - 8, 9);
5041 else if (IS_CARDOS_5 (app) && app->app_local->manufacturer_id
5042 && !ascii_strcasecmp (app->app_local->manufacturer_id,
5044 && app->serialno && app->serialnolen == 4+9
5045 && !memcmp (app->serialno, "\xff\x00\x00\xff", 4)
5046 && !any_control_or_space_mem (app->serialno + 4, 9))
5048 /* Sample: ff0000ff354830313232363537 -> "5H01 2265 7" */
5049 serial = xtrymalloc (9+2+1);
5052 s = app->serialno + 4;
5053 for (i=0; i < 4; i++)
5063 else if (prkdf && prkdf->serial_number && *prkdf->serial_number
5064 && !strchr (prkdf->serial_number, '%')
5065 && !any_control_or_space (prkdf->serial_number))
5067 serial = xtrystrdup (prkdf->serial_number);
5071 serial = app_get_serialno (app);
5078 /* Return an allocated string to be used as prompt. PRKDF may be
5079 * NULL. Returns NULL on malloc error. */
5081 make_pin_prompt (app_t app, int remaining, const char *firstline,
5082 prkdf_object_t prkdf)
5084 char *serial, *tmpbuf, *result;
5085 const char *holder = NULL;
5087 serial = get_dispserialno (app, prkdf);
5089 if (app->app_local->card_product == CARD_PRODUCT_GENUA)
5091 /* The label of the first non SO-PIN is used for the holder. */
5094 for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5095 if (aodf->auth_type == AUTH_TYPE_PIN
5096 && !aodf->pinflags.so_pin
5099 holder = aodf->label;
5106 else if (prkdf && prkdf->common_name)
5107 holder = prkdf->common_name;
5108 else if (app->app_local->token_label)
5109 holder = app->app_local->token_label;
5113 /* TRANSLATORS: Put a \x1f right before a colon. This can be
5114 * used by pinentry to nicely align the names and values. Keep
5115 * the %s at the start and end of the string. */
5116 result = xtryasprintf (_("%s"
5117 "Number\x1f: %s%%0A"
5126 return NULL; /* Out of core. */
5128 /* Append a "remaining attempts" info if needed. */
5129 if (remaining != -1 && remaining < 3)
5133 /* TRANSLATORS: This is the number of remaining attempts to
5134 * enter a PIN. Use %%0A (double-percent,0A) for a linefeed. */
5135 rembuf = xtryasprintf (_("Remaining attempts: %d"), remaining);
5138 tmpbuf = strconcat (firstline, "%0A%0A", result,
5139 "%0A%0A", rembuf, NULL);
5149 tmpbuf = strconcat (firstline, "%0A%0A", result, NULL);
5158 /* Given the private key object PRKDF and its authentication object
5159 * AODF ask for the PIN and verify that PIN. If AODF is NULL, no
5160 * authentication is done. */
5162 verify_pin (app_t app,
5163 gpg_error_t (*pincb)(void*, const char *, char **), void *pincb_arg,
5164 prkdf_object_t prkdf, aodf_object_t aodf)
5180 pin_reference = aodf->pin_reference_valid? aodf->pin_reference : 0;
5182 if (IS_CARDOS_5 (app))
5184 /* We know that this card supports a verify status check. Note
5185 * that in contrast to PIV cards ISO7816_VERIFY_NOT_NEEDED is
5186 * not supported. We also don't use the pin_verified cache
5187 * status because that is not as reliable as to ask the card
5188 * about its state. */
5189 if (prkdf) /* Clear the cache which we don't use. */
5190 prkdf->pin_verified = 0;
5192 remaining = iso7816_verify_status (app_get_slot (app), pin_reference);
5193 if (remaining == ISO7816_VERIFY_NOT_NEEDED)
5198 else if (remaining < 0)
5199 remaining = -1; /* We don't care about the concrete error. */
5200 else if (remaining < 3)
5201 log_info ("p15: PIN has %d attempts left\n", remaining);
5204 remaining = -1; /* Unknown. */
5206 /* Check whether we already verified it. */
5207 if (prkdf && (prkdf->pin_verified || verified))
5208 return 0; /* Already done. */
5211 && prkdf->usageflags.non_repudiation
5212 && (app->app_local->card_type == CARD_TYPE_BELPIC
5213 || app->app_local->card_product == CARD_PRODUCT_DTRUST))
5214 label = _("||Please enter the PIN for the key to create "
5215 "qualified signatures.");
5216 else if (aodf->pinflags.so_pin)
5217 label = _("|A|Please enter the Admin PIN");
5218 else if (aodf->pinflags.unblocking_pin)
5219 label = _("|P|Please enter the PIN Unblocking Code (PUK) "
5220 "for the standard keys.");
5222 label = _("||Please enter the PIN for the standard keys.");
5225 char *prompt = make_pin_prompt (app, remaining, label, prkdf);
5227 err = gpg_error_from_syserror ();
5229 err = pincb (pincb_arg, prompt, &pinvalue);
5234 log_info ("p15: PIN callback returned error: %s\n", gpg_strerror (err));
5238 /* We might need to cope with UTF8 things here. Not sure how
5239 min_length etc. are exactly defined, for now we take them as
5240 a plain octet count. */
5241 if (strlen (pinvalue) < aodf->min_length)
5243 log_error ("p15: PIN is too short; minimum length is %lu\n",
5245 err = gpg_error (GPG_ERR_BAD_PIN);
5247 else if (aodf->stored_length && strlen (pinvalue) > aodf->stored_length)
5249 /* This would otherwise truncate the PIN silently. */
5250 log_error ("p15: PIN is too large; maximum length is %lu\n",
5251 aodf->stored_length);
5252 err = gpg_error (GPG_ERR_BAD_PIN);
5254 else if (aodf->max_length_valid && strlen (pinvalue) > aodf->max_length)
5256 log_error ("p15: PIN is too large; maximum length is %lu\n",
5258 err = gpg_error (GPG_ERR_BAD_PIN);
5269 switch (aodf->pintype)
5272 case PIN_TYPE_ASCII_NUMERIC:
5273 for (s=pinvalue; digitp (s); s++)
5277 errstr = "Non-numeric digits found in PIN";
5278 err = gpg_error (GPG_ERR_BAD_PIN);
5283 case PIN_TYPE_HALF_NIBBLE_BCD:
5284 errstr = "PIN type Half-Nibble-BCD is not supported";
5286 case PIN_TYPE_ISO9564_1:
5287 errstr = "PIN type ISO9564-1 is not supported";
5290 errstr = "Unknown PIN type";
5295 log_error ("p15: can't verify PIN: %s\n", errstr);
5297 return err? err : gpg_error (GPG_ERR_BAD_PIN_METHOD);
5301 if (aodf->pintype == PIN_TYPE_BCD )
5306 for (ndigits=0, s=pinvalue; *s; ndigits++, s++)
5308 paddedpin = xtrymalloc (aodf->stored_length+1);
5311 err = gpg_error_from_syserror ();
5317 paddedpin[i++] = 0x20 | (ndigits & 0x0f);
5318 for (s=pinvalue; i < aodf->stored_length && *s && s[1]; s = s+2 )
5319 paddedpin[i++] = (((*s - '0') << 4) | ((s[1] - '0') & 0x0f));
5320 if (i < aodf->stored_length && *s)
5321 paddedpin[i++] = (((*s - '0') << 4)
5322 |((aodf->pad_char_valid?aodf->pad_char:0)&0x0f));
5324 if (aodf->pinflags.needs_padding)
5326 while (i < aodf->stored_length)
5327 paddedpin[i++] = aodf->pad_char_valid? aodf->pad_char : 0;
5331 pinvalue = paddedpin;
5334 else if (aodf->pinflags.needs_padding)
5338 paddedpin = xtrymalloc (aodf->stored_length+1);
5341 err = gpg_error_from_syserror ();
5345 for (i=0, s=pinvalue; i < aodf->stored_length && *s; i++, s++)
5347 /* Not sure what padding char to use if none has been set.
5348 For now we use 0x00; maybe a space would be better. */
5349 for (; i < aodf->stored_length; i++)
5350 paddedpin[i] = aodf->pad_char_valid? aodf->pad_char : 0;
5354 pinvalue = paddedpin;
5357 pinvaluelen = strlen (pinvalue);
5359 /* log_printhex (pinvalue, pinvaluelen, */
5360 /* "about to verify with ref %lu pin:", pin_reference); */
5361 err = iso7816_verify (app_get_slot (app), pin_reference,
5362 pinvalue, pinvaluelen);
5366 log_error ("p15: PIN verification failed: %s\n", gpg_strerror (err));
5370 log_info ("p15: PIN verification succeeded\n");
5372 prkdf->pin_verified = 1;
5380 /* Handler for the PKSIGN command.
5382 Create the signature and return the allocated result in OUTDATA.
5383 If a PIN is required, the PINCB will be used to ask for the PIN;
5384 that callback should return the PIN in an allocated buffer and
5385 store that as the 3rd argument. */
5387 do_sign (app_t app, ctrl_t ctrl, const char *keyidstr, int hashalgo,
5388 gpg_error_t (*pincb)(void*, const char *, char **),
5390 const void *indata, size_t indatalen,
5391 unsigned char **outdata, size_t *outdatalen )
5394 prkdf_object_t prkdf; /* The private key object. */
5395 aodf_object_t aodf; /* The associated authentication object. */
5396 int mse_done = 0; /* Set to true if the MSE has been done. */
5397 unsigned int digestlen; /* Length of the hash. */
5398 int exmode, le_value;
5399 unsigned char oidbuf[64];
5402 unsigned char *indata_buffer = NULL; /* Malloced helper. */
5406 if (!keyidstr || !*keyidstr || !indatalen)
5407 return gpg_error (GPG_ERR_INV_VALUE);
5409 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5412 if (!(prkdf->usageflags.sign
5413 || prkdf->usageflags.sign_recover
5414 || prkdf->usageflags.non_repudiation
5415 || prkdf->gpgusage.cert
5416 || prkdf->gpgusage.sign
5417 || prkdf->gpgusage.auth ))
5419 log_error ("p15: key %s may not be used for signing\n", keyidstr);
5420 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
5425 log_error ("p15: no authentication object defined for %s\n", keyidstr);
5426 /* fixme: we might want to go ahead and do without PIN
5428 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
5431 /* Find the authentication object to this private key object. */
5432 for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5433 if (aodf->objidlen == prkdf->authidlen
5434 && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
5437 log_info ("p15: no authentication for %s needed\n", keyidstr);
5439 /* We need some more info about the key - get the keygrip to
5440 * populate these fields. */
5441 err = keygrip_from_prkdf (app, prkdf);
5444 log_error ("p15: keygrip_from_prkdf failed: %s\n", gpg_strerror (err));
5449 digestlen = gcry_md_get_algo_dlen (hashalgo);
5451 /* We handle ECC separately from RSA so that we do not need to touch
5452 * working code. In particular we prepare the input data before the
5453 * verify and a possible MSE. */
5456 if (digestlen != 32 && digestlen != 48 && digestlen != 64)
5458 log_error ("p15: ECC signing not possible: dlen=%u\n", digestlen);
5459 err = gpg_error (GPG_ERR_DIGEST_ALGO);
5463 if (indatalen == digestlen)
5464 ; /* Already prepared. */
5465 else if (indatalen > digestlen)
5467 /* Assume a PKCS#1 prefix and remove it. */
5468 oidbuflen = sizeof oidbuf;
5469 err = gcry_md_get_asnoid (hashalgo, &oidbuf, &oidbuflen);
5472 log_error ("p15: no OID for hash algo %d\n", hashalgo);
5473 err = gpg_error (GPG_ERR_INTERNAL);
5476 if (indatalen != oidbuflen + digestlen
5477 || memcmp (indata, oidbuf, oidbuflen))
5479 log_error ("p15: input data too long for ECC: len=%zu\n",
5481 err = gpg_error (GPG_ERR_INV_VALUE);
5484 indata = (const char*)indata + oidbuflen;
5485 indatalen -= oidbuflen;
5489 log_error ("p15: input data too short for ECC: len=%zu\n",
5491 err = gpg_error (GPG_ERR_INV_VALUE);
5495 else /* Prepare RSA input. */
5497 unsigned int framelen;
5498 unsigned char *frame;
5501 framelen = (prkdf->keynbits+7) / 8;
5504 log_error ("p15: key length unknown"
5505 " - can't prepare PKCS#v1.5 frame\n");
5506 err = gpg_error (GPG_ERR_INV_VALUE);
5510 oidbuflen = sizeof oidbuf;
5513 /* We assume that indata already has the required
5514 * digestinfo; thus merely prepend the padding below. */
5516 else if ((err = gcry_md_get_asnoid (hashalgo, &oidbuf, &oidbuflen)))
5518 log_debug ("p15: no OID for hash algo %d\n", hashalgo);
5523 if (indatalen == digestlen)
5525 /* Plain hash in INDATA; prepend the digestinfo. */
5526 indata_buffer = xtrymalloc (oidbuflen + indatalen);
5529 err = gpg_error_from_syserror ();
5532 memcpy (indata_buffer, oidbuf, oidbuflen);
5533 memcpy (indata_buffer+oidbuflen, indata, indatalen);
5534 indata = indata_buffer;
5535 indatalen = oidbuflen + indatalen;
5537 else if (indatalen == oidbuflen + digestlen
5538 && !memcmp (indata, oidbuf, oidbuflen))
5539 ; /* We already got the correct prefix. */
5542 err = gpg_error (GPG_ERR_INV_VALUE);
5543 log_error ("p15: bad input for signing with RSA and hash %d\n",
5548 /* Now prepend the pkcs#v1.5 padding. We require at least 8
5549 * byte of padding and 3 extra bytes for the prefix and the
5550 * delimiting nul. */
5551 if (!indatalen || indatalen + 8 + 4 > framelen)
5553 err = gpg_error (GPG_ERR_INV_VALUE);
5554 log_error ("p15: input does not fit into a %u bit PKCS#v1.5 frame\n",
5558 frame = xtrymalloc (framelen);
5561 err = gpg_error_from_syserror ();
5564 if (app->app_local->card_type == CARD_TYPE_BELPIC)
5566 /* This card wants only the plain hash w/o any prefix. */
5567 /* FIXME: We may want to remove this code because it is unlikely
5568 * that such cards are still in use. */
5569 memcpy (frame, indata, indatalen);
5570 framelen = indatalen;
5576 frame[n++] = 1; /* Block type. */
5577 i = framelen - indatalen - 3 ;
5578 memset (frame+n, 0xff, i);
5580 frame[n++] = 0; /* Delimiter. */
5581 memcpy (frame+n, indata, indatalen);
5583 log_assert (n == framelen);
5585 /* And now put it into the indata_buffer. */
5586 xfree (indata_buffer);
5587 indata_buffer = frame;
5588 indata = indata_buffer;
5589 indatalen = framelen;
5592 /* Prepare PIN verification. This is split so that we can do
5593 * MSE operation for some task after having selected the key file but
5594 * before sending the verify APDU. */
5595 err = prepare_verify_pin (app, keyidstr, prkdf, aodf);
5599 /* Due to the fact that the non-repudiation signature on a BELPIC
5600 card requires a verify immediately before the DSO we set the
5601 MSE before we do the verification. Other cards might also allow
5602 this but I don't want to break anything, thus we do it only
5603 for the BELPIC card here.
5604 FIXME: see comment above about these cards. */
5605 if (app->app_local->card_type == CARD_TYPE_BELPIC)
5607 unsigned char mse[5];
5609 mse[0] = 4; /* Length of the template. */
5610 mse[1] = 0x80; /* Algorithm reference tag. */
5611 if (hashalgo == MD_USER_TLS_MD5SHA1)
5612 mse[2] = 0x01; /* Let card do pkcs#1 0xFF padding. */
5614 mse[2] = 0x02; /* RSASSA-PKCS1-v1.5 using SHA1. */
5615 mse[3] = 0x84; /* Private key reference tag. */
5616 mse[4] = prkdf->key_reference_valid? prkdf->key_reference : 0x82;
5618 err = iso7816_manage_security_env (app_get_slot (app),
5625 log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5629 /* Now that we have all the information available run the actual PIN
5631 err = verify_pin (app, pincb, pincb_arg, prkdf, aodf);
5635 /* Manage security environment needs to be tweaked for certain cards. */
5638 else if (app->app_local->card_type == CARD_TYPE_TCOS)
5640 /* TCOS creates signatures always using the local key 0. MSE
5643 else if (app->app_local->card_type == CARD_TYPE_MICARDO)
5645 if (!prkdf->pathlen)
5646 err = gpg_error (GPG_ERR_BUG);
5648 err = micardo_mse (app, prkdf->path[prkdf->pathlen-1]);
5650 else if (prkdf->key_reference_valid)
5652 unsigned char mse[3];
5654 mse[0] = 0x84; /* Select asym. key. */
5656 mse[2] = prkdf->key_reference;
5658 err = iso7816_manage_security_env (app_get_slot (app),
5664 log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5668 if (prkdf->keyalgo == GCRY_PK_RSA && prkdf->keynbits >= 2048)
5671 le_value = prkdf->keynbits / 8;
5679 err = iso7816_compute_ds (app_get_slot (app),
5680 exmode, indata, indatalen,
5681 le_value, outdata, outdatalen);
5684 xfree (indata_buffer);
5689 /* Handler for the PKAUTH command.
5691 This is basically the same as the PKSIGN command but we first check
5692 that the requested key is suitable for authentication; that is, it
5693 must match the criteria used for the attribute $AUTHKEYID. See
5694 do_sign for calling conventions; there is no HASHALGO, though. */
5696 do_auth (app_t app, ctrl_t ctrl, const char *keyidstr,
5697 gpg_error_t (*pincb)(void*, const char *, char **),
5699 const void *indata, size_t indatalen,
5700 unsigned char **outdata, size_t *outdatalen )
5703 prkdf_object_t prkdf;
5706 if (!keyidstr || !*keyidstr)
5707 return gpg_error (GPG_ERR_INV_VALUE);
5709 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5712 if (!(prkdf->usageflags.sign || prkdf->gpgusage.auth))
5714 log_error ("p15: key %s may not be used for authentication\n", keyidstr);
5715 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
5718 algo = indatalen == 36? MD_USER_TLS_MD5SHA1 : GCRY_MD_SHA1;
5719 return do_sign (app, ctrl, keyidstr, algo, pincb, pincb_arg,
5720 indata, indatalen, outdata, outdatalen);
5724 /* Handler for the PKDECRYPT command. Decrypt the data in INDATA and
5725 * return the allocated result in OUTDATA. If a PIN is required the
5726 * PINCB will be used to ask for the PIN; it should return the PIN in
5727 * an allocated buffer and put it into PIN. */
5729 do_decipher (app_t app, ctrl_t ctrl, const char *keyidstr,
5730 gpg_error_t (*pincb)(void*, const char *, char **),
5732 const void *indata, size_t indatalen,
5733 unsigned char **outdata, size_t *outdatalen,
5734 unsigned int *r_info)
5737 prkdf_object_t prkdf; /* The private key object. */
5738 aodf_object_t aodf; /* The associated authentication object. */
5739 int exmode, le_value, padind;
5744 if (!keyidstr || !*keyidstr)
5745 return gpg_error (GPG_ERR_INV_VALUE);
5746 if (!indatalen || !indata || !outdatalen || !outdata)
5747 return gpg_error (GPG_ERR_INV_ARG);
5749 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5752 if (!(prkdf->usageflags.decrypt
5753 || prkdf->usageflags.unwrap
5754 || prkdf->gpgusage.encr ))
5756 log_error ("p15: key %s may not be used for decryption\n", keyidstr);
5757 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
5760 /* Find the authentication object to this private key object. */
5763 log_error ("p15: no authentication object defined for %s\n", keyidstr);
5764 /* fixme: we might want to go ahead and do without PIN
5766 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
5768 for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5769 if (aodf->objidlen == prkdf->authidlen
5770 && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
5773 log_info ("p15: no authentication for %s needed\n", keyidstr);
5775 /* We need some more info about the key - get the keygrip to
5776 * populate these fields. */
5777 err = keygrip_from_prkdf (app, prkdf);
5780 log_error ("p15: keygrip_from_prkdf failed: %s\n", gpg_strerror (err));
5784 /* Verify the PIN. */
5785 err = prepare_verify_pin (app, keyidstr, prkdf, aodf);
5787 err = verify_pin (app, pincb, pincb_arg, prkdf, aodf);
5791 if (prkdf->is_ecc && IS_CARDOS_5(app))
5794 err = iso7816_manage_security_env (app_get_slot (app), 0xF3, 0x01,
5798 log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5804 /* The next is guess work for CardOS. */
5805 if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
5807 /* From analyzing an USB trace of a Windows signing application
5808 * we see that the SE is simply reset to 0x14. It seems to be
5809 * sufficient to do this for decryption; signing still works
5810 * with the standard code despite that our trace showed that
5811 * there the SE is restored to 0x09. Note that the special
5812 * D-Trust AID is in any case select by prepare_verify_pin.
5814 * Hey, D-Trust please hand over the specs so that you can
5815 * actually sell your cards and we can properly implement it;
5816 * other vendors understand this and do not demand ridiculous
5817 * paper work or complicated procedures to get samples. */
5818 err = iso7816_manage_security_env (app_get_slot (app),
5819 0xF3, 0x14, NULL, 0);
5822 else if (prkdf->key_reference_valid)
5824 unsigned char mse[9];
5827 /* Note: This works with CardOS but the D-Trust card has the
5828 * problem that the next created signature would be broken. */
5833 mse[i++] = 0x80; /* Algorithm reference. */
5835 mse[i++] = 0x0a; /* RSA, no padding. */
5837 mse[i++] = 0x84; /* Key reference. */
5839 mse[i++] = prkdf->key_reference;
5840 if (prkdf->is_ecc && IS_CARDOS_5(app))
5842 mse[i++] = 0x95; /* ???. */
5846 log_assert (i <= DIM(mse));
5847 err = iso7816_manage_security_env (app_get_slot (app), 0x41, 0xB8,
5850 /* Check for MSE error. */
5853 log_error ("p15: MSE failed: %s\n", gpg_strerror (err));
5857 exmode = le_value = 0;
5859 if (prkdf->keyalgo == GCRY_PK_RSA && prkdf->keynbits >= 2048)
5861 exmode = 1; /* Extended length w/o a limit. */
5862 le_value = prkdf->keynbits / 8;
5865 if (app->app_local->card_product == CARD_PRODUCT_DTRUST)
5868 if (prkdf->is_ecc && IS_CARDOS_5(app))
5870 if ((indatalen & 1) && *(const char *)indata == 0x04)
5872 /* Strip indicator byte. */
5874 indata = (const char *)indata + 1;
5876 err = iso7816_pso_csv (app_get_slot (app), exmode,
5879 outdata, outdatalen);
5883 err = iso7816_decipher (app_get_slot (app), exmode,
5886 outdata, outdatalen);
5893 /* Perform a simple verify operation for the PIN specified by
5894 * KEYIDSTR. Note that we require a key reference which is then used
5895 * to select the authentication object. Return GPG_ERR_NO_PIN if a
5896 * PIN is not required for using the private key KEYIDSTR. */
5898 do_check_pin (app_t app, ctrl_t ctrl, const char *keyidstr,
5899 gpg_error_t (*pincb)(void*, const char *, char **),
5903 prkdf_object_t prkdf; /* The private key object. */
5904 aodf_object_t aodf; /* The associated authentication object. */
5908 if (!keyidstr || !*keyidstr)
5909 return gpg_error (GPG_ERR_INV_VALUE);
5911 err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
5913 && gpg_err_code (err) != GPG_ERR_INV_ID
5914 && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
5917 if (err) /* Not found or invalid - assume it is the label. */
5920 for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5921 if (aodf->label && !ascii_strcasecmp (aodf->label, keyidstr))
5924 return err; /* Re-use the original error code. */
5926 else /* Find the authentication object to this private key object. */
5930 log_error ("p15: no authentication object defined for %s\n",
5932 return gpg_error (GPG_ERR_UNSUPPORTED_OPERATION);
5934 for (aodf = app->app_local->auth_object_info; aodf; aodf = aodf->next)
5935 if (aodf->objidlen == prkdf->authidlen
5936 && !memcmp (aodf->objid, prkdf->authid, prkdf->authidlen))
5938 if (!aodf) /* None found. */
5939 return gpg_error (GPG_ERR_NO_PIN);
5942 err = prepare_verify_pin (app, keyidstr, prkdf, aodf);
5944 err = verify_pin (app, pincb, pincb_arg, prkdf, aodf);
5950 /* Process the various keygrip based info requests. */
5952 do_with_keygrip (app_t app, ctrl_t ctrl, int action,
5953 const char *want_keygripstr, int capability)
5956 char *serialno = NULL;
5958 prkdf_object_t prkdf;
5960 /* First a quick check for valid parameters. */
5963 case KEYGRIP_ACTION_LOOKUP:
5964 if (!want_keygripstr)
5966 err = gpg_error (GPG_ERR_NOT_FOUND);
5970 case KEYGRIP_ACTION_SEND_DATA:
5973 case KEYGRIP_ACTION_WRITE_STATUS:
5976 err = gpg_error (GPG_ERR_INV_ARG);
5980 /* Allocate the s/n string if needed. */
5981 if (action != KEYGRIP_ACTION_LOOKUP)
5983 serialno = app_get_serialno (app);
5986 err = gpg_error_from_syserror ();
5991 for (prkdf = app->app_local->private_key_info;
5992 prkdf; prkdf = prkdf->next)
5994 if (keygrip_from_prkdf (app, prkdf))
5997 if (action == KEYGRIP_ACTION_LOOKUP)
5999 if (!strcmp (prkdf->keygrip, want_keygripstr))
6001 err = 0; /* Found */
6005 else if (!want_keygripstr || !strcmp (prkdf->keygrip, want_keygripstr))
6009 if (capability == GCRY_PK_USAGE_SIGN)
6011 if (!(prkdf->usageflags.sign || prkdf->usageflags.sign_recover
6012 || prkdf->usageflags.non_repudiation))
6015 else if (capability == GCRY_PK_USAGE_ENCR)
6017 if (!(prkdf->usageflags.decrypt || prkdf->usageflags.unwrap))
6020 else if (capability == GCRY_PK_USAGE_AUTH)
6022 if (!(prkdf->usageflags.sign || prkdf->usageflags.sign_recover))
6026 keyref = keyref_from_prkdf (app, prkdf);
6029 err = gpg_error_from_syserror ();
6033 send_keyinfo (ctrl, as_data, prkdf->keygrip, serialno, keyref);
6035 if (want_keygripstr)
6037 err = 0; /* Found */
6043 /* Return an error so that the dispatcher keeps on looping over the
6044 * other applications. For clarity we use a different error code
6045 * when listing all keys. Note that in lookup mode WANT_KEYGRIPSTR
6047 if (!want_keygripstr)
6048 err = gpg_error (GPG_ERR_TRUE);
6050 err = gpg_error (GPG_ERR_NOT_FOUND);
6059 /* Assume that EF(DIR) has been selected. Read its content and figure
6060 out the home EF of pkcs#15. Return that home DF or 0 if not found
6061 and the value at the address of BELPIC indicates whether it was
6062 found by the belpic aid. */
6063 static unsigned short
6064 read_home_df (int slot, int *r_belpic)
6067 unsigned char *buffer;
6068 const unsigned char *p, *pp;
6069 size_t buflen, n, nn;
6070 unsigned short result = 0;
6074 err = iso7816_read_binary (slot, 0, 0, &buffer, &buflen);
6077 log_error ("p15: error reading EF(DIR): %s\n", gpg_strerror (err));
6081 /* FIXME: We need to scan all records. */
6082 p = find_tlv (buffer, buflen, 0x61, &n);
6085 pp = find_tlv (p, n, 0x4f, &nn);
6086 if (pp && ((nn == sizeof pkcs15_aid && !memcmp (pp, pkcs15_aid, nn))
6087 || (*r_belpic = (nn == sizeof pkcs15be_aid
6088 && !memcmp (pp, pkcs15be_aid, nn)))))
6090 pp = find_tlv (p, n, 0x50, &nn);
6091 if (pp && opt.verbose)
6092 log_info ("p15: application label from EF(DIR) is '%.*s'\n",
6094 pp = find_tlv (p, n, 0x51, &nn);
6095 if (pp && nn == 4 && *pp == 0x3f && !pp[1])
6097 result = ((pp[2] << 8) | pp[3]);
6099 log_info ("p15: application directory is 0x%04hX\n", result);
6109 Select the PKCS#15 application on the card in SLOT.
6112 app_select_p15 (app_t app)
6114 int slot = app_get_slot (app);
6116 unsigned short def_home_df = 0;
6117 card_type_t card_type = CARD_TYPE_UNKNOWN;
6120 unsigned char *fci = NULL;
6123 rc = iso7816_select_application_ext (slot, pkcs15_aid, sizeof pkcs15_aid, 1,
6126 { /* Not found: Try to locate it from 2F00. We use direct path
6127 selection here because it seems that the Belgian eID card
6128 does only allow for that. Many other cards supports this
6129 selection method too. Note, that we don't use
6130 select_application above for the Belgian card - the call
6131 works but it seems that it does not switch to the correct DF.
6132 Using the 2f02 just works. */
6133 unsigned short path[1] = { 0x2f00 };
6135 rc = iso7816_select_path (slot, path, 1, 0);
6139 def_home_df = read_home_df (slot, &is_belpic);
6142 path[0] = def_home_df;
6143 rc = iso7816_select_path (slot, path, 1, 0);
6148 { /* Still not found: Try the default DF. */
6149 def_home_df = DEFAULT_HOME_DF;
6150 rc = iso7816_select_file (slot, def_home_df, 1);
6154 /* Determine the type of the card. The general case is to look
6155 it up from the ATR table. For the Belgian eID card we know
6156 it instantly from the AID. */
6159 card_type = CARD_TYPE_BELPIC;
6167 atr = apdu_get_atr (app_get_slot (app), &atrlen);
6169 rc = gpg_error (GPG_ERR_INV_CARD);
6172 for (i=0; card_atr_list[i].atrlen; i++)
6173 if (card_atr_list[i].atrlen == atrlen
6174 && !memcmp (card_atr_list[i].atr, atr, atrlen))
6176 card_type = card_atr_list[i].type;
6185 app->apptype = APPTYPE_P15;
6187 app->app_local = xtrycalloc (1, sizeof *app->app_local);
6188 if (!app->app_local)
6190 rc = gpg_error_from_syserror ();
6194 /* Set the home DF from the FCI returned by the select. */
6195 if (!def_home_df && fci)
6197 const unsigned char *s;
6200 s = find_tlv (fci, fcilen, 0x83, &n);
6202 def_home_df = buf16_to_ushort (s);
6206 log_printhex (fci, fcilen, "fci:");
6207 log_info ("p15: select did not return the DF - using default\n");
6208 def_home_df = DEFAULT_HOME_DF;
6211 app->app_local->home_df = def_home_df;
6213 /* Store the card type. FIXME: We might want to put this into
6214 the common APP structure. */
6215 app->app_local->card_type = card_type;
6217 app->app_local->card_product = CARD_PRODUCT_UNKNOWN;
6219 /* Store whether we may and should use direct path selection. */
6222 case CARD_TYPE_CARDOS_50:
6223 case CARD_TYPE_CARDOS_53:
6227 app->app_local->no_extended_mode = 1;
6230 /* Use whatever has been determined above. */
6233 app->app_local->direct_path_selection = direct;
6235 /* Read basic information and thus check whether this is a real
6237 rc = read_p15_info (app);
6241 /* Special serial number munging. We need to check for a German
6242 prototype card right here because we need to access to
6243 EF(TokenInfo). We mark such a serial number by the using a
6244 prefix of FF0100. */
6245 if (APP_CARD(app)->serialnolen == 12
6246 && !memcmp (APP_CARD(app)->serialno,
6247 "\xD2\x76\0\0\0\0\0\0\0\0\0\0", 12))
6249 /* This is a German card with a silly serial number. Try to get
6250 the serial number from the EF(TokenInfo). . */
6253 /* FIXME: actually get it from EF(TokenInfo). */
6255 p = xtrymalloc (3 + APP_CARD(app)->serialnolen);
6257 rc = gpg_error (gpg_err_code_from_errno (errno));
6260 memcpy (p, "\xff\x01", 3);
6261 memcpy (p+3, APP_CARD(app)->serialno, APP_CARD(app)->serialnolen);
6262 APP_CARD(app)->serialnolen += 3;
6263 xfree (APP_CARD(app)->serialno);
6264 APP_CARD(app)->serialno = p;
6268 app->fnc.deinit = do_deinit;
6269 app->fnc.prep_reselect = NULL;
6270 app->fnc.reselect = NULL;
6271 app->fnc.learn_status = do_learn_status;
6272 app->fnc.readcert = do_readcert;
6273 app->fnc.getattr = do_getattr;
6274 app->fnc.setattr = NULL;
6275 app->fnc.genkey = NULL;
6276 app->fnc.sign = do_sign;
6277 app->fnc.auth = do_auth;
6278 app->fnc.decipher = do_decipher;
6279 app->fnc.change_pin = NULL;
6280 app->fnc.check_pin = do_check_pin;
6281 app->fnc.with_keygrip = do_with_keygrip;