1 /* card-util.c - Utility functions for the OpenPGP card.
2 * Copyright (C) 2003, 2004, 2005, 2009 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://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*/
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 a 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_learn (&info);
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)
151 rc = agent_scd_change_pin (1, info.serialno);
152 write_sc_op_status (rc);
154 tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc));
156 tty_printf ("PIN changed.\n");
158 else if (*answer == '2')
161 rc = agent_scd_change_pin (101, info.serialno);
162 write_sc_op_status (rc);
164 tty_printf ("Error unblocking the PIN: %s\n", gpg_strerror (rc));
166 tty_printf ("PIN unblocked and new PIN set.\n");
168 else if (*answer == '3')
170 /* Change Admin PIN. */
171 rc = agent_scd_change_pin (3, info.serialno);
172 write_sc_op_status (rc);
174 tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc));
176 tty_printf ("PIN changed.\n");
178 else if (*answer == '4')
180 /* Set a new Reset Code. */
181 rc = agent_scd_change_pin (102, info.serialno);
182 write_sc_op_status (rc);
184 tty_printf ("Error setting the Reset Code: %s\n",
187 tty_printf ("Reset Code set.\n");
189 else if (*answer == 'q' || *answer == 'Q')
195 agent_release_card_info (&info);
199 get_manufacturer (unsigned int no)
201 /* Note: Make sure that there is no colon or linefeed in the string. */
204 case 0x0001: return "PPC Card Systems";
205 case 0x0002: return "Prism";
206 case 0x0003: return "OpenFortress";
207 case 0x0004: return "Wewid AB";
208 case 0x0005: return "ZeitControl";
210 case 0x002A: return "Magrathea";
212 case 0xF517: return "FSIJ";
214 /* 0x00000 and 0xFFFF are defined as test cards per spec,
215 0xFFF00 to 0xFFFE are assigned for use with randomly created
218 case 0xffff: return "test card";
219 default: return (no & 0xff00) == 0xff00? "unmanaged S/N range":"unknown";
225 print_sha1_fpr (estream_t fp, const unsigned char *fpr)
231 for (i=0; i < 20 ; i+=2, fpr += 2 )
234 tty_fprintf (fp, " ");
235 tty_fprintf (fp, " %02X%02X", *fpr, fpr[1]);
239 tty_fprintf (fp, " [none]");
240 tty_fprintf (fp, "\n");
245 print_sha1_fpr_colon (estream_t fp, const unsigned char *fpr)
251 for (i=0; i < 20 ; i++, fpr++)
252 es_fprintf (fp, "%02X", *fpr);
259 print_name (estream_t fp, const char *text, const char *name)
261 tty_fprintf (fp, "%s", text);
263 /* FIXME: tty_printf_utf8_string2 eats everything after and
264 including an @ - e.g. when printing an url. */
268 print_utf8_buffer2 (fp, name, strlen (name), '\n');
270 tty_print_utf8_string2 (name, strlen (name), 0);
273 tty_fprintf (fp, _("[not set]"));
274 tty_fprintf (fp, "\n");
278 print_isoname (estream_t fp, const char *text,
279 const char *tag, const char *name)
282 es_fprintf (fp, "%s:", tag);
284 tty_fprintf (fp, "%s", text);
288 char *p, *given, *buf = xstrdup (name);
290 given = strstr (buf, "<<");
294 if (given && given[2])
299 es_write_sanitized (fp, given, strlen (given), ":", NULL);
301 print_utf8_buffer2 (fp, given, strlen (given), '\n');
303 tty_print_utf8_string2 (given, strlen (given), 0);
308 tty_fprintf (fp, " ");
312 es_write_sanitized (fp, buf, strlen (buf), ":", NULL);
314 print_utf8_buffer2 (fp, buf, strlen (buf), '\n');
316 tty_print_utf8_string2 (buf, strlen (buf), 0);
324 tty_fprintf (fp, _("[not set]"));
328 es_fputs (":\n", fp);
330 tty_fprintf (fp, "\n");
333 /* Return true if the SHA1 fingerprint FPR consists only of zeroes. */
335 fpr_is_zero (const char *fpr)
339 for (i=0; i < 20 && !fpr[i]; i++)
345 /* Return true if the SHA1 fingerprint FPR consists only of 0xFF. */
347 fpr_is_ff (const char *fpr)
351 for (i=0; i < 20 && fpr[i] == '\xff'; i++)
357 /* Print all available information about the current card. */
359 card_status (estream_t fp, char *serialno, size_t serialnobuflen)
361 struct agent_card_info_s info;
362 PKT_public_key *pk = xcalloc (1, sizeof *pk);
365 const unsigned char *thefpr;
368 if (serialno && serialnobuflen)
371 rc = agent_learn (&info);
375 es_fputs ("AID:::\n", fp);
376 log_error (_("OpenPGP card not available: %s\n"), gpg_strerror (rc));
382 es_fprintf (fp, "AID:%s:", info.serialno? info.serialno : "");
384 tty_fprintf (fp, "Application ID ...: %s\n",
385 info.serialno? info.serialno : "[none]");
386 if (!info.serialno || strncmp (info.serialno, "D27600012401", 12)
387 || strlen (info.serialno) != 32 )
389 if (info.apptype && !strcmp (info.apptype, "NKS"))
392 es_fputs ("netkey-card:\n", fp);
393 log_info ("this is a NetKey card\n");
395 else if (info.apptype && !strcmp (info.apptype, "DINSIG"))
398 es_fputs ("dinsig-card:\n", fp);
399 log_info ("this is a DINSIG compliant card\n");
401 else if (info.apptype && !strcmp (info.apptype, "P15"))
404 es_fputs ("pkcs15-card:\n", fp);
405 log_info ("this is a PKCS#15 compliant card\n");
407 else if (info.apptype && !strcmp (info.apptype, "GELDKARTE"))
410 es_fputs ("geldkarte-card:\n", fp);
411 log_info ("this is a Geldkarte compliant card\n");
416 es_fputs ("unknown:\n", fp);
418 log_info ("not an OpenPGP card\n");
419 agent_release_card_info (&info);
426 else if (strlen (serialno)+1 > serialnobuflen)
427 log_error ("serial number longer than expected\n");
429 strcpy (serialno, info.serialno);
432 es_fputs ("openpgp-card:\n", fp);
437 es_fprintf (fp, "version:%.4s:\n", info.serialno+12);
438 uval = xtoi_2(info.serialno+16)*256 + xtoi_2 (info.serialno+18);
439 es_fprintf (fp, "vendor:%04x:%s:\n", uval, get_manufacturer (uval));
440 es_fprintf (fp, "serial:%.8s:\n", info.serialno+20);
442 print_isoname (fp, "Name of cardholder: ", "name", info.disp_name);
444 es_fputs ("lang:", fp);
446 es_write_sanitized (fp, info.disp_lang, strlen (info.disp_lang),
448 es_fputs (":\n", fp);
450 es_fprintf (fp, "sex:%c:\n", (info.disp_sex == 1? 'm':
451 info.disp_sex == 2? 'f' : 'u'));
453 es_fputs ("url:", fp);
455 es_write_sanitized (fp, info.pubkey_url, strlen (info.pubkey_url),
457 es_fputs (":\n", fp);
459 es_fputs ("login:", fp);
461 es_write_sanitized (fp, info.login_data, strlen (info.login_data),
463 es_fputs (":\n", fp);
465 es_fprintf (fp, "forcepin:%d:::\n", !info.chv1_cached);
466 for (i=0; i < DIM (info.key_attr); i++)
467 if (info.key_attr[0].algo)
468 es_fprintf (fp, "keyattr:%d:%d:%u:\n", i+1,
469 info.key_attr[i].algo, info.key_attr[i].nbits);
470 es_fprintf (fp, "maxpinlen:%d:%d:%d:\n",
471 info.chvmaxlen[0], info.chvmaxlen[1], info.chvmaxlen[2]);
472 es_fprintf (fp, "pinretry:%d:%d:%d:\n",
473 info.chvretry[0], info.chvretry[1], info.chvretry[2]);
474 es_fprintf (fp, "sigcount:%lu:::\n", info.sig_counter);
476 for (i=0; i < 4; i++)
478 if (info.private_do[i])
480 es_fprintf (fp, "private_do:%d:", i+1);
481 es_write_sanitized (fp, info.private_do[i],
482 strlen (info.private_do[i]), ":", NULL);
483 es_fputs (":\n", fp);
487 es_fputs ("cafpr:", fp);
488 print_sha1_fpr_colon (fp, info.cafpr1valid? info.cafpr1:NULL);
489 print_sha1_fpr_colon (fp, info.cafpr2valid? info.cafpr2:NULL);
490 print_sha1_fpr_colon (fp, info.cafpr3valid? info.cafpr3:NULL);
492 es_fputs ("fpr:", fp);
493 print_sha1_fpr_colon (fp, info.fpr1valid? info.fpr1:NULL);
494 print_sha1_fpr_colon (fp, info.fpr2valid? info.fpr2:NULL);
495 print_sha1_fpr_colon (fp, info.fpr3valid? info.fpr3:NULL);
497 es_fprintf (fp, "fprtime:%lu:%lu:%lu:\n",
498 (unsigned long)info.fpr1time, (unsigned long)info.fpr2time,
499 (unsigned long)info.fpr3time);
503 tty_fprintf (fp, "Version ..........: %.1s%c.%.1s%c\n",
504 info.serialno[12] == '0'?"":info.serialno+12,
506 info.serialno[14] == '0'?"":info.serialno+14,
508 tty_fprintf (fp, "Manufacturer .....: %s\n",
509 get_manufacturer (xtoi_2(info.serialno+16)*256
510 + xtoi_2 (info.serialno+18)));
511 tty_fprintf (fp, "Serial number ....: %.8s\n", info.serialno+20);
513 print_isoname (fp, "Name of cardholder: ", "name", info.disp_name);
514 print_name (fp, "Language prefs ...: ", info.disp_lang);
515 tty_fprintf (fp, "Sex ..............: %s\n",
516 info.disp_sex == 1? _("male"):
517 info.disp_sex == 2? _("female") : _("unspecified"));
518 print_name (fp, "URL of public key : ", info.pubkey_url);
519 print_name (fp, "Login data .......: ", info.login_data);
520 if (info.private_do[0])
521 print_name (fp, "Private DO 1 .....: ", info.private_do[0]);
522 if (info.private_do[1])
523 print_name (fp, "Private DO 2 .....: ", info.private_do[1]);
524 if (info.private_do[2])
525 print_name (fp, "Private DO 3 .....: ", info.private_do[2]);
526 if (info.private_do[3])
527 print_name (fp, "Private DO 4 .....: ", info.private_do[3]);
528 if (info.cafpr1valid)
530 tty_fprintf (fp, "CA fingerprint %d .:", 1);
531 print_sha1_fpr (fp, info.cafpr1);
533 if (info.cafpr2valid)
535 tty_fprintf (fp, "CA fingerprint %d .:", 2);
536 print_sha1_fpr (fp, info.cafpr2);
538 if (info.cafpr3valid)
540 tty_fprintf (fp, "CA fingerprint %d .:", 3);
541 print_sha1_fpr (fp, info.cafpr3);
543 tty_fprintf (fp, "Signature PIN ....: %s\n",
544 info.chv1_cached? _("not forced"): _("forced"));
545 if (info.key_attr[0].algo)
547 tty_fprintf (fp, "Key attributes ...:");
548 for (i=0; i < DIM (info.key_attr); i++)
549 tty_fprintf (fp, " %u%c",
550 info.key_attr[i].nbits,
551 info.key_attr[i].algo == 1? 'R':
552 info.key_attr[i].algo == 17? 'D': '?');
553 tty_fprintf (fp, "\n");
555 tty_fprintf (fp, "Max. PIN lengths .: %d %d %d\n",
556 info.chvmaxlen[0], info.chvmaxlen[1], info.chvmaxlen[2]);
557 tty_fprintf (fp, "PIN retry counter : %d %d %d\n",
558 info.chvretry[0], info.chvretry[1], info.chvretry[2]);
559 tty_fprintf (fp, "Signature counter : %lu\n", info.sig_counter);
560 tty_fprintf (fp, "Signature key ....:");
561 print_sha1_fpr (fp, info.fpr1valid? info.fpr1:NULL);
562 if (info.fpr1valid && info.fpr1time)
563 tty_fprintf (fp, " created ....: %s\n",
564 isotimestamp (info.fpr1time));
565 tty_fprintf (fp, "Encryption key....:");
566 print_sha1_fpr (fp, info.fpr2valid? info.fpr2:NULL);
567 if (info.fpr2valid && info.fpr2time)
568 tty_fprintf (fp, " created ....: %s\n",
569 isotimestamp (info.fpr2time));
570 tty_fprintf (fp, "Authentication key:");
571 print_sha1_fpr (fp, info.fpr3valid? info.fpr3:NULL);
572 if (info.fpr3valid && info.fpr3time)
573 tty_fprintf (fp, " created ....: %s\n",
574 isotimestamp (info.fpr3time));
575 tty_fprintf (fp, "General key info..: ");
577 thefpr = (info.fpr1valid? info.fpr1 : info.fpr2valid? info.fpr2 :
578 info.fpr3valid? info.fpr3 : NULL);
579 /* If the fingerprint is all 0xff, the key has no asssociated
580 OpenPGP certificate. */
581 if ( thefpr && !fpr_is_ff (thefpr)
582 && !get_pubkey_byfprint (pk, thefpr, 20))
584 kbnode_t keyblock = NULL;
586 print_pubkey_info (fp, pk);
588 #if GNUPG_MAJOR_VERSION == 1
589 if ( !get_seckeyblock_byfprint (&keyblock, thefpr, 20) )
590 print_card_key_info (fp, keyblock);
591 else if ( !get_keyblock_byfprint (&keyblock, thefpr, 20) )
593 release_kbnode (keyblock);
596 if (!auto_create_card_key_stub (info.serialno,
597 info.fpr1valid? info.fpr1:NULL,
598 info.fpr2valid? info.fpr2:NULL,
599 info.fpr3valid? info.fpr3:NULL))
601 if ( !get_seckeyblock_byfprint (&keyblock, thefpr, 20) )
602 print_card_key_info (fp, keyblock);
606 #else /* GNUPG_MAJOR_VERSION != 1 */
607 if (!get_keyblock_byfprint (&keyblock, thefpr, 20))
608 print_card_key_info (fp, keyblock);
609 #endif /* GNUPG_MAJOR_VERSION != 1 */
611 release_kbnode (keyblock);
614 tty_fprintf (fp, "[none]\n");
617 free_public_key (pk);
618 agent_release_card_info (&info);
623 get_one_name (const char *prompt1, const char *prompt2)
630 name = cpr_get (prompt1, prompt2);
635 for (i=0; name[i] && name[i] >= ' ' && name[i] <= 126; i++)
638 /* The name must be in Latin-1 and not UTF-8 - lacking the code
639 to ensure this we restrict it to ASCII. */
641 tty_printf (_("Error: Only plain ASCII is currently allowed.\n"));
642 else if (strchr (name, '<'))
643 tty_printf (_("Error: The \"<\" character may not be used.\n"));
644 else if (strstr (name, " "))
645 tty_printf (_("Error: Double spaces are not allowed.\n"));
657 char *surname = NULL, *givenname = NULL;
661 surname = get_one_name ("keygen.smartcard.surname",
662 _("Cardholder's surname: "));
663 givenname = get_one_name ("keygen.smartcard.givenname",
664 _("Cardholder's given name: "));
665 if (!surname || !givenname || (!*surname && !*givenname))
669 return -1; /*canceled*/
672 isoname = xmalloc ( strlen (surname) + 2 + strlen (givenname) + 1);
673 strcpy (stpcpy (stpcpy (isoname, surname), "<<"), givenname);
676 for (p=isoname; *p; p++)
680 if (strlen (isoname) > 39 )
682 tty_printf (_("Error: Combined name too long "
683 "(limit is %d characters).\n"), 39);
688 rc = agent_scd_setattr ("DISP-NAME", isoname, strlen (isoname), NULL );
690 log_error ("error setting Name: %s\n", gpg_strerror (rc));
703 url = cpr_get ("cardedit.change_url", _("URL to retrieve public key: "));
709 if (strlen (url) > 254 )
711 tty_printf (_("Error: URL too long "
712 "(limit is %d characters).\n"), 254);
717 rc = agent_scd_setattr ("PUBKEY-URL", url, strlen (url), NULL );
719 log_error ("error setting URL: %s\n", gpg_strerror (rc));
721 write_sc_op_status (rc);
726 /* Fetch the key from the URL given on the card or try to get it from
727 the default keyserver. */
729 fetch_url (ctrl_t ctrl)
732 struct agent_card_info_s info;
734 memset(&info,0,sizeof(info));
736 rc=agent_scd_getattr("PUBKEY-URL",&info);
738 log_error("error retrieving URL from card: %s\n",gpg_strerror(rc));
741 struct keyserver_spec *spec=NULL;
743 rc=agent_scd_getattr("KEY-FPR",&info);
745 log_error("error retrieving key fingerprint from card: %s\n",
747 else if (info.pubkey_url && *info.pubkey_url)
749 spec=parse_keyserver_uri(info.pubkey_url,1,NULL,0);
750 if(spec && info.fpr1valid)
752 /* This is not perfectly right. Currently, all card
753 fingerprints are 20 digits, but what about
754 fingerprints for a future v5 key? We should get the
755 length from somewhere lower in the code. In any
756 event, the fpr/keyid is not meaningful for straight
757 HTTP fetches, but using it allows the card to point
758 to HKP and LDAP servers as well. */
759 rc = keyserver_import_fprint (ctrl, info.fpr1, 20, spec);
760 free_keyserver_spec(spec);
763 else if (info.fpr1valid)
765 rc = keyserver_import_fprint (ctrl, info.fpr1, 20, opt.keyserver);
773 /* Read data from file FNAME up to MAXLEN characters. On error return
774 -1 and store NULL at R_BUFFER; on success return the number of
775 bytes read and store the address of a newly allocated buffer at
778 get_data_from_file (const char *fname, size_t maxlen, char **r_buffer)
786 fp = es_fopen (fname, "rb");
787 #if GNUPG_MAJOR_VERSION == 1
788 if (fp && is_secured_file (fileno (fp)))
797 tty_printf (_("can't open `%s': %s\n"), fname, strerror (errno));
801 data = xtrymalloc (maxlen? maxlen:1);
804 tty_printf (_("error allocating enough memory: %s\n"), strerror (errno));
810 n = es_fread (data, 1, maxlen, fp);
816 tty_printf (_("error reading `%s': %s\n"), fname, strerror (errno));
825 /* Write LENGTH bytes from BUFFER to file FNAME. Return 0 on
828 put_data_to_file (const char *fname, const void *buffer, size_t length)
832 fp = es_fopen (fname, "wb");
833 #if GNUPG_MAJOR_VERSION == 1
834 if (fp && is_secured_file (fileno (fp)))
843 tty_printf (_("can't create `%s': %s\n"), fname, strerror (errno));
847 if (length && es_fwrite (buffer, length, 1, fp) != 1)
849 tty_printf (_("error writing `%s': %s\n"), fname, strerror (errno));
859 change_login (const char *args)
865 if (args && *args == '<') /* Read it from a file */
867 for (args++; spacep (args); args++)
869 n = get_data_from_file (args, 254, &data);
875 data = cpr_get ("cardedit.change_login",
876 _("Login data (account name): "));
886 tty_printf (_("Error: Login data too long "
887 "(limit is %d characters).\n"), 254);
892 rc = agent_scd_setattr ("LOGIN-DATA", data, n, NULL );
894 log_error ("error setting login data: %s\n", gpg_strerror (rc));
896 write_sc_op_status (rc);
901 change_private_do (const char *args, int nr)
903 char do_name[] = "PRIVATE-DO-X";
908 assert (nr >= 1 && nr <= 4);
909 do_name[11] = '0' + nr;
911 if (args && (args = strchr (args, '<'))) /* Read it from a file */
913 for (args++; spacep (args); args++)
915 n = get_data_from_file (args, 254, &data);
921 data = cpr_get ("cardedit.change_private_do",
922 _("Private DO data: "));
932 tty_printf (_("Error: Private DO too long "
933 "(limit is %d characters).\n"), 254);
938 rc = agent_scd_setattr (do_name, data, n, NULL );
940 log_error ("error setting private DO: %s\n", gpg_strerror (rc));
942 write_sc_op_status (rc);
948 change_cert (const char *args)
954 if (args && *args == '<') /* Read it from a file */
956 for (args++; spacep (args); args++)
958 n = get_data_from_file (args, 16384, &data);
964 tty_printf ("usage error: redirection to file required\n");
968 rc = agent_scd_writecert ("OPENPGP.3", data, n);
970 log_error ("error writing certificate to card: %s\n", gpg_strerror (rc));
972 write_sc_op_status (rc);
978 read_cert (const char *args)
985 if (args && *args == '>') /* Write it to a file */
987 for (args++; spacep (args); args++)
993 tty_printf ("usage error: redirection to file required\n");
997 rc = agent_scd_readcert ("OPENPGP.3", &buffer, &length);
999 log_error ("error reading certificate from card: %s\n", gpg_strerror (rc));
1001 rc = put_data_to_file (fname, buffer, length);
1003 write_sc_op_status (rc);
1014 data = cpr_get ("cardedit.change_lang",
1015 _("Language preferences: "));
1021 if (strlen (data) > 8 || (strlen (data) & 1))
1023 tty_printf (_("Error: invalid length of preference string.\n"));
1028 for (p=data; *p && *p >= 'a' && *p <= 'z'; p++)
1032 tty_printf (_("Error: invalid characters in preference string.\n"));
1037 rc = agent_scd_setattr ("DISP-LANG", data, strlen (data), NULL );
1039 log_error ("error setting lang: %s\n", gpg_strerror (rc));
1041 write_sc_op_status (rc);
1053 data = cpr_get ("cardedit.change_sex",
1054 _("Sex ((M)ale, (F)emale or space): "));
1062 else if ((*data == 'M' || *data == 'm') && !data[1])
1064 else if ((*data == 'F' || *data == 'f') && !data[1])
1068 tty_printf (_("Error: invalid response.\n"));
1073 rc = agent_scd_setattr ("DISP-SEX", str, 1, NULL );
1075 log_error ("error setting sex: %s\n", gpg_strerror (rc));
1077 write_sc_op_status (rc);
1083 change_cafpr (int fprno)
1088 unsigned char fpr[20];
1090 data = cpr_get ("cardedit.change_cafpr", _("CA fingerprint: "));
1096 for (i=0, s=data; i < 20 && *s; )
1113 tty_printf (_("Error: invalid formatted fingerprint.\n"));
1117 rc = agent_scd_setattr (fprno==1?"CA-FPR-1":
1118 fprno==2?"CA-FPR-2":
1119 fprno==3?"CA-FPR-3":"x", fpr, 20, NULL );
1121 log_error ("error setting cafpr: %s\n", gpg_strerror (rc));
1122 write_sc_op_status (rc);
1129 toggle_forcesig (void)
1131 struct agent_card_info_s info;
1135 memset (&info, 0, sizeof info);
1136 rc = agent_scd_getattr ("CHV-STATUS", &info);
1139 log_error ("error getting current status: %s\n", gpg_strerror (rc));
1142 newstate = !info.chv1_cached;
1143 agent_release_card_info (&info);
1145 rc = agent_scd_setattr ("CHV-STATUS-1", newstate? "\x01":"", 1, NULL);
1147 log_error ("error toggling signature PIN flag: %s\n", gpg_strerror (rc));
1148 write_sc_op_status (rc);
1152 /* Helper for the key generation/edit functions. */
1154 get_info_for_key_operation (struct agent_card_info_s *info)
1158 memset (info, 0, sizeof *info);
1159 rc = agent_scd_getattr ("SERIALNO", info);
1160 if (rc || !info->serialno || strncmp (info->serialno, "D27600012401", 12)
1161 || strlen (info->serialno) != 32 )
1163 log_error (_("key operation not possible: %s\n"),
1164 rc ? gpg_strerror (rc) : _("not an OpenPGP card"));
1167 rc = agent_scd_getattr ("KEY-FPR", info);
1169 rc = agent_scd_getattr ("CHV-STATUS", info);
1171 rc = agent_scd_getattr ("DISP-NAME", info);
1173 rc = agent_scd_getattr ("EXTCAP", info);
1175 rc = agent_scd_getattr ("KEY-ATTR", info);
1177 log_error (_("error getting current key info: %s\n"), gpg_strerror (rc));
1182 /* Helper for the key generation/edit functions. */
1184 check_pin_for_key_operation (struct agent_card_info_s *info, int *forced_chv1)
1188 agent_clear_pin_cache (info->serialno);
1190 *forced_chv1 = !info->chv1_cached;
1192 { /* Switch off the forced mode so that during key generation we
1193 don't get bothered with PIN queries for each
1195 rc = agent_scd_setattr ("CHV-STATUS-1", "\x01", 1, info->serialno);
1198 log_error ("error clearing forced signature PIN flag: %s\n",
1206 /* Check the PIN now, so that we won't get asked later for each
1207 binding signature. */
1208 rc = agent_scd_checkpin (info->serialno);
1211 log_error ("error checking the PIN: %s\n", gpg_strerror (rc));
1212 write_sc_op_status (rc);
1218 /* Helper for the key generation/edit functions. */
1220 restore_forced_chv1 (int *forced_chv1)
1225 { /* Switch back to forced state. */
1226 rc = agent_scd_setattr ("CHV-STATUS-1", "", 1, NULL);
1229 log_error ("error setting forced signature PIN flag: %s\n",
1236 /* Helper for the key generation/edit functions. */
1238 show_card_key_info (struct agent_card_info_s *info)
1240 tty_fprintf (NULL, "Signature key ....:");
1241 print_sha1_fpr (NULL, info->fpr1valid? info->fpr1:NULL);
1242 tty_fprintf (NULL, "Encryption key....:");
1243 print_sha1_fpr (NULL, info->fpr2valid? info->fpr2:NULL);
1244 tty_fprintf (NULL, "Authentication key:");
1245 print_sha1_fpr (NULL, info->fpr3valid? info->fpr3:NULL);
1250 /* Helper for the key generation/edit functions. */
1252 replace_existing_key_p (struct agent_card_info_s *info, int keyno)
1254 assert (keyno >= 0 && keyno <= 3);
1256 if ((keyno == 1 && info->fpr1valid)
1257 || (keyno == 2 && info->fpr2valid)
1258 || (keyno == 3 && info->fpr3valid))
1261 log_info ("WARNING: such a key has already been stored on the card!\n");
1263 if ( !cpr_get_answer_is_yes( "cardedit.genkeys.replace_key",
1264 _("Replace existing key? (y/N) ")))
1272 show_keysize_warning (void)
1280 (_("NOTE: There is no guarantee that the card "
1281 "supports the requested size.\n"
1282 " If the key generation does not succeed, "
1283 "please check the\n"
1284 " documentation of your card to see what "
1285 "sizes are allowed.\n"));
1289 /* Ask for the size of a card key. NBITS is the current size
1290 configured for the card. KEYNO is the number of the key used to
1291 select the prompt. Returns 0 to use the default size (i.e. NBITS)
1292 or the selected size. */
1294 ask_card_keysize (int keyno, unsigned int nbits)
1296 unsigned int min_nbits = 1024;
1297 unsigned int max_nbits = 3072; /* GnuPG limit due to Assuan. */
1298 char *prompt, *answer;
1299 unsigned int req_nbits;
1305 _("What keysize do you want for the Signature key? (%u) "):
1307 _("What keysize do you want for the Encryption key? (%u) "):
1308 _("What keysize do you want for the Authentication key? (%u) "),
1310 answer = cpr_get ("cardedit.genkeys.size", prompt);
1312 req_nbits = *answer? atoi (answer): nbits;
1316 if (req_nbits != nbits && (req_nbits % 32) )
1318 req_nbits = ((req_nbits + 31) / 32) * 32;
1319 tty_printf (_("rounded up to %u bits\n"), req_nbits);
1322 if (req_nbits == nbits)
1323 return 0; /* Use default. */
1325 if (req_nbits < min_nbits || req_nbits > max_nbits)
1327 tty_printf (_("%s keysizes must be in the range %u-%u\n"),
1328 "RSA", min_nbits, max_nbits);
1332 tty_printf (_("The card will now be re-configured "
1333 "to generate a key of %u bits\n"), req_nbits);
1334 show_keysize_warning ();
1341 /* Change the size of key KEYNO (0..2) to NBITS and show an error
1342 message if that fails. */
1344 do_change_keysize (int keyno, unsigned int nbits)
1349 snprintf (args, sizeof args, "--force %d 1 %u", keyno+1, nbits);
1350 err = agent_scd_setattr ("KEY-ATTR", args, strlen (args), NULL);
1352 log_error (_("error changing size of key %d to %u bits: %s\n"),
1353 keyno+1, nbits, gpg_strerror (err));
1359 generate_card_keys (void)
1361 struct agent_card_info_s info;
1366 if (get_info_for_key_operation (&info))
1373 /* FIXME: Should be something like cpr_get_bool so that a status
1374 GET_BOOL will be emitted. */
1375 answer = cpr_get ("cardedit.genkeys.backup_enc",
1376 _("Make off-card backup of encryption key? (Y/n) "));
1378 want_backup = answer_is_yes_no_default (answer, 1/*(default to Yes)*/);
1385 if ( (info.fpr1valid && !fpr_is_zero (info.fpr1))
1386 || (info.fpr2valid && !fpr_is_zero (info.fpr2))
1387 || (info.fpr3valid && !fpr_is_zero (info.fpr3)))
1390 log_info (_("NOTE: keys are already stored on the card!\n"));
1392 if ( !cpr_get_answer_is_yes ("cardedit.genkeys.replace_keys",
1393 _("Replace existing keys? (y/N) ")))
1395 agent_release_card_info (&info);
1400 /* If no displayed name has been set, we assume that this is a fresh
1401 card and print a hint about the default PINs. */
1402 if (!info.disp_name || !*info.disp_name)
1405 tty_printf (_("Please note that the factory settings of the PINs are\n"
1406 " PIN = `%s' Admin PIN = `%s'\n"
1407 "You should change them using the command --change-pin\n"),
1408 "123456", "12345678");
1412 if (check_pin_for_key_operation (&info, &forced_chv1))
1415 /* If the cards features changeable key attributes, we ask for the
1417 if (info.is_v2 && info.extcap.aac)
1421 for (keyno = 0; keyno < DIM (info.key_attr); keyno++)
1423 nbits = ask_card_keysize (keyno, info.key_attr[keyno].nbits);
1424 if (nbits && do_change_keysize (keyno, nbits))
1426 /* Error: Better read the default key size again. */
1427 agent_release_card_info (&info);
1428 if (get_info_for_key_operation (&info))
1430 /* Ask again for this key size. */
1434 /* Note that INFO has not be synced. However we will only use
1435 the serialnumber and thus it won't harm. */
1438 generate_keypair (NULL, info.serialno, want_backup);
1441 agent_release_card_info (&info);
1442 restore_forced_chv1 (&forced_chv1);
1446 /* This function is used by the key edit menu to generate an arbitrary
1449 card_generate_subkey (KBNODE pub_keyblock)
1452 struct agent_card_info_s info;
1453 int forced_chv1 = 0;
1456 err = get_info_for_key_operation (&info);
1460 show_card_key_info (&info);
1462 tty_printf (_("Please select the type of key to generate:\n"));
1464 tty_printf (_(" (1) Signature key\n"));
1465 tty_printf (_(" (2) Encryption key\n"));
1466 tty_printf (_(" (3) Authentication key\n"));
1470 char *answer = cpr_get ("cardedit.genkeys.subkeytype",
1471 _("Your selection? "));
1473 if (*answer == CONTROL_D)
1476 err = gpg_error (GPG_ERR_CANCELED);
1479 keyno = *answer? atoi(answer): 0;
1481 if (keyno >= 1 && keyno <= 3)
1483 tty_printf(_("Invalid selection.\n"));
1486 if (replace_existing_key_p (&info, keyno))
1488 err = gpg_error (GPG_ERR_CANCELED);
1492 err = check_pin_for_key_operation (&info, &forced_chv1);
1496 /* If the cards features changeable key attributes, we ask for the
1498 if (info.is_v2 && info.extcap.aac)
1503 nbits = ask_card_keysize (keyno-1, info.key_attr[keyno-1].nbits);
1504 if (nbits && do_change_keysize (keyno-1, nbits))
1506 /* Error: Better read the default key size again. */
1507 agent_release_card_info (&info);
1508 err = get_info_for_key_operation (&info);
1513 /* Note that INFO has not be synced. However we will only use
1514 the serialnumber and thus it won't harm. */
1517 err = generate_card_subkeypair (pub_keyblock, keyno, info.serialno);
1520 agent_release_card_info (&info);
1521 restore_forced_chv1 (&forced_chv1);
1526 /* Store the key at NODE into the smartcard and modify NODE to
1527 carry the serialno stuff instead of the actual secret key
1528 parameters. USE is the usage for that key; 0 means any
1531 card_store_subkey (KBNODE node, int use)
1533 log_info ("FIXME: card_store_subkey has not yet been implemented\n");
1534 /* struct agent_card_info_s info; */
1538 /* PKT_secret_key *copied_sk = NULL; */
1539 /* PKT_secret_key *sk; */
1541 /* const char *s; */
1542 /* int allow_keyno[3]; */
1543 /* unsigned int nbits; */
1546 /* assert (node->pkt->pkttype == PKT_SECRET_KEY */
1547 /* || node->pkt->pkttype == PKT_SECRET_SUBKEY); */
1548 /* sk = node->pkt->pkt.secret_key; */
1550 /* if (get_info_for_key_operation (&info)) */
1553 /* if (!info.extcap.ki) */
1555 /* tty_printf ("The card does not support the import of keys\n"); */
1556 /* tty_printf ("\n"); */
1560 /* show_card_key_info (&info); */
1562 /* nbits = nbits_from_sk (sk); */
1564 /* if (!is_RSA (sk->pubkey_algo) || (!info.is_v2 && nbits != 1024) ) */
1566 /* tty_printf ("You may only store a 1024 bit RSA key on the card\n"); */
1567 /* tty_printf ("\n"); */
1571 /* allow_keyno[0] = (!use || (use & (PUBKEY_USAGE_SIG))); */
1572 /* allow_keyno[1] = (!use || (use & (PUBKEY_USAGE_ENC))); */
1573 /* allow_keyno[2] = (!use || (use & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_AUTH))); */
1575 /* tty_printf (_("Please select where to store the key:\n")); */
1577 /* if (allow_keyno[0]) */
1578 /* tty_printf (_(" (1) Signature key\n")); */
1579 /* if (allow_keyno[1]) */
1580 /* tty_printf (_(" (2) Encryption key\n")); */
1581 /* if (allow_keyno[2]) */
1582 /* tty_printf (_(" (3) Authentication key\n")); */
1586 /* char *answer = cpr_get ("cardedit.genkeys.storekeytype", */
1587 /* _("Your selection? ")); */
1588 /* cpr_kill_prompt(); */
1589 /* if (*answer == CONTROL_D || !*answer) */
1591 /* xfree (answer); */
1594 /* keyno = *answer? atoi(answer): 0; */
1595 /* xfree(answer); */
1596 /* if (keyno >= 1 && keyno <= 3 && allow_keyno[keyno-1]) */
1598 /* if (info.is_v2 && !info.extcap.aac */
1599 /* && info.key_attr[keyno-1].nbits != nbits) */
1601 /* tty_printf ("Key does not match the card's capability.\n"); */
1604 /* break; /\* Okay. *\/ */
1607 /* tty_printf(_("Invalid selection.\n")); */
1610 /* if (replace_existing_key_p (&info, keyno)) */
1613 /* /\* Unprotect key. *\/ */
1614 /* switch (is_secret_key_protected (sk) ) */
1616 /* case 0: /\* Not protected. *\/ */
1619 /* log_error (_("unknown key protection algorithm\n")); */
1622 /* if (sk->protect.s2k.mode == 1001) */
1624 /* log_error (_("secret parts of key are not available\n")); */
1627 /* if (sk->protect.s2k.mode == 1002) */
1629 /* log_error (_("secret key already stored on a card\n")); */
1632 /* /\* We better copy the key before we unprotect it. *\/ */
1633 /* copied_sk = sk = copy_secret_key (NULL, sk); */
1634 /* rc = 0/\*check_secret_key (sk, 0)*\/; */
1639 /* #warning code save_unprotected_key_to_card */
1640 /* /\* rc = save_unprotected_key_to_card (sk, keyno); *\/ */
1641 /* /\* if (rc) *\/ */
1643 /* /\* log_error (_("error writing key to card: %s\n"), gpg_strerror (rc)); *\/ */
1644 /* /\* goto leave; *\/ */
1647 /* /\* Get back to the maybe protected original secret key. *\/ */
1648 /* if (copied_sk) */
1650 /* free_secret_key (copied_sk); */
1651 /* copied_sk = NULL; */
1653 /* sk = node->pkt->pkt.secret_key; */
1655 /* /\* Get rid of the secret key parameters and store the serial numer. *\/ */
1656 /* n = pubkey_get_nskey (sk->pubkey_algo); */
1657 /* for (i=pubkey_get_npkey (sk->pubkey_algo); i < n; i++) */
1659 /* gcry_mpi_release (sk->skey[i]); */
1660 /* sk->skey[i] = NULL; */
1662 /* i = pubkey_get_npkey (sk->pubkey_algo); */
1663 /* sk->skey[i] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8); */
1664 /* sk->is_protected = 1; */
1665 /* sk->protect.s2k.mode = 1002; */
1666 /* s = info.serialno; */
1667 /* for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1]; */
1668 /* sk->protect.ivlen++, s += 2) */
1669 /* sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s); */
1674 /* if (copied_sk) */
1675 /* free_secret_key (copied_sk); */
1676 /* agent_release_card_info (&info); */
1683 /* Data used by the command parser. This needs to be outside of the
1684 function scope to allow readline based command completion. */
1688 cmdQUIT, cmdADMIN, cmdHELP, cmdLIST, cmdDEBUG, cmdVERIFY,
1689 cmdNAME, cmdURL, cmdFETCH, cmdLOGIN, cmdLANG, cmdSEX, cmdCAFPR,
1690 cmdFORCESIG, cmdGENERATE, cmdPASSWD, cmdPRIVATEDO, cmdWRITECERT,
1691 cmdREADCERT, cmdUNBLOCK,
1703 { "quit" , cmdQUIT , 0, N_("quit this menu")},
1704 { "q" , cmdQUIT , 0, NULL },
1705 { "admin" , cmdADMIN , 0, N_("show admin commands")},
1706 { "help" , cmdHELP , 0, N_("show this help")},
1707 { "?" , cmdHELP , 0, NULL },
1708 { "list" , cmdLIST , 0, N_("list all available data")},
1709 { "l" , cmdLIST , 0, NULL },
1710 { "debug" , cmdDEBUG , 0, NULL },
1711 { "name" , cmdNAME , 1, N_("change card holder's name")},
1712 { "url" , cmdURL , 1, N_("change URL to retrieve key")},
1713 { "fetch" , cmdFETCH , 0, N_("fetch the key specified in the card URL")},
1714 { "login" , cmdLOGIN , 1, N_("change the login name")},
1715 { "lang" , cmdLANG , 1, N_("change the language preferences")},
1716 { "sex" , cmdSEX , 1, N_("change card holder's sex")},
1717 { "cafpr" , cmdCAFPR , 1, N_("change a CA fingerprint")},
1718 { "forcesig", cmdFORCESIG, 1, N_("toggle the signature force PIN flag")},
1719 { "generate", cmdGENERATE, 1, N_("generate new keys")},
1720 { "passwd" , cmdPASSWD, 0, N_("menu to change or unblock the PIN")},
1721 { "verify" , cmdVERIFY, 0, N_("verify the PIN and list all data")},
1722 { "unblock" , cmdUNBLOCK,0, N_("unblock the PIN using a Reset Code") },
1723 /* Note, that we do not announce these command yet. */
1724 { "privatedo", cmdPRIVATEDO, 0, NULL },
1725 { "readcert", cmdREADCERT, 0, NULL },
1726 { "writecert", cmdWRITECERT, 1, NULL },
1727 { NULL, cmdINVCMD, 0, NULL }
1731 #ifdef HAVE_LIBREADLINE
1733 /* These two functions are used by readline for command completion. */
1736 command_generator(const char *text,int state)
1738 static int list_index,len;
1741 /* If this is a new word to complete, initialize now. This includes
1742 saving the length of TEXT for efficiency, and initializing the
1743 index variable to 0. */
1750 /* Return the next partial match */
1751 while((name=cmds[list_index].name))
1753 /* Only complete commands that have help text */
1754 if(cmds[list_index++].desc && strncmp(name,text,len)==0)
1755 return strdup(name);
1762 card_edit_completion(const char *text, int start, int end)
1765 /* If we are at the start of a line, we try and command-complete.
1766 If not, just do nothing for now. */
1769 return rl_completion_matches(text,command_generator);
1771 rl_attempted_completion_over=1;
1775 #endif /*HAVE_LIBREADLINE*/
1777 /* Menu to edit all user changeable values on an OpenPGP card. Only
1778 Key creation is not handled here. */
1780 card_edit (ctrl_t ctrl, strlist_t commands)
1782 enum cmdids cmd = cmdNOP;
1783 int have_commands = !!commands;
1785 char *answer = NULL;
1787 char serialnobuf[50];
1790 if (opt.command_fd != -1)
1792 else if (opt.batch && !have_commands)
1794 log_error(_("can't do this in batch mode\n"));
1801 const char *arg_string = "";
1802 const char *arg_rest = "";
1810 if (opt.with_colons)
1812 card_status (es_stdout, serialnobuf, DIM (serialnobuf));
1817 card_status (NULL, serialnobuf, DIM (serialnobuf));
1830 answer = xstrdup (commands->d);
1831 commands = commands->next;
1835 answer = xstrdup ("quit");
1843 tty_enable_completion (card_edit_completion);
1844 answer = cpr_get_no_help("cardedit.prompt", _("gpg/card> "));
1846 tty_disable_completion ();
1848 trim_spaces(answer);
1850 while ( *answer == '#' );
1852 arg_number = 0; /* Yes, here is the init which egcc complains about */
1855 cmd = cmdLIST; /* Default to the list command */
1856 else if (*answer == CONTROL_D)
1860 if ((p=strchr (answer,' ')))
1863 trim_spaces (answer);
1865 arg_number = atoi(p);
1868 while (digitp (arg_rest))
1870 while (spacep (arg_rest))
1874 for (i=0; cmds[i].name; i++ )
1875 if (!ascii_strcasecmp (answer, cmds[i].name ))
1879 cmd_admin_only = cmds[i].admin_only;
1882 if (!allow_admin && cmd_admin_only)
1885 tty_printf (_("Admin-only command\n"));
1892 for (i=0; cmds[i].name; i++ )
1894 && (!cmds[i].admin_only || (cmds[i].admin_only && allow_admin)))
1895 tty_printf("%-10s %s\n", cmds[i].name, _(cmds[i].desc) );
1899 if ( !strcmp (arg_string, "on") )
1901 else if ( !strcmp (arg_string, "off") )
1903 else if ( !strcmp (arg_string, "verify") )
1905 /* Force verification of the Admin Command. However,
1906 this is only done if the retry counter is at initial
1908 char *tmp = xmalloc (strlen (serialnobuf) + 6 + 1);
1909 strcpy (stpcpy (tmp, serialnobuf), "[CHV3]");
1910 allow_admin = !agent_scd_checkpin (tmp);
1914 allow_admin=!allow_admin;
1916 tty_printf(_("Admin commands are allowed\n"));
1918 tty_printf(_("Admin commands are not allowed\n"));
1922 agent_scd_checkpin (serialnobuf);
1943 change_login (arg_string);
1955 if ( arg_number < 1 || arg_number > 3 )
1956 tty_printf ("usage: cafpr N\n"
1959 change_cafpr (arg_number);
1963 if ( arg_number < 1 || arg_number > 4 )
1964 tty_printf ("usage: privatedo N\n"
1967 change_private_do (arg_string, arg_number);
1971 if ( arg_number != 3 )
1972 tty_printf ("usage: writecert 3 < FILE\n");
1974 change_cert (arg_rest);
1978 if ( arg_number != 3 )
1979 tty_printf ("usage: readcert 3 > FILE\n");
1981 read_cert (arg_rest);
1989 generate_card_keys ();
1993 change_pin (0, allow_admin);
1997 change_pin (1, allow_admin);
2009 tty_printf (_("Invalid command (try \"help\")\n"));
2011 } /* End command switch. */
2012 } /* End of main menu loop. */