1 /* card-util.c - Utility functions for the OpenPGP card.
2 * Copyright (C) 2003-2005, 2009 Free Software Foundation, Inc.
3 * Copyright (C) 2003-2005, 2009 Werner Koch
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/>.
26 #ifdef HAVE_LIBREADLINE
27 # define GNUPG_LIBREADLINE_H_INCLUDED
28 # include <readline/readline.h>
29 #endif /*HAVE_LIBREADLINE*/
31 #if GNUPG_MAJOR_VERSION != 1
33 #endif /*GNUPG_MAJOR_VERSION != 1*/
34 #include "../common/util.h"
35 #include "../common/i18n.h"
36 #include "../common/ttyio.h"
37 #include "../common/status.h"
40 #include "keyserver-internal.h"
42 #if GNUPG_MAJOR_VERSION == 1
43 # include "cardglue.h"
44 #else /*GNUPG_MAJOR_VERSION!=1*/
45 # include "call-agent.h"
46 #endif /*GNUPG_MAJOR_VERSION!=1*/
48 #define CONTROL_D ('D' - 'A' + 1)
52 write_sc_op_status (gpg_error_t err)
54 switch (gpg_err_code (err))
57 write_status (STATUS_SC_OP_SUCCESS);
59 #if GNUPG_MAJOR_VERSION != 1
60 case GPG_ERR_CANCELED:
61 case GPG_ERR_FULLY_CANCELED:
62 write_status_text (STATUS_SC_OP_FAILURE, "1");
65 write_status_text (STATUS_SC_OP_FAILURE, "2");
68 write_status (STATUS_SC_OP_FAILURE);
70 #endif /* GNUPG_MAJOR_VERSION != 1 */
75 /* Change the PIN of an OpenPGP card. This is an interactive
78 change_pin (int unblock_v2, int allow_admin)
80 struct agent_card_info_s info;
83 rc = agent_scd_learn (&info, 0);
86 log_error (_("OpenPGP card not available: %s\n"),
91 log_info (_("OpenPGP card no. %s detected\n"),
92 info.serialno? info.serialno : "[none]");
94 agent_clear_pin_cache (info.serialno);
98 agent_release_card_info (&info);
99 log_error (_("can't do this in batch mode\n"));
107 log_error (_("This command is only available for version 2 cards\n"));
108 else if (!info.chvretry[1])
109 log_error (_("Reset Code not or not anymore available\n"));
112 rc = agent_scd_change_pin (2, info.serialno);
113 write_sc_op_status (rc);
115 tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc));
117 tty_printf ("PIN changed.\n");
120 else if (!allow_admin)
122 rc = agent_scd_change_pin (1, info.serialno);
123 write_sc_op_status (rc);
125 tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc));
127 tty_printf ("PIN changed.\n");
135 tty_printf ("1 - change PIN\n"
137 "3 - change Admin PIN\n"
138 "4 - set the Reset Code\n"
142 answer = cpr_get("cardutil.change_pin.menu",_("Your selection? "));
144 if (strlen (answer) != 1)
150 rc = agent_scd_change_pin (1, info.serialno);
151 write_sc_op_status (rc);
153 tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc));
155 tty_printf ("PIN changed.\n");
157 else if (*answer == '2')
160 rc = agent_scd_change_pin (101, info.serialno);
161 write_sc_op_status (rc);
163 tty_printf ("Error unblocking the PIN: %s\n", gpg_strerror (rc));
165 tty_printf ("PIN unblocked and new PIN set.\n");
167 else if (*answer == '3')
169 /* Change Admin PIN. */
170 rc = agent_scd_change_pin (3, info.serialno);
171 write_sc_op_status (rc);
173 tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc));
175 tty_printf ("PIN changed.\n");
177 else if (*answer == '4')
179 /* Set a new Reset Code. */
180 rc = agent_scd_change_pin (102, info.serialno);
181 write_sc_op_status (rc);
183 tty_printf ("Error setting the Reset Code: %s\n",
186 tty_printf ("Reset Code set.\n");
188 else if (*answer == 'q' || *answer == 'Q')
194 agent_release_card_info (&info);
198 get_manufacturer (unsigned int no)
200 /* Note: Make sure that there is no colon or linefeed in the string. */
203 case 0x0001: return "PPC Card Systems";
204 case 0x0002: return "Prism";
205 case 0x0003: return "OpenFortress";
206 case 0x0004: return "Wewid";
207 case 0x0005: return "ZeitControl";
208 case 0x0006: return "Yubico";
209 case 0x0007: return "OpenKMS";
210 case 0x0008: return "LogoEmail";
211 case 0x0009: return "Fidesmo";
212 case 0x000A: return "Dangerous Things";
214 case 0x002A: return "Magrathea";
215 case 0x0042: return "GnuPG e.V.";
217 case 0x1337: return "Warsaw Hackerspace";
218 case 0x2342: return "warpzone"; /* hackerspace Muenster. */
219 case 0x63AF: return "Trustica";
220 case 0xBD0E: return "Paranoidlabs";
221 case 0xF517: return "FSIJ";
223 /* 0x0000 and 0xFFFF are defined as test cards per spec,
224 0xFF00 to 0xFFFE are assigned for use with randomly created
227 case 0xffff: return "test card";
228 default: return (no & 0xff00) == 0xff00? "unmanaged S/N range":"unknown";
234 print_sha1_fpr (estream_t fp, const unsigned char *fpr)
240 for (i=0; i < 20 ; i+=2, fpr += 2 )
243 tty_fprintf (fp, " ");
244 tty_fprintf (fp, " %02X%02X", *fpr, fpr[1]);
248 tty_fprintf (fp, " [none]");
249 tty_fprintf (fp, "\n");
254 print_sha1_fpr_colon (estream_t fp, const unsigned char *fpr)
260 for (i=0; i < 20 ; i++, fpr++)
261 es_fprintf (fp, "%02X", *fpr);
268 print_keygrip (estream_t fp, const unsigned char *grp)
272 if (opt.with_keygrip)
274 tty_fprintf (fp, " keygrip ....: ");
275 for (i=0; i < 20 ; i++, grp++)
276 es_fprintf (fp, "%02X", *grp);
277 tty_fprintf (fp, "\n");
283 print_name (estream_t fp, const char *text, const char *name)
285 tty_fprintf (fp, "%s", text);
287 /* FIXME: tty_printf_utf8_string2 eats everything after and
288 including an @ - e.g. when printing an url. */
292 print_utf8_buffer2 (fp, name, strlen (name), '\n');
294 tty_print_utf8_string2 (NULL, name, strlen (name), 0);
297 tty_fprintf (fp, _("[not set]"));
298 tty_fprintf (fp, "\n");
302 print_isoname (estream_t fp, const char *text,
303 const char *tag, const char *name)
306 es_fprintf (fp, "%s:", tag);
308 tty_fprintf (fp, "%s", text);
312 char *p, *given, *buf = xstrdup (name);
314 given = strstr (buf, "<<");
318 if (given && given[2])
323 es_write_sanitized (fp, given, strlen (given), ":", NULL);
325 print_utf8_buffer2 (fp, given, strlen (given), '\n');
327 tty_print_utf8_string2 (NULL, given, strlen (given), 0);
332 tty_fprintf (fp, " ");
336 es_write_sanitized (fp, buf, strlen (buf), ":", NULL);
338 print_utf8_buffer2 (fp, buf, strlen (buf), '\n');
340 tty_print_utf8_string2 (NULL, buf, strlen (buf), 0);
348 tty_fprintf (fp, _("[not set]"));
352 es_fputs (":\n", fp);
354 tty_fprintf (fp, "\n");
357 /* Return true if the SHA1 fingerprint FPR consists only of zeroes. */
359 fpr_is_zero (const char *fpr)
363 for (i=0; i < 20 && !fpr[i]; i++)
369 /* Return true if the SHA1 fingerprint FPR consists only of 0xFF. */
371 fpr_is_ff (const char *fpr)
375 for (i=0; i < 20 && fpr[i] == '\xff'; i++)
381 /* Print all available information about the current card. */
383 current_card_status (ctrl_t ctrl, estream_t fp,
384 char *serialno, size_t serialnobuflen)
386 struct agent_card_info_s info;
387 PKT_public_key *pk = xcalloc (1, sizeof *pk);
388 kbnode_t keyblock = NULL;
391 const unsigned char *thefpr;
394 if (serialno && serialnobuflen)
397 rc = agent_scd_learn (&info, 0);
401 es_fputs ("AID:::\n", fp);
402 log_error (_("OpenPGP card not available: %s\n"), gpg_strerror (rc));
408 es_fprintf (fp, "Reader:%s:", info.reader? info.reader : "");
410 tty_fprintf (fp, "Reader ...........: %s\n",
411 info.reader? info.reader : "[none]");
413 es_fprintf (fp, "AID:%s:", info.serialno? info.serialno : "");
415 tty_fprintf (fp, "Application ID ...: %s\n",
416 info.serialno? info.serialno : "[none]");
417 if (!info.serialno || strncmp (info.serialno, "D27600012401", 12)
418 || strlen (info.serialno) != 32 )
420 if (info.apptype && !strcmp (info.apptype, "NKS"))
423 es_fputs ("netkey-card:\n", fp);
424 log_info ("this is a NetKey card\n");
426 else if (info.apptype && !strcmp (info.apptype, "DINSIG"))
429 es_fputs ("dinsig-card:\n", fp);
430 log_info ("this is a DINSIG compliant card\n");
432 else if (info.apptype && !strcmp (info.apptype, "P15"))
435 es_fputs ("pkcs15-card:\n", fp);
436 log_info ("this is a PKCS#15 compliant card\n");
438 else if (info.apptype && !strcmp (info.apptype, "GELDKARTE"))
441 es_fputs ("geldkarte-card:\n", fp);
442 log_info ("this is a Geldkarte compliant card\n");
447 es_fputs ("unknown:\n", fp);
449 log_info ("not an OpenPGP card\n");
450 agent_release_card_info (&info);
457 else if (strlen (info.serialno)+1 > serialnobuflen)
458 log_error ("serial number longer than expected\n");
460 strcpy (serialno, info.serialno);
463 es_fputs ("openpgp-card:\n", fp);
468 es_fprintf (fp, "version:%.4s:\n", info.serialno+12);
469 uval = xtoi_2(info.serialno+16)*256 + xtoi_2 (info.serialno+18);
470 es_fprintf (fp, "vendor:%04x:%s:\n", uval, get_manufacturer (uval));
471 es_fprintf (fp, "serial:%.8s:\n", info.serialno+20);
473 print_isoname (fp, "Name of cardholder: ", "name", info.disp_name);
475 es_fputs ("lang:", fp);
477 es_write_sanitized (fp, info.disp_lang, strlen (info.disp_lang),
479 es_fputs (":\n", fp);
481 es_fprintf (fp, "sex:%c:\n", (info.disp_sex == 1? 'm':
482 info.disp_sex == 2? 'f' : 'u'));
484 es_fputs ("url:", fp);
486 es_write_sanitized (fp, info.pubkey_url, strlen (info.pubkey_url),
488 es_fputs (":\n", fp);
490 es_fputs ("login:", fp);
492 es_write_sanitized (fp, info.login_data, strlen (info.login_data),
494 es_fputs (":\n", fp);
496 es_fprintf (fp, "forcepin:%d:::\n", !info.chv1_cached);
497 for (i=0; i < DIM (info.key_attr); i++)
498 if (info.key_attr[i].algo == PUBKEY_ALGO_RSA)
499 es_fprintf (fp, "keyattr:%d:%d:%u:\n", i+1,
500 info.key_attr[i].algo, info.key_attr[i].nbits);
501 else if (info.key_attr[i].algo == PUBKEY_ALGO_ECDH
502 || info.key_attr[i].algo == PUBKEY_ALGO_ECDSA
503 || info.key_attr[i].algo == PUBKEY_ALGO_EDDSA)
504 es_fprintf (fp, "keyattr:%d:%d:%s:\n", i+1,
505 info.key_attr[i].algo, info.key_attr[i].curve);
506 es_fprintf (fp, "maxpinlen:%d:%d:%d:\n",
507 info.chvmaxlen[0], info.chvmaxlen[1], info.chvmaxlen[2]);
508 es_fprintf (fp, "pinretry:%d:%d:%d:\n",
509 info.chvretry[0], info.chvretry[1], info.chvretry[2]);
510 es_fprintf (fp, "sigcount:%lu:::\n", info.sig_counter);
512 for (i=0; i < 4; i++)
514 if (info.private_do[i])
516 es_fprintf (fp, "private_do:%d:", i+1);
517 es_write_sanitized (fp, info.private_do[i],
518 strlen (info.private_do[i]), ":", NULL);
519 es_fputs (":\n", fp);
523 es_fputs ("cafpr:", fp);
524 print_sha1_fpr_colon (fp, info.cafpr1valid? info.cafpr1:NULL);
525 print_sha1_fpr_colon (fp, info.cafpr2valid? info.cafpr2:NULL);
526 print_sha1_fpr_colon (fp, info.cafpr3valid? info.cafpr3:NULL);
528 es_fputs ("fpr:", fp);
529 print_sha1_fpr_colon (fp, info.fpr1valid? info.fpr1:NULL);
530 print_sha1_fpr_colon (fp, info.fpr2valid? info.fpr2:NULL);
531 print_sha1_fpr_colon (fp, info.fpr3valid? info.fpr3:NULL);
533 es_fprintf (fp, "fprtime:%lu:%lu:%lu:\n",
534 (unsigned long)info.fpr1time, (unsigned long)info.fpr2time,
535 (unsigned long)info.fpr3time);
536 es_fputs ("grp:", fp);
537 print_sha1_fpr_colon (fp, info.grp1);
538 print_sha1_fpr_colon (fp, info.grp2);
539 print_sha1_fpr_colon (fp, info.grp3);
544 tty_fprintf (fp, "Version ..........: %.1s%c.%.1s%c\n",
545 info.serialno[12] == '0'?"":info.serialno+12,
547 info.serialno[14] == '0'?"":info.serialno+14,
549 tty_fprintf (fp, "Manufacturer .....: %s\n",
550 get_manufacturer (xtoi_2(info.serialno+16)*256
551 + xtoi_2 (info.serialno+18)));
552 tty_fprintf (fp, "Serial number ....: %.8s\n", info.serialno+20);
554 print_isoname (fp, "Name of cardholder: ", "name", info.disp_name);
555 print_name (fp, "Language prefs ...: ", info.disp_lang);
556 tty_fprintf (fp, "Salutation .......: %s\n",
557 info.disp_sex == 1? _("Mr."):
558 info.disp_sex == 2? _("Mrs.") : "");
559 print_name (fp, "URL of public key : ", info.pubkey_url);
560 print_name (fp, "Login data .......: ", info.login_data);
561 if (info.private_do[0])
562 print_name (fp, "Private DO 1 .....: ", info.private_do[0]);
563 if (info.private_do[1])
564 print_name (fp, "Private DO 2 .....: ", info.private_do[1]);
565 if (info.private_do[2])
566 print_name (fp, "Private DO 3 .....: ", info.private_do[2]);
567 if (info.private_do[3])
568 print_name (fp, "Private DO 4 .....: ", info.private_do[3]);
569 if (info.cafpr1valid)
571 tty_fprintf (fp, "CA fingerprint %d .:", 1);
572 print_sha1_fpr (fp, info.cafpr1);
574 if (info.cafpr2valid)
576 tty_fprintf (fp, "CA fingerprint %d .:", 2);
577 print_sha1_fpr (fp, info.cafpr2);
579 if (info.cafpr3valid)
581 tty_fprintf (fp, "CA fingerprint %d .:", 3);
582 print_sha1_fpr (fp, info.cafpr3);
584 tty_fprintf (fp, "Signature PIN ....: %s\n",
585 info.chv1_cached? _("not forced"): _("forced"));
586 if (info.key_attr[0].algo)
588 tty_fprintf (fp, "Key attributes ...:");
589 for (i=0; i < DIM (info.key_attr); i++)
590 if (info.key_attr[i].algo == PUBKEY_ALGO_RSA)
591 tty_fprintf (fp, " rsa%u", info.key_attr[i].nbits);
592 else if (info.key_attr[i].algo == PUBKEY_ALGO_ECDH
593 || info.key_attr[i].algo == PUBKEY_ALGO_ECDSA
594 || info.key_attr[i].algo == PUBKEY_ALGO_EDDSA)
596 const char *curve_for_print = "?";
598 if (info.key_attr[i].curve)
601 oid = openpgp_curve_to_oid (info.key_attr[i].curve, NULL);
603 curve_for_print = openpgp_oid_to_curve (oid, 0);
605 tty_fprintf (fp, " %s", curve_for_print);
607 tty_fprintf (fp, "\n");
609 tty_fprintf (fp, "Max. PIN lengths .: %d %d %d\n",
610 info.chvmaxlen[0], info.chvmaxlen[1], info.chvmaxlen[2]);
611 tty_fprintf (fp, "PIN retry counter : %d %d %d\n",
612 info.chvretry[0], info.chvretry[1], info.chvretry[2]);
613 tty_fprintf (fp, "Signature counter : %lu\n", info.sig_counter);
614 tty_fprintf (fp, "Signature key ....:");
615 print_sha1_fpr (fp, info.fpr1valid? info.fpr1:NULL);
616 if (info.fpr1valid && info.fpr1time)
618 tty_fprintf (fp, " created ....: %s\n",
619 isotimestamp (info.fpr1time));
620 print_keygrip (fp, info.grp1);
622 tty_fprintf (fp, "Encryption key....:");
623 print_sha1_fpr (fp, info.fpr2valid? info.fpr2:NULL);
624 if (info.fpr2valid && info.fpr2time)
626 tty_fprintf (fp, " created ....: %s\n",
627 isotimestamp (info.fpr2time));
628 print_keygrip (fp, info.grp2);
630 tty_fprintf (fp, "Authentication key:");
631 print_sha1_fpr (fp, info.fpr3valid? info.fpr3:NULL);
632 if (info.fpr3valid && info.fpr3time)
634 tty_fprintf (fp, " created ....: %s\n",
635 isotimestamp (info.fpr3time));
636 print_keygrip (fp, info.grp3);
638 tty_fprintf (fp, "General key info..: ");
640 thefpr = (info.fpr1valid? info.fpr1 : info.fpr2valid? info.fpr2 :
641 info.fpr3valid? info.fpr3 : NULL);
642 /* If the fingerprint is all 0xff, the key has no asssociated
643 OpenPGP certificate. */
644 if ( thefpr && !fpr_is_ff (thefpr)
645 && !get_pubkey_byfprint (ctrl, pk, &keyblock, thefpr, 20))
647 print_pubkey_info (ctrl, fp, pk);
649 print_card_key_info (fp, keyblock);
652 tty_fprintf (fp, "[none]\n");
655 release_kbnode (keyblock);
656 free_public_key (pk);
657 agent_release_card_info (&info);
661 /* Print all available information for specific card with SERIALNO.
662 Print all available information for current card when SERIALNO is NULL.
663 Or print for all cards when SERIALNO is "all". */
665 card_status (ctrl_t ctrl, estream_t fp, const char *serialno)
668 strlist_t card_list, sl;
672 if (serialno == NULL)
674 current_card_status (ctrl, fp, NULL, 0);
678 if (!strcmp (serialno, "all"))
681 err = agent_scd_serialno (&serialno0, NULL);
684 if (gpg_err_code (err) != GPG_ERR_ENODEV && opt.verbose)
685 log_info (_("error getting serial number of card: %s\n"),
687 /* Nothing available. */
691 err = agent_scd_cardlist (&card_list);
693 for (sl = card_list; sl; sl = sl->next)
697 if (!all_cards && strcmp (serialno, sl->d))
700 err = agent_scd_serialno (&serialno1, sl->d);
704 log_info (_("error getting serial number of card: %s\n"),
709 current_card_status (ctrl, fp, NULL, 0);
716 /* Select the original card again. */
717 err = agent_scd_serialno (&serialno0, serialno0);
721 free_strlist (card_list);
726 get_one_name (const char *prompt1, const char *prompt2)
733 name = cpr_get (prompt1, prompt2);
738 for (i=0; name[i] && name[i] >= ' ' && name[i] <= 126; i++)
741 /* The name must be in Latin-1 and not UTF-8 - lacking the code
742 to ensure this we restrict it to ASCII. */
744 tty_printf (_("Error: Only plain ASCII is currently allowed.\n"));
745 else if (strchr (name, '<'))
746 tty_printf (_("Error: The \"<\" character may not be used.\n"));
747 else if (strstr (name, " "))
748 tty_printf (_("Error: Double spaces are not allowed.\n"));
760 char *surname = NULL, *givenname = NULL;
764 surname = get_one_name ("keygen.smartcard.surname",
765 _("Cardholder's surname: "));
766 givenname = get_one_name ("keygen.smartcard.givenname",
767 _("Cardholder's given name: "));
768 if (!surname || !givenname || (!*surname && !*givenname))
772 return -1; /*canceled*/
775 isoname = xmalloc ( strlen (surname) + 2 + strlen (givenname) + 1);
776 strcpy (stpcpy (stpcpy (isoname, surname), "<<"), givenname);
779 for (p=isoname; *p; p++)
783 if (strlen (isoname) > 39 )
785 tty_printf (_("Error: Combined name too long "
786 "(limit is %d characters).\n"), 39);
791 rc = agent_scd_setattr ("DISP-NAME", isoname, strlen (isoname), NULL );
793 log_error ("error setting Name: %s\n", gpg_strerror (rc));
806 url = cpr_get ("cardedit.change_url", _("URL to retrieve public key: "));
812 rc = agent_scd_setattr ("PUBKEY-URL", url, strlen (url), NULL );
814 log_error ("error setting URL: %s\n", gpg_strerror (rc));
816 write_sc_op_status (rc);
821 /* Fetch the key from the URL given on the card or try to get it from
822 the default keyserver. */
824 fetch_url (ctrl_t ctrl)
827 struct agent_card_info_s info;
829 memset(&info,0,sizeof(info));
831 rc=agent_scd_getattr("PUBKEY-URL",&info);
833 log_error("error retrieving URL from card: %s\n",gpg_strerror(rc));
836 rc=agent_scd_getattr("KEY-FPR",&info);
838 log_error("error retrieving key fingerprint from card: %s\n",
840 else if (info.pubkey_url && *info.pubkey_url)
844 add_to_strlist (&sl, info.pubkey_url);
845 rc = keyserver_fetch (ctrl, sl, KEYORG_URL);
848 else if (info.fpr1valid)
850 rc = keyserver_import_fprint (ctrl, info.fpr1, 20, opt.keyserver, 0);
858 #define MAX_GET_DATA_FROM_FILE 16384
860 /* Read data from file FNAME up to MAX_GET_DATA_FROM_FILE characters.
861 On error return -1 and store NULL at R_BUFFER; on success return
862 the number of bytes read and store the address of a newly allocated
863 buffer at R_BUFFER. */
865 get_data_from_file (const char *fname, char **r_buffer)
873 fp = es_fopen (fname, "rb");
874 #if GNUPG_MAJOR_VERSION == 1
875 if (fp && is_secured_file (fileno (fp)))
884 tty_printf (_("can't open '%s': %s\n"), fname, strerror (errno));
888 data = xtrymalloc (MAX_GET_DATA_FROM_FILE);
891 tty_printf (_("error allocating enough memory: %s\n"), strerror (errno));
896 n = es_fread (data, 1, MAX_GET_DATA_FROM_FILE, fp);
900 tty_printf (_("error reading '%s': %s\n"), fname, strerror (errno));
909 /* Write LENGTH bytes from BUFFER to file FNAME. Return 0 on
912 put_data_to_file (const char *fname, const void *buffer, size_t length)
916 fp = es_fopen (fname, "wb");
917 #if GNUPG_MAJOR_VERSION == 1
918 if (fp && is_secured_file (fileno (fp)))
927 tty_printf (_("can't create '%s': %s\n"), fname, strerror (errno));
931 if (length && es_fwrite (buffer, length, 1, fp) != 1)
933 tty_printf (_("error writing '%s': %s\n"), fname, strerror (errno));
943 change_login (const char *args)
949 if (args && *args == '<') /* Read it from a file */
951 for (args++; spacep (args); args++)
953 n = get_data_from_file (args, &data);
959 data = cpr_get ("cardedit.change_login",
960 _("Login data (account name): "));
968 rc = agent_scd_setattr ("LOGIN-DATA", data, n, NULL );
970 log_error ("error setting login data: %s\n", gpg_strerror (rc));
972 write_sc_op_status (rc);
977 change_private_do (const char *args, int nr)
979 char do_name[] = "PRIVATE-DO-X";
984 log_assert (nr >= 1 && nr <= 4);
985 do_name[11] = '0' + nr;
987 if (args && (args = strchr (args, '<'))) /* Read it from a file */
989 for (args++; spacep (args); args++)
991 n = get_data_from_file (args, &data);
997 data = cpr_get ("cardedit.change_private_do",
998 _("Private DO data: "));
1006 rc = agent_scd_setattr (do_name, data, n, NULL );
1008 log_error ("error setting private DO: %s\n", gpg_strerror (rc));
1010 write_sc_op_status (rc);
1016 change_cert (const char *args)
1022 if (args && *args == '<') /* Read it from a file */
1024 for (args++; spacep (args); args++)
1026 n = get_data_from_file (args, &data);
1032 tty_printf ("usage error: redirection to file required\n");
1036 rc = agent_scd_writecert ("OPENPGP.3", data, n);
1038 log_error ("error writing certificate to card: %s\n", gpg_strerror (rc));
1040 write_sc_op_status (rc);
1046 read_cert (const char *args)
1053 if (args && *args == '>') /* Write it to a file */
1055 for (args++; spacep (args); args++)
1061 tty_printf ("usage error: redirection to file required\n");
1065 rc = agent_scd_readcert ("OPENPGP.3", &buffer, &length);
1067 log_error ("error reading certificate from card: %s\n", gpg_strerror (rc));
1069 rc = put_data_to_file (fname, buffer, length);
1071 write_sc_op_status (rc);
1082 data = cpr_get ("cardedit.change_lang",
1083 _("Language preferences: "));
1089 if (strlen (data) > 8 || (strlen (data) & 1))
1091 tty_printf (_("Error: invalid length of preference string.\n"));
1096 for (p=data; *p && *p >= 'a' && *p <= 'z'; p++)
1100 tty_printf (_("Error: invalid characters in preference string.\n"));
1105 rc = agent_scd_setattr ("DISP-LANG", data, strlen (data), NULL );
1107 log_error ("error setting lang: %s\n", gpg_strerror (rc));
1109 write_sc_op_status (rc);
1121 data = cpr_get ("cardedit.change_sex",
1122 _("Salutation (M = Mr., F = Mrs., or space): "));
1130 else if ((*data == 'M' || *data == 'm') && !data[1])
1132 else if ((*data == 'F' || *data == 'f') && !data[1])
1136 tty_printf (_("Error: invalid response.\n"));
1141 rc = agent_scd_setattr ("DISP-SEX", str, 1, NULL );
1143 log_error ("error setting salutation: %s\n", gpg_strerror (rc));
1145 write_sc_op_status (rc);
1151 change_cafpr (int fprno)
1156 unsigned char fpr[MAX_FINGERPRINT_LEN];
1159 data = cpr_get ("cardedit.change_cafpr", _("CA fingerprint: "));
1165 for (i=0, s=data; i < MAX_FINGERPRINT_LEN && *s; )
1181 if ((fprlen != 20 && fprlen != 32) || *s)
1183 tty_printf (_("Error: invalid formatted fingerprint.\n"));
1187 rc = agent_scd_setattr (fprno==1?"CA-FPR-1":
1188 fprno==2?"CA-FPR-2":
1189 fprno==3?"CA-FPR-3":"x", fpr, fprlen, NULL );
1191 log_error ("error setting cafpr: %s\n", gpg_strerror (rc));
1192 write_sc_op_status (rc);
1199 toggle_forcesig (void)
1201 struct agent_card_info_s info;
1205 memset (&info, 0, sizeof info);
1206 rc = agent_scd_getattr ("CHV-STATUS", &info);
1209 log_error ("error getting current status: %s\n", gpg_strerror (rc));
1212 newstate = !info.chv1_cached;
1213 agent_release_card_info (&info);
1215 rc = agent_scd_setattr ("CHV-STATUS-1", newstate? "\x01":"", 1, NULL);
1217 log_error ("error toggling signature PIN flag: %s\n", gpg_strerror (rc));
1218 write_sc_op_status (rc);
1222 /* Helper for the key generation/edit functions. */
1224 get_info_for_key_operation (struct agent_card_info_s *info)
1228 memset (info, 0, sizeof *info);
1229 rc = agent_scd_getattr ("SERIALNO", info);
1230 if (rc || !info->serialno || strncmp (info->serialno, "D27600012401", 12)
1231 || strlen (info->serialno) != 32 )
1233 log_error (_("key operation not possible: %s\n"),
1234 rc ? gpg_strerror (rc) : _("not an OpenPGP card"));
1237 rc = agent_scd_getattr ("KEY-FPR", info);
1239 rc = agent_scd_getattr ("CHV-STATUS", info);
1241 rc = agent_scd_getattr ("DISP-NAME", info);
1243 rc = agent_scd_getattr ("EXTCAP", info);
1245 rc = agent_scd_getattr ("KEY-ATTR", info);
1247 log_error (_("error getting current key info: %s\n"), gpg_strerror (rc));
1252 /* Helper for the key generation/edit functions. */
1254 check_pin_for_key_operation (struct agent_card_info_s *info, int *forced_chv1)
1258 agent_clear_pin_cache (info->serialno);
1260 *forced_chv1 = !info->chv1_cached;
1262 { /* Switch off the forced mode so that during key generation we
1263 don't get bothered with PIN queries for each
1265 rc = agent_scd_setattr ("CHV-STATUS-1", "\x01", 1, info->serialno);
1268 log_error ("error clearing forced signature PIN flag: %s\n",
1276 /* Check the PIN now, so that we won't get asked later for each
1277 binding signature. */
1278 rc = agent_scd_checkpin (info->serialno);
1281 log_error ("error checking the PIN: %s\n", gpg_strerror (rc));
1282 write_sc_op_status (rc);
1288 /* Helper for the key generation/edit functions. */
1290 restore_forced_chv1 (int *forced_chv1)
1295 { /* Switch back to forced state. */
1296 rc = agent_scd_setattr ("CHV-STATUS-1", "", 1, NULL);
1299 log_error ("error setting forced signature PIN flag: %s\n",
1306 /* Helper for the key generation/edit functions. */
1308 show_card_key_info (struct agent_card_info_s *info)
1310 tty_fprintf (NULL, "Signature key ....:");
1311 print_sha1_fpr (NULL, info->fpr1valid? info->fpr1:NULL);
1312 tty_fprintf (NULL, "Encryption key....:");
1313 print_sha1_fpr (NULL, info->fpr2valid? info->fpr2:NULL);
1314 tty_fprintf (NULL, "Authentication key:");
1315 print_sha1_fpr (NULL, info->fpr3valid? info->fpr3:NULL);
1320 /* Helper for the key generation/edit functions. */
1322 replace_existing_key_p (struct agent_card_info_s *info, int keyno)
1324 log_assert (keyno >= 0 && keyno <= 3);
1326 if ((keyno == 1 && info->fpr1valid)
1327 || (keyno == 2 && info->fpr2valid)
1328 || (keyno == 3 && info->fpr3valid))
1331 log_info ("WARNING: such a key has already been stored on the card!\n");
1333 if ( !cpr_get_answer_is_yes( "cardedit.genkeys.replace_key",
1334 _("Replace existing key? (y/N) ")))
1343 show_keysize_warning (void)
1351 (_("Note: There is no guarantee that the card supports the requested\n"
1352 " key type or size. If the key generation does not succeed,\n"
1353 " please check the documentation of your card to see which\n"
1354 " key types and sizes are supported.\n")
1359 /* Ask for the size of a card key. NBITS is the current size
1360 configured for the card. Returns 0 to use the default size
1361 (i.e. NBITS) or the selected size. */
1363 ask_card_rsa_keysize (unsigned int nbits)
1365 unsigned int min_nbits = 1024;
1366 unsigned int max_nbits = 4096;
1367 char *prompt, *answer;
1368 unsigned int req_nbits;
1372 prompt = xasprintf (_("What keysize do you want? (%u) "), nbits);
1373 answer = cpr_get ("cardedit.genkeys.size", prompt);
1375 req_nbits = *answer? atoi (answer): nbits;
1379 if (req_nbits != nbits && (req_nbits % 32) )
1381 req_nbits = ((req_nbits + 31) / 32) * 32;
1382 tty_printf (_("rounded up to %u bits\n"), req_nbits);
1385 if (req_nbits == nbits)
1386 return 0; /* Use default. */
1388 if (req_nbits < min_nbits || req_nbits > max_nbits)
1390 tty_printf (_("%s keysizes must be in the range %u-%u\n"),
1391 "RSA", min_nbits, max_nbits);
1398 /* Ask for the key attribute of a card key. CURRENT is the current
1399 attribute configured for the card. KEYNO is the number of the key
1400 used to select the prompt. Returns NULL to use the default
1401 attribute or the selected attribute structure. */
1402 static struct key_attr *
1403 ask_card_keyattr (int keyno, const struct key_attr *current)
1405 struct key_attr *key_attr = NULL;
1406 char *answer = NULL;
1409 tty_printf (_("Changing card key attribute for: "));
1411 tty_printf (_("Signature key\n"));
1412 else if (keyno == 1)
1413 tty_printf (_("Encryption key\n"));
1415 tty_printf (_("Authentication key\n"));
1417 tty_printf (_("Please select what kind of key you want:\n"));
1418 tty_printf (_(" (%d) RSA\n"), 1 );
1419 tty_printf (_(" (%d) ECC\n"), 2 );
1424 answer = cpr_get ("cardedit.genkeys.algo", _("Your selection? "));
1426 algo = *answer? atoi (answer) : 0;
1428 if (!*answer || algo == 1 || algo == 2)
1431 tty_printf (_("Invalid selection.\n"));
1437 key_attr = xmalloc (sizeof (struct key_attr));
1441 unsigned int nbits, result_nbits;
1443 if (current->algo == PUBKEY_ALGO_RSA)
1444 nbits = current->nbits;
1448 result_nbits = ask_card_rsa_keysize (nbits);
1449 if (result_nbits == 0)
1451 if (current->algo == PUBKEY_ALGO_RSA)
1457 result_nbits = nbits;
1462 key_attr->algo = PUBKEY_ALGO_RSA;
1463 key_attr->nbits = result_nbits;
1469 const char *oid_str;
1471 if (current->algo == PUBKEY_ALGO_RSA)
1474 /* Encryption key */
1475 algo = PUBKEY_ALGO_ECDH;
1476 else /* Signature key or Authentication key */
1477 algo = PUBKEY_ALGO_ECDSA;
1482 algo = current->algo;
1483 curve = current->curve;
1486 curve = ask_curve (&algo, NULL, curve);
1489 key_attr->algo = algo;
1490 oid_str = openpgp_curve_to_oid (curve, NULL);
1491 key_attr->curve = openpgp_oid_to_curve (oid_str, 0);
1503 if (key_attr->algo == PUBKEY_ALGO_RSA)
1504 tty_printf (_("The card will now be re-configured"
1505 " to generate a key of %u bits\n"), key_attr->nbits);
1506 else if (key_attr->algo == PUBKEY_ALGO_ECDH
1507 || key_attr->algo == PUBKEY_ALGO_ECDSA
1508 || key_attr->algo == PUBKEY_ALGO_EDDSA)
1509 tty_printf (_("The card will now be re-configured"
1510 " to generate a key of type: %s\n"), key_attr->curve),
1512 show_keysize_warning ();
1520 /* Change the key attribute of key KEYNO (0..2) and show an error
1521 * message if that fails. */
1523 do_change_keyattr (int keyno, const struct key_attr *key_attr)
1525 gpg_error_t err = 0;
1528 if (key_attr->algo == PUBKEY_ALGO_RSA)
1529 snprintf (args, sizeof args, "--force %d 1 rsa%u", keyno+1,
1531 else if (key_attr->algo == PUBKEY_ALGO_ECDH
1532 || key_attr->algo == PUBKEY_ALGO_ECDSA
1533 || key_attr->algo == PUBKEY_ALGO_EDDSA)
1534 snprintf (args, sizeof args, "--force %d %d %s",
1535 keyno+1, key_attr->algo, key_attr->curve);
1538 log_error (_("public key algorithm %d (%s) is not supported\n"),
1539 key_attr->algo, gcry_pk_algo_name (key_attr->algo));
1540 return gpg_error (GPG_ERR_PUBKEY_ALGO);
1543 err = agent_scd_setattr ("KEY-ATTR", args, strlen (args), NULL);
1545 log_error (_("error changing key attribute for key %d: %s\n"),
1546 keyno+1, gpg_strerror (err));
1554 struct agent_card_info_s info;
1558 err = get_info_for_key_operation (&info);
1561 log_error (_("error getting card info: %s\n"), gpg_strerror (err));
1565 if (!(info.is_v2 && info.extcap.aac))
1567 log_error (_("This command is not supported by this card\n"));
1571 for (keyno = 0; keyno < DIM (info.key_attr); keyno++)
1573 struct key_attr *key_attr;
1575 if ((key_attr = ask_card_keyattr (keyno, &info.key_attr[keyno])))
1577 err = do_change_keyattr (keyno, key_attr);
1581 /* Error: Better read the default key attribute again. */
1582 agent_release_card_info (&info);
1583 if (get_info_for_key_operation (&info))
1585 /* Ask again for this key. */
1592 agent_release_card_info (&info);
1597 generate_card_keys (ctrl_t ctrl)
1599 struct agent_card_info_s info;
1603 if (get_info_for_key_operation (&info))
1610 /* FIXME: Should be something like cpr_get_bool so that a status
1611 GET_BOOL will be emitted. */
1612 answer = cpr_get ("cardedit.genkeys.backup_enc",
1613 _("Make off-card backup of encryption key? (Y/n) "));
1615 want_backup = answer_is_yes_no_default (answer, 1/*(default to Yes)*/);
1622 if ( (info.fpr1valid && !fpr_is_zero (info.fpr1))
1623 || (info.fpr2valid && !fpr_is_zero (info.fpr2))
1624 || (info.fpr3valid && !fpr_is_zero (info.fpr3)))
1627 log_info (_("Note: keys are already stored on the card!\n"));
1629 if ( !cpr_get_answer_is_yes ("cardedit.genkeys.replace_keys",
1630 _("Replace existing keys? (y/N) ")))
1632 agent_release_card_info (&info);
1637 /* If no displayed name has been set, we assume that this is a fresh
1638 card and print a hint about the default PINs. */
1639 if (!info.disp_name || !*info.disp_name)
1642 tty_printf (_("Please note that the factory settings of the PINs are\n"
1643 " PIN = '%s' Admin PIN = '%s'\n"
1644 "You should change them using the command --change-pin\n"),
1645 "123456", "12345678");
1650 if (check_pin_for_key_operation (&info, &forced_chv1))
1653 generate_keypair (ctrl, 1, NULL, info.serialno, want_backup);
1656 agent_release_card_info (&info);
1657 restore_forced_chv1 (&forced_chv1);
1661 /* This function is used by the key edit menu to generate an arbitrary
1664 card_generate_subkey (ctrl_t ctrl, kbnode_t pub_keyblock)
1667 struct agent_card_info_s info;
1668 int forced_chv1 = 0;
1671 err = get_info_for_key_operation (&info);
1675 show_card_key_info (&info);
1677 tty_printf (_("Please select the type of key to generate:\n"));
1679 tty_printf (_(" (1) Signature key\n"));
1680 tty_printf (_(" (2) Encryption key\n"));
1681 tty_printf (_(" (3) Authentication key\n"));
1685 char *answer = cpr_get ("cardedit.genkeys.subkeytype",
1686 _("Your selection? "));
1688 if (*answer == CONTROL_D)
1691 err = gpg_error (GPG_ERR_CANCELED);
1694 keyno = *answer? atoi(answer): 0;
1696 if (keyno >= 1 && keyno <= 3)
1698 tty_printf(_("Invalid selection.\n"));
1701 if (replace_existing_key_p (&info, keyno) < 0)
1703 err = gpg_error (GPG_ERR_CANCELED);
1707 err = check_pin_for_key_operation (&info, &forced_chv1);
1711 err = generate_card_subkeypair (ctrl, pub_keyblock, keyno, info.serialno);
1714 agent_release_card_info (&info);
1715 restore_forced_chv1 (&forced_chv1);
1720 /* Store the key at NODE into the smartcard and modify NODE to
1721 carry the serialno stuff instead of the actual secret key
1722 parameters. USE is the usage for that key; 0 means any
1725 card_store_subkey (KBNODE node, int use)
1727 struct agent_card_info_s info;
1736 gnupg_isotime_t timebuf;
1738 log_assert (node->pkt->pkttype == PKT_PUBLIC_KEY
1739 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
1741 pk = node->pkt->pkt.public_key;
1743 if (get_info_for_key_operation (&info))
1746 if (!info.extcap.ki)
1748 tty_printf ("The card does not support the import of keys\n");
1753 nbits = nbits_from_pk (pk);
1755 if (!info.is_v2 && nbits != 1024)
1757 tty_printf ("You may only store a 1024 bit RSA key on the card\n");
1762 allow_keyno[0] = (!use || (use & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_CERT)));
1763 allow_keyno[1] = (!use || (use & (PUBKEY_USAGE_ENC)));
1764 allow_keyno[2] = (!use || (use & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_AUTH)));
1766 tty_printf (_("Please select where to store the key:\n"));
1769 tty_printf (_(" (1) Signature key\n"));
1771 tty_printf (_(" (2) Encryption key\n"));
1773 tty_printf (_(" (3) Authentication key\n"));
1777 char *answer = cpr_get ("cardedit.genkeys.storekeytype",
1778 _("Your selection? "));
1780 if (*answer == CONTROL_D || !*answer)
1785 keyno = *answer? atoi(answer): 0;
1787 if (keyno >= 1 && keyno <= 3 && allow_keyno[keyno-1])
1789 if (info.is_v2 && !info.extcap.aac
1790 && info.key_attr[keyno-1].nbits != nbits)
1792 tty_printf ("Key does not match the card's capability.\n");
1798 tty_printf(_("Invalid selection.\n"));
1801 if ((rc = replace_existing_key_p (&info, keyno)) < 0)
1804 err = hexkeygrip_from_pk (pk, &hexgrip);
1808 epoch2isotime (timebuf, (time_t)pk->timestamp);
1809 rc = agent_keytocard (hexgrip, keyno, rc, info.serialno, timebuf);
1812 log_error (_("KEYTOCARD failed: %s\n"), gpg_strerror (rc));
1818 agent_release_card_info (&info);
1824 /* Direct sending of an hex encoded APDU with error printing. */
1826 send_apdu (const char *hexapdu, const char *desc, unsigned int ignore)
1831 err = agent_scd_apdu (hexapdu, &sw);
1833 tty_printf ("sending card command %s failed: %s\n", desc,
1834 gpg_strerror (err));
1835 else if (!hexapdu || !strcmp (hexapdu, "undefined"))
1837 else if (ignore == 0xffff)
1838 ; /* Ignore all status words. */
1839 else if (sw != 0x9000)
1843 case 0x6285: err = gpg_error (GPG_ERR_OBJ_TERM_STATE); break;
1844 case 0x6982: err = gpg_error (GPG_ERR_BAD_PIN); break;
1845 case 0x6985: err = gpg_error (GPG_ERR_USE_CONDITIONS); break;
1846 default: err = gpg_error (GPG_ERR_CARD);
1848 if (!(ignore && ignore == sw))
1849 tty_printf ("card command %s failed: %s (0x%04x)\n", desc,
1850 gpg_strerror (err), sw);
1856 /* Do a factory reset after confirmation. */
1858 factory_reset (void)
1860 struct agent_card_info_s info;
1862 char *answer = NULL;
1866 /* The code below basically does the same what this
1867 gpg-connect-agent script does:
1870 scd serialno undefined
1871 scd apdu 00 A4 04 00 06 D2 76 00 01 24 01
1872 scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40
1873 scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40
1874 scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40
1875 scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40
1876 scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40
1877 scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40
1878 scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40
1879 scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40
1880 scd apdu 00 e6 00 00
1881 scd apdu 00 44 00 00
1883 /echo Card has been reset to factory defaults
1885 but tries to find out something about the card first.
1888 err = agent_scd_learn (&info, 0);
1889 if (gpg_err_code (err) == GPG_ERR_OBJ_TERM_STATE
1890 && gpg_err_source (err) == GPG_ERR_SOURCE_SCD)
1894 log_error (_("OpenPGP card not available: %s\n"), gpg_strerror (err));
1900 log_info (_("OpenPGP card no. %s detected\n"),
1901 info.serialno? info.serialno : "[none]");
1902 if (!(info.status_indicator == 3 || info.status_indicator == 5))
1904 /* Note: We won't see status-indicator 3 here because it is not
1905 possible to select a card application in termination state. */
1906 log_error (_("This command is not supported by this card\n"));
1911 log_info (_("Note: This command destroys all keys stored on the card!\n"));
1913 if (!cpr_get_answer_is_yes ("cardedit.factory-reset.proceed",
1914 _("Continue? (y/N) ")))
1918 answer = cpr_get ("cardedit.factory-reset.really",
1919 _("Really do a factory reset? (enter \"yes\") "));
1921 trim_spaces (answer);
1922 if (strcmp (answer, "yes"))
1925 /* We need to select a card application before we can send APDUs
1926 to the card without scdaemon doing anything on its own. */
1927 err = send_apdu (NULL, "RESET", 0);
1930 err = send_apdu ("undefined", "dummy select ", 0);
1934 /* Select the OpenPGP application. */
1935 err = send_apdu ("00A4040006D27600012401", "SELECT AID", 0);
1939 /* Do some dummy verifies with wrong PINs to set the retry
1940 counter to zero. We can't easily use the card version 2.1
1941 feature of presenting the admin PIN to allow the terminate
1942 command because there is no machinery in scdaemon to catch
1943 the verify command and ask for the PIN when the "APDU"
1945 /* Here, the length of dummy wrong PIN is 32-byte, also
1946 supporting authentication with KDF DO. */
1947 for (i=0; i < 4; i++)
1948 send_apdu ("0020008120"
1949 "40404040404040404040404040404040"
1950 "40404040404040404040404040404040", "VERIFY", 0xffff);
1951 for (i=0; i < 4; i++)
1952 send_apdu ("0020008320"
1953 "40404040404040404040404040404040"
1954 "40404040404040404040404040404040", "VERIFY", 0xffff);
1956 /* Send terminate datafile command. */
1957 err = send_apdu ("00e60000", "TERMINATE DF", 0x6985);
1962 /* Send activate datafile command. This is used without
1963 confirmation if the card is already in termination state. */
1964 err = send_apdu ("00440000", "ACTIVATE DF", 0);
1968 /* Finally we reset the card reader once more. */
1969 err = send_apdu (NULL, "RESET", 0);
1971 /* Then, connect the card again. */
1976 err = agent_scd_serialno (&serialno0, NULL);
1983 agent_release_card_info (&info);
1987 #define USER_PIN_DEFAULT "123456"
1988 #define ADMIN_PIN_DEFAULT "12345678"
1989 #define KDF_DATA_LENGTH_MIN 90
1990 #define KDF_DATA_LENGTH_MAX 110
1992 /* Generate KDF data. */
1994 gen_kdf_data (unsigned char *data, int single_salt)
1996 const unsigned char h0[] = { 0x81, 0x01, 0x03,
1999 const unsigned char h1[] = { 0x84, 0x08 };
2000 const unsigned char h2[] = { 0x85, 0x08 };
2001 const unsigned char h3[] = { 0x86, 0x08 };
2002 const unsigned char h4[] = { 0x87, 0x20 };
2003 const unsigned char h5[] = { 0x88, 0x20 };
2004 unsigned char *p, *salt_user, *salt_admin;
2005 unsigned char s2k_char;
2006 unsigned int iterations;
2007 unsigned char count_4byte[4];
2008 gpg_error_t err = 0;
2012 s2k_char = encode_s2k_iterations (0);
2013 iterations = S2K_DECODE_COUNT (s2k_char);
2014 count_4byte[0] = (iterations >> 24) & 0xff;
2015 count_4byte[1] = (iterations >> 16) & 0xff;
2016 count_4byte[2] = (iterations >> 8) & 0xff;
2017 count_4byte[3] = (iterations & 0xff);
2019 memcpy (p, h0, sizeof h0);
2021 memcpy (p, count_4byte, sizeof count_4byte);
2022 p += sizeof count_4byte;
2023 memcpy (p, h1, sizeof h1);
2024 salt_user = (p += sizeof h1);
2025 gcry_randomize (p, 8, GCRY_STRONG_RANDOM);
2029 salt_admin = salt_user;
2032 memcpy (p, h2, sizeof h2);
2034 gcry_randomize (p, 8, GCRY_STRONG_RANDOM);
2036 memcpy (p, h3, sizeof h3);
2037 salt_admin = (p += sizeof h3);
2038 gcry_randomize (p, 8, GCRY_STRONG_RANDOM);
2042 memcpy (p, h4, sizeof h4);
2044 err = gcry_kdf_derive (USER_PIN_DEFAULT, strlen (USER_PIN_DEFAULT),
2045 GCRY_KDF_ITERSALTED_S2K, DIGEST_ALGO_SHA256,
2046 salt_user, 8, iterations, 32, p);
2050 memcpy (p, h5, sizeof h5);
2052 err = gcry_kdf_derive (ADMIN_PIN_DEFAULT, strlen (ADMIN_PIN_DEFAULT),
2053 GCRY_KDF_ITERSALTED_S2K, DIGEST_ALGO_SHA256,
2054 salt_admin, 8, iterations, 32, p);
2060 /* Setup KDF data object which is used for PIN authentication. */
2062 kdf_setup (const char *args)
2064 struct agent_card_info_s info;
2066 unsigned char kdf_data[KDF_DATA_LENGTH_MAX];
2067 int single = (*args != 0);
2069 memset (&info, 0, sizeof info);
2071 err = agent_scd_getattr ("EXTCAP", &info);
2074 log_error (_("error getting card info: %s\n"), gpg_strerror (err));
2078 if (!info.extcap.kdf)
2080 log_error (_("This command is not supported by this card\n"));
2084 err = gen_kdf_data (kdf_data, single);
2088 err = agent_scd_setattr ("KDF", kdf_data,
2089 single ? KDF_DATA_LENGTH_MIN : KDF_DATA_LENGTH_MAX,
2094 err = agent_scd_getattr ("KDF", &info);
2098 log_error (_("error for setup KDF: %s\n"), gpg_strerror (err));
2101 agent_release_card_info (&info);
2104 /* Data used by the command parser. This needs to be outside of the
2105 function scope to allow readline based command completion. */
2109 cmdQUIT, cmdADMIN, cmdHELP, cmdLIST, cmdDEBUG, cmdVERIFY,
2110 cmdNAME, cmdURL, cmdFETCH, cmdLOGIN, cmdLANG, cmdSEX, cmdCAFPR,
2111 cmdFORCESIG, cmdGENERATE, cmdPASSWD, cmdPRIVATEDO, cmdWRITECERT,
2112 cmdREADCERT, cmdUNBLOCK, cmdFACTORYRESET, cmdKDFSETUP,
2125 { "quit" , cmdQUIT , 0, N_("quit this menu")},
2126 { "q" , cmdQUIT , 0, NULL },
2127 { "admin" , cmdADMIN , 0, N_("show admin commands")},
2128 { "help" , cmdHELP , 0, N_("show this help")},
2129 { "?" , cmdHELP , 0, NULL },
2130 { "list" , cmdLIST , 0, N_("list all available data")},
2131 { "l" , cmdLIST , 0, NULL },
2132 { "debug" , cmdDEBUG , 0, NULL },
2133 { "name" , cmdNAME , 1, N_("change card holder's name")},
2134 { "url" , cmdURL , 1, N_("change URL to retrieve key")},
2135 { "fetch" , cmdFETCH , 0, N_("fetch the key specified in the card URL")},
2136 { "login" , cmdLOGIN , 1, N_("change the login name")},
2137 { "lang" , cmdLANG , 1, N_("change the language preferences")},
2138 { "salutation",cmdSEX , 1, N_("change card holder's salutation")},
2139 { "sex" ,cmdSEX , 1, NULL }, /* Backward compatibility. */
2140 { "cafpr" , cmdCAFPR , 1, N_("change a CA fingerprint")},
2141 { "forcesig", cmdFORCESIG, 1, N_("toggle the signature force PIN flag")},
2142 { "generate", cmdGENERATE, 1, N_("generate new keys")},
2143 { "passwd" , cmdPASSWD, 0, N_("menu to change or unblock the PIN")},
2144 { "verify" , cmdVERIFY, 0, N_("verify the PIN and list all data")},
2145 { "unblock" , cmdUNBLOCK,0, N_("unblock the PIN using a Reset Code") },
2146 { "factory-reset", cmdFACTORYRESET, 1, N_("destroy all keys and data")},
2147 { "kdf-setup", cmdKDFSETUP, 1, N_("setup KDF for PIN authentication")},
2148 { "key-attr", cmdKEYATTR, 1, N_("change the key attribute")},
2149 /* Note, that we do not announce these command yet. */
2150 { "privatedo", cmdPRIVATEDO, 0, NULL },
2151 { "readcert", cmdREADCERT, 0, NULL },
2152 { "writecert", cmdWRITECERT, 1, NULL },
2153 { NULL, cmdINVCMD, 0, NULL }
2157 #ifdef HAVE_LIBREADLINE
2159 /* These two functions are used by readline for command completion. */
2162 command_generator(const char *text,int state)
2164 static int list_index,len;
2167 /* If this is a new word to complete, initialize now. This includes
2168 saving the length of TEXT for efficiency, and initializing the
2169 index variable to 0. */
2176 /* Return the next partial match */
2177 while((name=cmds[list_index].name))
2179 /* Only complete commands that have help text */
2180 if(cmds[list_index++].desc && strncmp(name,text,len)==0)
2181 return strdup(name);
2188 card_edit_completion(const char *text, int start, int end)
2191 /* If we are at the start of a line, we try and command-complete.
2192 If not, just do nothing for now. */
2195 return rl_completion_matches(text,command_generator);
2197 rl_attempted_completion_over=1;
2201 #endif /*HAVE_LIBREADLINE*/
2203 /* Menu to edit all user changeable values on an OpenPGP card. Only
2204 Key creation is not handled here. */
2206 card_edit (ctrl_t ctrl, strlist_t commands)
2208 enum cmdids cmd = cmdNOP;
2209 int have_commands = !!commands;
2211 char *answer = NULL;
2213 char serialnobuf[50];
2216 if (opt.command_fd != -1)
2218 else if (opt.batch && !have_commands)
2220 log_error(_("can't do this in batch mode\n"));
2227 const char *arg_string = "";
2228 const char *arg_rest = "";
2236 if (opt.with_colons)
2238 current_card_status (ctrl, es_stdout,
2239 serialnobuf, DIM (serialnobuf));
2244 current_card_status (ctrl, NULL,
2245 serialnobuf, DIM (serialnobuf));
2258 answer = xstrdup (commands->d);
2259 commands = commands->next;
2263 answer = xstrdup ("quit");
2271 tty_enable_completion (card_edit_completion);
2272 answer = cpr_get_no_help("cardedit.prompt", _("gpg/card> "));
2274 tty_disable_completion ();
2276 trim_spaces(answer);
2278 while ( *answer == '#' );
2280 arg_number = 0; /* Yes, here is the init which egcc complains about */
2283 cmd = cmdLIST; /* Default to the list command */
2284 else if (*answer == CONTROL_D)
2288 if ((p=strchr (answer,' ')))
2291 trim_spaces (answer);
2293 arg_number = atoi(p);
2296 while (digitp (arg_rest))
2298 while (spacep (arg_rest))
2302 for (i=0; cmds[i].name; i++ )
2303 if (!ascii_strcasecmp (answer, cmds[i].name ))
2307 cmd_admin_only = cmds[i].admin_only;
2310 if (!allow_admin && cmd_admin_only)
2313 tty_printf (_("Admin-only command\n"));
2320 for (i=0; cmds[i].name; i++ )
2322 && (!cmds[i].admin_only || (cmds[i].admin_only && allow_admin)))
2323 tty_printf("%-14s %s\n", cmds[i].name, _(cmds[i].desc) );
2327 if ( !strcmp (arg_string, "on") )
2329 else if ( !strcmp (arg_string, "off") )
2331 else if ( !strcmp (arg_string, "verify") )
2333 /* Force verification of the Admin Command. However,
2334 this is only done if the retry counter is at initial
2336 char *tmp = xmalloc (strlen (serialnobuf) + 6 + 1);
2337 strcpy (stpcpy (tmp, serialnobuf), "[CHV3]");
2338 allow_admin = !agent_scd_checkpin (tmp);
2342 allow_admin=!allow_admin;
2344 tty_printf(_("Admin commands are allowed\n"));
2346 tty_printf(_("Admin commands are not allowed\n"));
2350 agent_scd_checkpin (serialnobuf);
2371 change_login (arg_string);
2383 if ( arg_number < 1 || arg_number > 3 )
2384 tty_printf ("usage: cafpr N\n"
2387 change_cafpr (arg_number);
2391 if ( arg_number < 1 || arg_number > 4 )
2392 tty_printf ("usage: privatedo N\n"
2395 change_private_do (arg_string, arg_number);
2399 if ( arg_number != 3 )
2400 tty_printf ("usage: writecert 3 < FILE\n");
2402 change_cert (arg_rest);
2406 if ( arg_number != 3 )
2407 tty_printf ("usage: readcert 3 > FILE\n");
2409 read_cert (arg_rest);
2417 generate_card_keys (ctrl);
2421 change_pin (0, allow_admin);
2425 change_pin (1, allow_admin);
2428 case cmdFACTORYRESET:
2433 kdf_setup (arg_string);
2449 tty_printf (_("Invalid command (try \"help\")\n"));
2451 } /* End command switch. */
2452 } /* End of main menu loop. */