agent/
[gnupg.git] / g10 / card-util.c
blob61fd3112e6091ba555584b11b2ac441171cf2a61
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/>.
20 #include <config.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <errno.h>
25 #include <assert.h>
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
32 # include "gpg.h"
33 #endif /*GNUPG_MAJOR_VERSION != 1*/
34 #include "util.h"
35 #include "i18n.h"
36 #include "ttyio.h"
37 #include "status.h"
38 #include "options.h"
39 #include "main.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)
51 static void
52 write_sc_op_status (gpg_error_t err)
54 switch (gpg_err_code (err))
56 case 0:
57 write_status (STATUS_SC_OP_SUCCESS);
58 break;
59 #if GNUPG_MAJOR_VERSION != 1
60 case GPG_ERR_CANCELED:
61 write_status_text (STATUS_SC_OP_FAILURE, "1");
62 break;
63 case GPG_ERR_BAD_PIN:
64 write_status_text (STATUS_SC_OP_FAILURE, "2");
65 break;
66 default:
67 write_status (STATUS_SC_OP_FAILURE);
68 break;
69 #endif /* GNUPG_MAJOR_VERSION != 1 */
74 /* Change the PIN of a an OpenPGP card. This is an interactive
75 function. */
76 void
77 change_pin (int unblock_v2, int allow_admin)
79 struct agent_card_info_s info;
80 int rc;
82 rc = agent_learn (&info);
83 if (rc)
85 log_error (_("OpenPGP card not available: %s\n"),
86 gpg_strerror (rc));
87 return;
90 log_info (_("OpenPGP card no. %s detected\n"),
91 info.serialno? info.serialno : "[none]");
93 agent_clear_pin_cache (info.serialno);
95 if (opt.batch)
97 agent_release_card_info (&info);
98 log_error (_("can't do this in batch mode\n"));
99 return;
103 if (unblock_v2)
105 if (!info.is_v2)
106 log_error (_("This command is only available for version 2 cards\n"));
107 else if (!info.chvretry[1])
108 log_error (_("Reset Code not or not anymore available\n"));
109 else
111 rc = agent_scd_change_pin (2, info.serialno);
112 write_sc_op_status (rc);
113 if (rc)
114 tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc));
115 else
116 tty_printf ("PIN changed.\n");
119 else if (!allow_admin)
121 rc = agent_scd_change_pin (1, info.serialno);
122 write_sc_op_status (rc);
123 if (rc)
124 tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc));
125 else
126 tty_printf ("PIN changed.\n");
128 else
129 for (;;)
131 char *answer;
133 tty_printf ("\n");
134 tty_printf ("1 - change PIN\n"
135 "2 - unblock PIN\n"
136 "3 - change Admin PIN\n"
137 "4 - set the Reset Code\n"
138 "Q - quit\n");
139 tty_printf ("\n");
141 answer = cpr_get("cardutil.change_pin.menu",_("Your selection? "));
142 cpr_kill_prompt();
143 if (strlen (answer) != 1)
144 continue;
146 rc = 0;
147 if (*answer == '1')
149 /* Change PIN. */
150 rc = agent_scd_change_pin (1, info.serialno);
151 write_sc_op_status (rc);
152 if (rc)
153 tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc));
154 else
155 tty_printf ("PIN changed.\n");
157 else if (*answer == '2')
159 /* Unblock PIN. */
160 rc = agent_scd_change_pin (101, info.serialno);
161 write_sc_op_status (rc);
162 if (rc)
163 tty_printf ("Error unblocking the PIN: %s\n", gpg_strerror (rc));
164 else
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);
172 if (rc)
173 tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc));
174 else
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);
182 if (rc)
183 tty_printf ("Error setting the Reset Code: %s\n",
184 gpg_strerror (rc));
185 else
186 tty_printf ("Reset Code set.\n");
188 else if (*answer == 'q' || *answer == 'Q')
190 break;
194 agent_release_card_info (&info);
197 static const char *
198 get_manufacturer (unsigned int no)
200 /* Note: Make sure that there is no colon or linefeed in the string. */
201 switch (no)
203 case 0x0001: return "PPC Card Systems";
204 case 0x0002: return "Prism";
205 case 0x0003: return "OpenFortress";
206 case 0x0004: return "Wewid AB";
207 case 0x0005: return "ZeitControl";
209 case 0x002A: return "Magrathea";
210 /* 0x00000 and 0xFFFF are defined as test cards per spec,
211 0xFFF00 to 0xFFFE are assigned for use with randomly created
212 serial numbers. */
213 case 0x0000:
214 case 0xffff: return "test card";
215 default: return (no & 0xff00) == 0xff00? "unmanaged S/N range":"unknown";
220 static void
221 print_sha1_fpr (FILE *fp, const unsigned char *fpr)
223 int i;
225 if (fpr)
227 for (i=0; i < 20 ; i+=2, fpr += 2 )
229 if (i == 10 )
230 tty_fprintf (fp, " ");
231 tty_fprintf (fp, " %02X%02X", *fpr, fpr[1]);
234 else
235 tty_fprintf (fp, " [none]");
236 tty_fprintf (fp, "\n");
240 static void
241 print_sha1_fpr_colon (FILE *fp, const unsigned char *fpr)
243 int i;
245 if (fpr)
247 for (i=0; i < 20 ; i++, fpr++)
248 fprintf (fp, "%02X", *fpr);
250 putc (':', fp);
254 static void
255 print_name (FILE *fp, const char *text, const char *name)
257 tty_fprintf (fp, "%s", text);
259 /* FIXME: tty_printf_utf8_string2 eats everything after and
260 including an @ - e.g. when printing an url. */
261 if (name && *name)
263 if (fp)
264 print_utf8_string2 (fp, name, strlen (name), '\n');
265 else
266 tty_print_utf8_string2 (name, strlen (name), 0);
268 else
269 tty_fprintf (fp, _("[not set]"));
270 tty_fprintf (fp, "\n");
273 static void
274 print_isoname (FILE *fp, const char *text, const char *tag, const char *name)
276 if (opt.with_colons)
277 fprintf (fp, "%s:", tag);
278 else
279 tty_fprintf (fp, "%s", text);
281 if (name && *name)
283 char *p, *given, *buf = xstrdup (name);
285 given = strstr (buf, "<<");
286 for (p=buf; *p; p++)
287 if (*p == '<')
288 *p = ' ';
289 if (given && given[2])
291 *given = 0;
292 given += 2;
293 if (opt.with_colons)
294 print_string (fp, given, strlen (given), ':');
295 else if (fp)
296 print_utf8_string2 (fp, given, strlen (given), '\n');
297 else
298 tty_print_utf8_string2 (given, strlen (given), 0);
300 if (opt.with_colons)
301 putc (':', fp);
302 else if (*buf)
303 tty_fprintf (fp, " ");
306 if (opt.with_colons)
307 print_string (fp, buf, strlen (buf), ':');
308 else if (fp)
309 print_utf8_string2 (fp, buf, strlen (buf), '\n');
310 else
311 tty_print_utf8_string2 (buf, strlen (buf), 0);
312 xfree (buf);
314 else
316 if (opt.with_colons)
317 putc (':', fp);
318 else
319 tty_fprintf (fp, _("[not set]"));
322 if (opt.with_colons)
323 fputs (":\n", fp);
324 else
325 tty_fprintf (fp, "\n");
328 /* Return true if the SHA1 fingerprint FPR consists only of zeroes. */
329 static int
330 fpr_is_zero (const char *fpr)
332 int i;
334 for (i=0; i < 20 && !fpr[i]; i++)
336 return (i == 20);
340 /* Return true if the SHA1 fingerprint FPR consists only of 0xFF. */
341 static int
342 fpr_is_ff (const char *fpr)
344 int i;
346 for (i=0; i < 20 && fpr[i] == '\xff'; i++)
348 return (i == 20);
352 /* Print all available information about the current card. */
353 void
354 card_status (FILE *fp, char *serialno, size_t serialnobuflen)
356 struct agent_card_info_s info;
357 PKT_public_key *pk = xcalloc (1, sizeof *pk);
358 int rc;
359 unsigned int uval;
360 const unsigned char *thefpr;
361 int i;
363 if (serialno && serialnobuflen)
364 *serialno = 0;
366 rc = agent_learn (&info);
367 if (rc)
369 if (opt.with_colons)
370 fputs ("AID:::\n", fp);
371 log_error (_("OpenPGP card not available: %s\n"),
372 gpg_strerror (rc));
373 xfree (pk);
374 return;
377 if (opt.with_colons)
378 fprintf (fp, "AID:%s:", info.serialno? info.serialno : "");
379 else
380 tty_fprintf (fp, "Application ID ...: %s\n",
381 info.serialno? info.serialno : "[none]");
382 if (!info.serialno || strncmp (info.serialno, "D27600012401", 12)
383 || strlen (info.serialno) != 32 )
385 if (info.apptype && !strcmp (info.apptype, "NKS"))
387 if (opt.with_colons)
388 fputs ("netkey-card:\n", fp);
389 log_info ("this is a NetKey card\n");
391 else if (info.apptype && !strcmp (info.apptype, "DINSIG"))
393 if (opt.with_colons)
394 fputs ("dinsig-card:\n", fp);
395 log_info ("this is a DINSIG compliant card\n");
397 else if (info.apptype && !strcmp (info.apptype, "P15"))
399 if (opt.with_colons)
400 fputs ("pkcs15-card:\n", fp);
401 log_info ("this is a PKCS#15 compliant card\n");
403 else if (info.apptype && !strcmp (info.apptype, "GELDKARTE"))
405 if (opt.with_colons)
406 fputs ("geldkarte-card:\n", fp);
407 log_info ("this is a Geldkarte compliant card\n");
409 else
411 if (opt.with_colons)
412 fputs ("unknown:\n", fp);
414 log_info ("not an OpenPGP card\n");
415 agent_release_card_info (&info);
416 xfree (pk);
417 return;
420 if (!serialno)
422 else if (strlen (serialno)+1 > serialnobuflen)
423 log_error ("serial number longer than expected\n");
424 else
425 strcpy (serialno, info.serialno);
427 if (opt.with_colons)
428 fputs ("openpgp-card:\n", fp);
431 if (opt.with_colons)
433 fprintf (fp, "version:%.4s:\n", info.serialno+12);
434 uval = xtoi_2(info.serialno+16)*256 + xtoi_2 (info.serialno+18);
435 fprintf (fp, "vendor:%04x:%s:\n", uval, get_manufacturer (uval));
436 fprintf (fp, "serial:%.8s:\n", info.serialno+20);
438 print_isoname (fp, "Name of cardholder: ", "name", info.disp_name);
440 fputs ("lang:", fp);
441 if (info.disp_lang)
442 print_string (fp, info.disp_lang, strlen (info.disp_lang), ':');
443 fputs (":\n", fp);
445 fprintf (fp, "sex:%c:\n", (info.disp_sex == 1? 'm':
446 info.disp_sex == 2? 'f' : 'u'));
448 fputs ("url:", fp);
449 if (info.pubkey_url)
450 print_string (fp, info.pubkey_url, strlen (info.pubkey_url), ':');
451 fputs (":\n", fp);
453 fputs ("login:", fp);
454 if (info.login_data)
455 print_string (fp, info.login_data, strlen (info.login_data), ':');
456 fputs (":\n", fp);
458 fprintf (fp, "forcepin:%d:::\n", !info.chv1_cached);
459 for (i=0; i < DIM (info.key_attr); i++)
460 if (info.key_attr[0].algo)
461 fprintf (fp, "keyattr:%d:%d:%u:\n", i+1,
462 info.key_attr[i].algo, info.key_attr[i].nbits);
463 fprintf (fp, "maxpinlen:%d:%d:%d:\n",
464 info.chvmaxlen[0], info.chvmaxlen[1], info.chvmaxlen[2]);
465 fprintf (fp, "pinretry:%d:%d:%d:\n",
466 info.chvretry[0], info.chvretry[1], info.chvretry[2]);
467 fprintf (fp, "sigcount:%lu:::\n", info.sig_counter);
469 for (i=0; i < 4; i++)
471 if (info.private_do[i])
473 fprintf (fp, "private_do:%d:", i+1);
474 print_string (fp, info.private_do[i],
475 strlen (info.private_do[i]), ':');
476 fputs (":\n", fp);
480 fputs ("cafpr:", fp);
481 print_sha1_fpr_colon (fp, info.cafpr1valid? info.cafpr1:NULL);
482 print_sha1_fpr_colon (fp, info.cafpr2valid? info.cafpr2:NULL);
483 print_sha1_fpr_colon (fp, info.cafpr3valid? info.cafpr3:NULL);
484 putc ('\n', fp);
485 fputs ("fpr:", fp);
486 print_sha1_fpr_colon (fp, info.fpr1valid? info.fpr1:NULL);
487 print_sha1_fpr_colon (fp, info.fpr2valid? info.fpr2:NULL);
488 print_sha1_fpr_colon (fp, info.fpr3valid? info.fpr3:NULL);
489 putc ('\n', fp);
490 fprintf (fp, "fprtime:%lu:%lu:%lu:\n",
491 (unsigned long)info.fpr1time, (unsigned long)info.fpr2time,
492 (unsigned long)info.fpr3time);
494 else
496 tty_fprintf (fp, "Version ..........: %.1s%c.%.1s%c\n",
497 info.serialno[12] == '0'?"":info.serialno+12,
498 info.serialno[13],
499 info.serialno[14] == '0'?"":info.serialno+14,
500 info.serialno[15]);
501 tty_fprintf (fp, "Manufacturer .....: %s\n",
502 get_manufacturer (xtoi_2(info.serialno+16)*256
503 + xtoi_2 (info.serialno+18)));
504 tty_fprintf (fp, "Serial number ....: %.8s\n", info.serialno+20);
506 print_isoname (fp, "Name of cardholder: ", "name", info.disp_name);
507 print_name (fp, "Language prefs ...: ", info.disp_lang);
508 tty_fprintf (fp, "Sex ..............: %s\n",
509 info.disp_sex == 1? _("male"):
510 info.disp_sex == 2? _("female") : _("unspecified"));
511 print_name (fp, "URL of public key : ", info.pubkey_url);
512 print_name (fp, "Login data .......: ", info.login_data);
513 if (info.private_do[0])
514 print_name (fp, "Private DO 1 .....: ", info.private_do[0]);
515 if (info.private_do[1])
516 print_name (fp, "Private DO 2 .....: ", info.private_do[1]);
517 if (info.private_do[2])
518 print_name (fp, "Private DO 3 .....: ", info.private_do[2]);
519 if (info.private_do[3])
520 print_name (fp, "Private DO 4 .....: ", info.private_do[3]);
521 if (info.cafpr1valid)
523 tty_fprintf (fp, "CA fingerprint %d .:", 1);
524 print_sha1_fpr (fp, info.cafpr1);
526 if (info.cafpr2valid)
528 tty_fprintf (fp, "CA fingerprint %d .:", 2);
529 print_sha1_fpr (fp, info.cafpr2);
531 if (info.cafpr3valid)
533 tty_fprintf (fp, "CA fingerprint %d .:", 3);
534 print_sha1_fpr (fp, info.cafpr3);
536 tty_fprintf (fp, "Signature PIN ....: %s\n",
537 info.chv1_cached? _("not forced"): _("forced"));
538 if (info.key_attr[0].algo)
540 tty_fprintf (fp, "Key attributes ...:");
541 for (i=0; i < DIM (info.key_attr); i++)
542 tty_fprintf (fp, " %u%c",
543 info.key_attr[i].nbits,
544 info.key_attr[i].algo == 1? 'R':
545 info.key_attr[i].algo == 17? 'D': '?');
546 tty_fprintf (fp, "\n");
548 tty_fprintf (fp, "Max. PIN lengths .: %d %d %d\n",
549 info.chvmaxlen[0], info.chvmaxlen[1], info.chvmaxlen[2]);
550 tty_fprintf (fp, "PIN retry counter : %d %d %d\n",
551 info.chvretry[0], info.chvretry[1], info.chvretry[2]);
552 tty_fprintf (fp, "Signature counter : %lu\n", info.sig_counter);
553 tty_fprintf (fp, "Signature key ....:");
554 print_sha1_fpr (fp, info.fpr1valid? info.fpr1:NULL);
555 if (info.fpr1valid && info.fpr1time)
556 tty_fprintf (fp, " created ....: %s\n",
557 isotimestamp (info.fpr1time));
558 tty_fprintf (fp, "Encryption key....:");
559 print_sha1_fpr (fp, info.fpr2valid? info.fpr2:NULL);
560 if (info.fpr2valid && info.fpr2time)
561 tty_fprintf (fp, " created ....: %s\n",
562 isotimestamp (info.fpr2time));
563 tty_fprintf (fp, "Authentication key:");
564 print_sha1_fpr (fp, info.fpr3valid? info.fpr3:NULL);
565 if (info.fpr3valid && info.fpr3time)
566 tty_fprintf (fp, " created ....: %s\n",
567 isotimestamp (info.fpr3time));
568 tty_fprintf (fp, "General key info..: ");
570 thefpr = (info.fpr1valid? info.fpr1 : info.fpr2valid? info.fpr2 :
571 info.fpr3valid? info.fpr3 : NULL);
572 /* If the fingerprint is all 0xff, the key has no asssociated
573 OpenPGP certificate. */
574 if ( thefpr && !fpr_is_ff (thefpr)
575 && !get_pubkey_byfprint (pk, thefpr, 20))
577 KBNODE keyblock = NULL;
579 print_pubkey_info (fp, pk);
581 if ( !get_seckeyblock_byfprint (&keyblock, thefpr, 20) )
582 print_card_key_info (fp, keyblock);
583 else if ( !get_keyblock_byfprint (&keyblock, thefpr, 20) )
585 release_kbnode (keyblock);
586 keyblock = NULL;
588 if (!auto_create_card_key_stub (info.serialno,
589 info.fpr1valid? info.fpr1:NULL,
590 info.fpr2valid? info.fpr2:NULL,
591 info.fpr3valid? info.fpr3:NULL))
593 if ( !get_seckeyblock_byfprint (&keyblock, thefpr, 20) )
594 print_card_key_info (fp, keyblock);
598 release_kbnode (keyblock);
600 else
601 tty_fprintf (fp, "[none]\n");
604 free_public_key (pk);
605 agent_release_card_info (&info);
609 static char *
610 get_one_name (const char *prompt1, const char *prompt2)
612 char *name;
613 int i;
615 for (;;)
617 name = cpr_get (prompt1, prompt2);
618 if (!name)
619 return NULL;
620 trim_spaces (name);
621 cpr_kill_prompt ();
622 for (i=0; name[i] && name[i] >= ' ' && name[i] <= 126; i++)
625 /* The name must be in Latin-1 and not UTF-8 - lacking the code
626 to ensure this we restrict it to ASCII. */
627 if (name[i])
628 tty_printf (_("Error: Only plain ASCII is currently allowed.\n"));
629 else if (strchr (name, '<'))
630 tty_printf (_("Error: The \"<\" character may not be used.\n"));
631 else if (strstr (name, " "))
632 tty_printf (_("Error: Double spaces are not allowed.\n"));
633 else
634 return name;
635 xfree (name);
641 static int
642 change_name (void)
644 char *surname = NULL, *givenname = NULL;
645 char *isoname, *p;
646 int rc;
648 surname = get_one_name ("keygen.smartcard.surname",
649 _("Cardholder's surname: "));
650 givenname = get_one_name ("keygen.smartcard.givenname",
651 _("Cardholder's given name: "));
652 if (!surname || !givenname || (!*surname && !*givenname))
654 xfree (surname);
655 xfree (givenname);
656 return -1; /*canceled*/
659 isoname = xmalloc ( strlen (surname) + 2 + strlen (givenname) + 1);
660 strcpy (stpcpy (stpcpy (isoname, surname), "<<"), givenname);
661 xfree (surname);
662 xfree (givenname);
663 for (p=isoname; *p; p++)
664 if (*p == ' ')
665 *p = '<';
667 if (strlen (isoname) > 39 )
669 tty_printf (_("Error: Combined name too long "
670 "(limit is %d characters).\n"), 39);
671 xfree (isoname);
672 return -1;
675 rc = agent_scd_setattr ("DISP-NAME", isoname, strlen (isoname), NULL );
676 if (rc)
677 log_error ("error setting Name: %s\n", gpg_strerror (rc));
679 xfree (isoname);
680 return rc;
684 static int
685 change_url (void)
687 char *url;
688 int rc;
690 url = cpr_get ("cardedit.change_url", _("URL to retrieve public key: "));
691 if (!url)
692 return -1;
693 trim_spaces (url);
694 cpr_kill_prompt ();
696 if (strlen (url) > 254 )
698 tty_printf (_("Error: URL too long "
699 "(limit is %d characters).\n"), 254);
700 xfree (url);
701 return -1;
704 rc = agent_scd_setattr ("PUBKEY-URL", url, strlen (url), NULL );
705 if (rc)
706 log_error ("error setting URL: %s\n", gpg_strerror (rc));
707 xfree (url);
708 write_sc_op_status (rc);
709 return rc;
713 /* Fetch the key from the URL given on the card or try to get it from
714 the default keyserver. */
715 static int
716 fetch_url(void)
718 int rc;
719 struct agent_card_info_s info;
721 memset(&info,0,sizeof(info));
723 rc=agent_scd_getattr("PUBKEY-URL",&info);
724 if(rc)
725 log_error("error retrieving URL from card: %s\n",gpg_strerror(rc));
726 else
728 struct keyserver_spec *spec=NULL;
730 rc=agent_scd_getattr("KEY-FPR",&info);
731 if(rc)
732 log_error("error retrieving key fingerprint from card: %s\n",
733 gpg_strerror(rc));
734 else if (info.pubkey_url && *info.pubkey_url)
736 spec=parse_keyserver_uri(info.pubkey_url,1,NULL,0);
737 if(spec && info.fpr1valid)
739 /* This is not perfectly right. Currently, all card
740 fingerprints are 20 digits, but what about
741 fingerprints for a future v5 key? We should get the
742 length from somewhere lower in the code. In any
743 event, the fpr/keyid is not meaningful for straight
744 HTTP fetches, but using it allows the card to point
745 to HKP and LDAP servers as well. */
746 rc=keyserver_import_fprint(info.fpr1,20,spec);
747 free_keyserver_spec(spec);
750 else if (info.fpr1valid)
752 rc = keyserver_import_fprint (info.fpr1, 20, opt.keyserver);
756 return rc;
760 /* Read data from file FNAME up to MAXLEN characters. On error return
761 -1 and store NULL at R_BUFFER; on success return the number of
762 bytes read and store the address of a newly allocated buffer at
763 R_BUFFER. */
764 static int
765 get_data_from_file (const char *fname, size_t maxlen, char **r_buffer)
767 FILE *fp;
768 char *data;
769 int n;
771 *r_buffer = NULL;
773 fp = fopen (fname, "rb");
774 #if GNUPG_MAJOR_VERSION == 1
775 if (fp && is_secured_file (fileno (fp)))
777 fclose (fp);
778 fp = NULL;
779 errno = EPERM;
781 #endif
782 if (!fp)
784 tty_printf (_("can't open `%s': %s\n"), fname, strerror (errno));
785 return -1;
788 data = xtrymalloc (maxlen? maxlen:1);
789 if (!data)
791 tty_printf (_("error allocating enough memory: %s\n"), strerror (errno));
792 fclose (fp);
793 return -1;
796 if (maxlen)
797 n = fread (data, 1, maxlen, fp);
798 else
799 n = 0;
800 fclose (fp);
801 if (n < 0)
803 tty_printf (_("error reading `%s': %s\n"), fname, strerror (errno));
804 xfree (data);
805 return -1;
807 *r_buffer = data;
808 return n;
812 /* Write LENGTH bytes from BUFFER to file FNAME. Return 0 on
813 success. */
814 static int
815 put_data_to_file (const char *fname, const void *buffer, size_t length)
817 FILE *fp;
819 fp = fopen (fname, "wb");
820 #if GNUPG_MAJOR_VERSION == 1
821 if (fp && is_secured_file (fileno (fp)))
823 fclose (fp);
824 fp = NULL;
825 errno = EPERM;
827 #endif
828 if (!fp)
830 tty_printf (_("can't create `%s': %s\n"), fname, strerror (errno));
831 return -1;
834 if (length && fwrite (buffer, length, 1, fp) != 1)
836 tty_printf (_("error writing `%s': %s\n"), fname, strerror (errno));
837 fclose (fp);
838 return -1;
840 fclose (fp);
841 return 0;
845 static int
846 change_login (const char *args)
848 char *data;
849 int n;
850 int rc;
852 if (args && *args == '<') /* Read it from a file */
854 for (args++; spacep (args); args++)
856 n = get_data_from_file (args, 254, &data);
857 if (n < 0)
858 return -1;
860 else
862 data = cpr_get ("cardedit.change_login",
863 _("Login data (account name): "));
864 if (!data)
865 return -1;
866 trim_spaces (data);
867 cpr_kill_prompt ();
868 n = strlen (data);
871 if (n > 254 )
873 tty_printf (_("Error: Login data too long "
874 "(limit is %d characters).\n"), 254);
875 xfree (data);
876 return -1;
879 rc = agent_scd_setattr ("LOGIN-DATA", data, n, NULL );
880 if (rc)
881 log_error ("error setting login data: %s\n", gpg_strerror (rc));
882 xfree (data);
883 write_sc_op_status (rc);
884 return rc;
887 static int
888 change_private_do (const char *args, int nr)
890 char do_name[] = "PRIVATE-DO-X";
891 char *data;
892 int n;
893 int rc;
895 assert (nr >= 1 && nr <= 4);
896 do_name[11] = '0' + nr;
898 if (args && (args = strchr (args, '<'))) /* Read it from a file */
900 for (args++; spacep (args); args++)
902 n = get_data_from_file (args, 254, &data);
903 if (n < 0)
904 return -1;
906 else
908 data = cpr_get ("cardedit.change_private_do",
909 _("Private DO data: "));
910 if (!data)
911 return -1;
912 trim_spaces (data);
913 cpr_kill_prompt ();
914 n = strlen (data);
917 if (n > 254 )
919 tty_printf (_("Error: Private DO too long "
920 "(limit is %d characters).\n"), 254);
921 xfree (data);
922 return -1;
925 rc = agent_scd_setattr (do_name, data, n, NULL );
926 if (rc)
927 log_error ("error setting private DO: %s\n", gpg_strerror (rc));
928 xfree (data);
929 write_sc_op_status (rc);
930 return rc;
934 static int
935 change_cert (const char *args)
937 char *data;
938 int n;
939 int rc;
941 if (args && *args == '<') /* Read it from a file */
943 for (args++; spacep (args); args++)
945 n = get_data_from_file (args, 16384, &data);
946 if (n < 0)
947 return -1;
949 else
951 tty_printf ("usage error: redirectrion to file required\n");
952 return -1;
955 rc = agent_scd_writecert ("OPENPGP.3", data, n);
956 if (rc)
957 log_error ("error writing certificate to card: %s\n", gpg_strerror (rc));
958 xfree (data);
959 write_sc_op_status (rc);
960 return rc;
964 static int
965 read_cert (const char *args)
967 const char *fname;
968 void *buffer;
969 size_t length;
970 int rc;
972 if (args && *args == '>') /* Write it to a file */
974 for (args++; spacep (args); args++)
976 fname = args;
978 else
980 tty_printf ("usage error: redirectrion to file required\n");
981 return -1;
984 rc = agent_scd_readcert ("OPENPGP.3", &buffer, &length);
985 if (rc)
986 log_error ("error reading certificate from card: %s\n", gpg_strerror (rc));
987 else
988 rc = put_data_to_file (fname, buffer, length);
989 xfree (buffer);
990 write_sc_op_status (rc);
991 return rc;
995 static int
996 change_lang (void)
998 char *data, *p;
999 int rc;
1001 data = cpr_get ("cardedit.change_lang",
1002 _("Language preferences: "));
1003 if (!data)
1004 return -1;
1005 trim_spaces (data);
1006 cpr_kill_prompt ();
1008 if (strlen (data) > 8 || (strlen (data) & 1))
1010 tty_printf (_("Error: invalid length of preference string.\n"));
1011 xfree (data);
1012 return -1;
1015 for (p=data; *p && *p >= 'a' && *p <= 'z'; p++)
1017 if (*p)
1019 tty_printf (_("Error: invalid characters in preference string.\n"));
1020 xfree (data);
1021 return -1;
1024 rc = agent_scd_setattr ("DISP-LANG", data, strlen (data), NULL );
1025 if (rc)
1026 log_error ("error setting lang: %s\n", gpg_strerror (rc));
1027 xfree (data);
1028 write_sc_op_status (rc);
1029 return rc;
1033 static int
1034 change_sex (void)
1036 char *data;
1037 const char *str;
1038 int rc;
1040 data = cpr_get ("cardedit.change_sex",
1041 _("Sex ((M)ale, (F)emale or space): "));
1042 if (!data)
1043 return -1;
1044 trim_spaces (data);
1045 cpr_kill_prompt ();
1047 if (!*data)
1048 str = "9";
1049 else if ((*data == 'M' || *data == 'm') && !data[1])
1050 str = "1";
1051 else if ((*data == 'F' || *data == 'f') && !data[1])
1052 str = "2";
1053 else
1055 tty_printf (_("Error: invalid response.\n"));
1056 xfree (data);
1057 return -1;
1060 rc = agent_scd_setattr ("DISP-SEX", str, 1, NULL );
1061 if (rc)
1062 log_error ("error setting sex: %s\n", gpg_strerror (rc));
1063 xfree (data);
1064 write_sc_op_status (rc);
1065 return rc;
1069 static int
1070 change_cafpr (int fprno)
1072 char *data;
1073 const char *s;
1074 int i, c, rc;
1075 unsigned char fpr[20];
1077 data = cpr_get ("cardedit.change_cafpr", _("CA fingerprint: "));
1078 if (!data)
1079 return -1;
1080 trim_spaces (data);
1081 cpr_kill_prompt ();
1083 for (i=0, s=data; i < 20 && *s; )
1085 while (spacep(s))
1086 s++;
1087 if (*s == ':')
1088 s++;
1089 while (spacep(s))
1090 s++;
1091 c = hextobyte (s);
1092 if (c == -1)
1093 break;
1094 fpr[i++] = c;
1095 s += 2;
1097 xfree (data);
1098 if (i != 20 || *s)
1100 tty_printf (_("Error: invalid formatted fingerprint.\n"));
1101 return -1;
1104 rc = agent_scd_setattr (fprno==1?"CA-FPR-1":
1105 fprno==2?"CA-FPR-2":
1106 fprno==3?"CA-FPR-3":"x", fpr, 20, NULL );
1107 if (rc)
1108 log_error ("error setting cafpr: %s\n", gpg_strerror (rc));
1109 write_sc_op_status (rc);
1110 return rc;
1115 static void
1116 toggle_forcesig (void)
1118 struct agent_card_info_s info;
1119 int rc;
1120 int newstate;
1122 memset (&info, 0, sizeof info);
1123 rc = agent_scd_getattr ("CHV-STATUS", &info);
1124 if (rc)
1126 log_error ("error getting current status: %s\n", gpg_strerror (rc));
1127 return;
1129 newstate = !info.chv1_cached;
1130 agent_release_card_info (&info);
1132 rc = agent_scd_setattr ("CHV-STATUS-1", newstate? "\x01":"", 1, NULL);
1133 if (rc)
1134 log_error ("error toggling signature PIN flag: %s\n", gpg_strerror (rc));
1135 write_sc_op_status (rc);
1139 /* Helper for the key generation/edit functions. */
1140 static int
1141 get_info_for_key_operation (struct agent_card_info_s *info)
1143 int rc;
1145 memset (info, 0, sizeof *info);
1146 rc = agent_scd_getattr ("SERIALNO", info);
1147 if (rc || !info->serialno || strncmp (info->serialno, "D27600012401", 12)
1148 || strlen (info->serialno) != 32 )
1150 log_error (_("key operation not possible: %s\n"),
1151 rc ? gpg_strerror (rc) : _("not an OpenPGP card"));
1152 return rc? rc: -1;
1154 rc = agent_scd_getattr ("KEY-FPR", info);
1155 if (!rc)
1156 rc = agent_scd_getattr ("CHV-STATUS", info);
1157 if (!rc)
1158 rc = agent_scd_getattr ("DISP-NAME", info);
1159 if (!rc)
1160 rc = agent_scd_getattr ("EXTCAP", info);
1161 if (!rc)
1162 rc = agent_scd_getattr ("KEY-ATTR", info);
1163 if (rc)
1164 log_error (_("error getting current key info: %s\n"), gpg_strerror (rc));
1165 return rc;
1169 /* Helper for the key generation/edit functions. */
1170 static int
1171 check_pin_for_key_operation (struct agent_card_info_s *info, int *forced_chv1)
1173 int rc = 0;
1175 agent_clear_pin_cache (info->serialno);
1177 *forced_chv1 = !info->chv1_cached;
1178 if (*forced_chv1)
1179 { /* Switch off the forced mode so that during key generation we
1180 don't get bothered with PIN queries for each
1181 self-signature. */
1182 rc = agent_scd_setattr ("CHV-STATUS-1", "\x01", 1, info->serialno);
1183 if (rc)
1185 log_error ("error clearing forced signature PIN flag: %s\n",
1186 gpg_strerror (rc));
1187 *forced_chv1 = 0;
1191 if (!rc)
1193 /* Check the PIN now, so that we won't get asked later for each
1194 binding signature. */
1195 rc = agent_scd_checkpin (info->serialno);
1196 if (rc)
1198 log_error ("error checking the PIN: %s\n", gpg_strerror (rc));
1199 write_sc_op_status (rc);
1202 return rc;
1205 /* Helper for the key generation/edit functions. */
1206 static void
1207 restore_forced_chv1 (int *forced_chv1)
1209 int rc;
1211 if (*forced_chv1)
1212 { /* Switch back to forced state. */
1213 rc = agent_scd_setattr ("CHV-STATUS-1", "", 1, NULL);
1214 if (rc)
1216 log_error ("error setting forced signature PIN flag: %s\n",
1217 gpg_strerror (rc));
1223 /* Helper for the key generation/edit functions. */
1224 static void
1225 show_card_key_info (struct agent_card_info_s *info)
1227 tty_fprintf (NULL, "Signature key ....:");
1228 print_sha1_fpr (NULL, info->fpr1valid? info->fpr1:NULL);
1229 tty_fprintf (NULL, "Encryption key....:");
1230 print_sha1_fpr (NULL, info->fpr2valid? info->fpr2:NULL);
1231 tty_fprintf (NULL, "Authentication key:");
1232 print_sha1_fpr (NULL, info->fpr3valid? info->fpr3:NULL);
1233 tty_printf ("\n");
1237 /* Helper for the key generation/edit functions. */
1238 static int
1239 replace_existing_key_p (struct agent_card_info_s *info, int keyno)
1241 assert (keyno >= 0 && keyno <= 3);
1243 if ((keyno == 1 && info->fpr1valid)
1244 || (keyno == 2 && info->fpr2valid)
1245 || (keyno == 3 && info->fpr3valid))
1247 tty_printf ("\n");
1248 log_info ("WARNING: such a key has already been stored on the card!\n");
1249 tty_printf ("\n");
1250 if ( !cpr_get_answer_is_yes( "cardedit.genkeys.replace_key",
1251 _("Replace existing key? (y/N) ")))
1252 return -1;
1254 return 0;
1258 static void
1259 show_keysize_warning (void)
1261 static int shown;
1263 if (shown)
1264 return;
1265 shown = 1;
1266 tty_printf
1267 (_("NOTE: There is no guarantee that the card "
1268 "supports the requested size.\n"
1269 " If the key generation does not succeed, "
1270 "please check the\n"
1271 " documentation of your card to see what "
1272 "sizes are allowed.\n"));
1276 /* Ask for the size of a card key. NBITS is the current size
1277 configured for the card. KEYNO is the number of the key used to
1278 select the prompt. Returns 0 to use the default size (i.e. NBITS)
1279 or the selected size. */
1280 static unsigned int
1281 ask_card_keysize (int keyno, unsigned int nbits)
1283 unsigned int min_nbits = 1024;
1284 unsigned int max_nbits = 3072; /* GnuPG limit due to Assuan. */
1285 char *prompt, *answer;
1286 unsigned int req_nbits;
1288 for (;;)
1290 prompt = xasprintf
1291 (keyno == 0?
1292 _("What keysize do you want for the Signature key? (%u) "):
1293 keyno == 1?
1294 _("What keysize do you want for the Encryption key? (%u) "):
1295 _("What keysize do you want for the Authentication key? (%u) "),
1296 nbits);
1297 answer = cpr_get ("cardedit.genkeys.size", prompt);
1298 cpr_kill_prompt ();
1299 req_nbits = *answer? atoi (answer): nbits;
1300 xfree (prompt);
1301 xfree (answer);
1303 if (req_nbits != nbits && (req_nbits % 32) )
1305 req_nbits = ((req_nbits + 31) / 32) * 32;
1306 tty_printf (_("rounded up to %u bits\n"), req_nbits);
1309 if (req_nbits == nbits)
1310 return 0; /* Use default. */
1312 if (req_nbits < min_nbits || req_nbits > max_nbits)
1314 tty_printf (_("%s keysizes must be in the range %u-%u\n"),
1315 "RSA", min_nbits, max_nbits);
1317 else
1319 tty_printf (_("The card will now be re-configured "
1320 "to generate a key of %u bits\n"), req_nbits);
1321 show_keysize_warning ();
1322 return req_nbits;
1328 /* Change the size of key KEYNO (0..2) to NBITS and show an error
1329 message if that fails. */
1330 static gpg_error_t
1331 do_change_keysize (int keyno, unsigned int nbits)
1333 gpg_error_t err;
1334 char args[100];
1336 snprintf (args, sizeof args, "--force %d 1 %u", keyno+1, nbits);
1337 err = agent_scd_setattr ("KEY-ATTR", args, strlen (args), NULL);
1338 if (err)
1339 log_error (_("error changing size of key %d to %u bits: %s\n"),
1340 keyno+1, nbits, gpg_strerror (err));
1341 return err;
1345 static void
1346 generate_card_keys (void)
1348 struct agent_card_info_s info;
1349 int forced_chv1;
1350 int want_backup;
1351 int keyno;
1353 if (get_info_for_key_operation (&info))
1354 return;
1356 if (info.extcap.ki)
1358 char *answer;
1360 answer = cpr_get ("cardedit.genkeys.backup_enc",
1361 _("Make off-card backup of encryption key? (Y/n) "));
1363 want_backup = answer_is_yes_no_default (answer, 1/*(default to Yes)*/);
1364 cpr_kill_prompt ();
1365 xfree (answer);
1367 else
1368 want_backup = 0;
1370 if ( (info.fpr1valid && !fpr_is_zero (info.fpr1))
1371 || (info.fpr2valid && !fpr_is_zero (info.fpr2))
1372 || (info.fpr3valid && !fpr_is_zero (info.fpr3)))
1374 tty_printf ("\n");
1375 log_info (_("NOTE: keys are already stored on the card!\n"));
1376 tty_printf ("\n");
1377 if ( !cpr_get_answer_is_yes ("cardedit.genkeys.replace_keys",
1378 _("Replace existing keys? (y/N) ")))
1380 agent_release_card_info (&info);
1381 return;
1385 /* If no displayed name has been set, we assume that this is a fresh
1386 card and print a hint about the default PINs. */
1387 if (!info.disp_name || !*info.disp_name)
1389 tty_printf ("\n");
1390 tty_printf (_("Please note that the factory settings of the PINs are\n"
1391 " PIN = `%s' Admin PIN = `%s'\n"
1392 "You should change them using the command --change-pin\n"),
1393 "123456", "12345678");
1394 tty_printf ("\n");
1397 if (check_pin_for_key_operation (&info, &forced_chv1))
1398 goto leave;
1400 /* If the cards features changeable key attributes, we ask for the
1401 key size. */
1402 if (info.is_v2 && info.extcap.aac)
1404 unsigned int nbits;
1406 for (keyno = 0; keyno < DIM (info.key_attr); keyno++)
1408 nbits = ask_card_keysize (keyno, info.key_attr[keyno].nbits);
1409 if (nbits && do_change_keysize (keyno, nbits))
1411 /* Error: Better read the default key size again. */
1412 agent_release_card_info (&info);
1413 if (get_info_for_key_operation (&info))
1414 goto leave;
1415 /* Ask again for this key size. */
1416 keyno--;
1419 /* Note that INFO has not be synced. However we will only use
1420 the serialnumber and thus it won't harm. */
1423 generate_keypair (NULL, info.serialno, want_backup? opt.homedir:NULL);
1425 leave:
1426 agent_release_card_info (&info);
1427 restore_forced_chv1 (&forced_chv1);
1431 /* This function is used by the key edit menu to generate an arbitrary
1432 subkey. */
1434 card_generate_subkey (KBNODE pub_keyblock, KBNODE sec_keyblock)
1436 struct agent_card_info_s info;
1437 int okay = 0;
1438 int forced_chv1 = 0;
1439 int keyno;
1441 if (get_info_for_key_operation (&info))
1442 return 0;
1444 show_card_key_info (&info);
1446 tty_printf (_("Please select the type of key to generate:\n"));
1448 tty_printf (_(" (1) Signature key\n"));
1449 tty_printf (_(" (2) Encryption key\n"));
1450 tty_printf (_(" (3) Authentication key\n"));
1452 for (;;)
1454 char *answer = cpr_get ("cardedit.genkeys.subkeytype",
1455 _("Your selection? "));
1456 cpr_kill_prompt();
1457 if (*answer == CONTROL_D)
1459 xfree (answer);
1460 goto leave;
1462 keyno = *answer? atoi(answer): 0;
1463 xfree(answer);
1464 if (keyno >= 1 && keyno <= 3)
1465 break; /* Okay. */
1466 tty_printf(_("Invalid selection.\n"));
1469 if (replace_existing_key_p (&info, keyno))
1470 goto leave;
1472 if (check_pin_for_key_operation (&info, &forced_chv1))
1473 goto leave;
1475 /* If the cards features changeable key attributes, we ask for the
1476 key size. */
1477 if (info.is_v2 && info.extcap.aac)
1479 unsigned int nbits;
1481 ask_again:
1482 nbits = ask_card_keysize (keyno-1, info.key_attr[keyno-1].nbits);
1483 if (nbits && do_change_keysize (keyno-1, nbits))
1485 /* Error: Better read the default key size again. */
1486 agent_release_card_info (&info);
1487 if (get_info_for_key_operation (&info))
1488 goto leave;
1489 goto ask_again;
1491 /* Note that INFO has not be synced. However we will only use
1492 the serialnumber and thus it won't harm. */
1495 okay = generate_card_subkeypair (pub_keyblock, sec_keyblock,
1496 keyno, info.serialno);
1498 leave:
1499 agent_release_card_info (&info);
1500 restore_forced_chv1 (&forced_chv1);
1501 return okay;
1505 /* Store the key at NODE into the smartcard and modify NODE to
1506 carry the serialno stuff instead of the actual secret key
1507 parameters. USE is the usage for that key; 0 means any
1508 usage. */
1509 int
1510 card_store_subkey (KBNODE node, int use)
1512 struct agent_card_info_s info;
1513 int okay = 0;
1514 int rc;
1515 int keyno, i;
1516 PKT_secret_key *copied_sk = NULL;
1517 PKT_secret_key *sk;
1518 size_t n;
1519 const char *s;
1520 int allow_keyno[3];
1521 unsigned int nbits;
1524 assert (node->pkt->pkttype == PKT_SECRET_KEY
1525 || node->pkt->pkttype == PKT_SECRET_SUBKEY);
1526 sk = node->pkt->pkt.secret_key;
1528 if (get_info_for_key_operation (&info))
1529 return 0;
1531 if (!info.extcap.ki)
1533 tty_printf ("The card does not support the import of keys\n");
1534 tty_printf ("\n");
1535 goto leave;
1538 show_card_key_info (&info);
1540 nbits = nbits_from_sk (sk);
1542 if (!is_RSA (sk->pubkey_algo) || (!info.is_v2 && nbits != 1024) )
1544 tty_printf ("You may only store a 1024 bit RSA key on the card\n");
1545 tty_printf ("\n");
1546 goto leave;
1549 allow_keyno[0] = (!use || (use & (PUBKEY_USAGE_SIG)));
1550 allow_keyno[1] = (!use || (use & (PUBKEY_USAGE_ENC)));
1551 allow_keyno[2] = (!use || (use & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_AUTH)));
1553 tty_printf (_("Please select where to store the key:\n"));
1555 if (allow_keyno[0])
1556 tty_printf (_(" (1) Signature key\n"));
1557 if (allow_keyno[1])
1558 tty_printf (_(" (2) Encryption key\n"));
1559 if (allow_keyno[2])
1560 tty_printf (_(" (3) Authentication key\n"));
1562 for (;;)
1564 char *answer = cpr_get ("cardedit.genkeys.storekeytype",
1565 _("Your selection? "));
1566 cpr_kill_prompt();
1567 if (*answer == CONTROL_D || !*answer)
1569 xfree (answer);
1570 goto leave;
1572 keyno = *answer? atoi(answer): 0;
1573 xfree(answer);
1574 if (keyno >= 1 && keyno <= 3 && allow_keyno[keyno-1])
1576 if (info.is_v2 && !info.extcap.aac
1577 && info.key_attr[keyno-1].nbits != nbits)
1579 tty_printf ("Key does not match the card's capability.\n");
1581 else
1582 break; /* Okay. */
1584 else
1585 tty_printf(_("Invalid selection.\n"));
1588 if (replace_existing_key_p (&info, keyno))
1589 goto leave;
1591 /* Unprotect key. */
1592 switch (is_secret_key_protected (sk) )
1594 case 0: /* Not protected. */
1595 break;
1596 case -1:
1597 log_error (_("unknown key protection algorithm\n"));
1598 goto leave;
1599 default:
1600 if (sk->protect.s2k.mode == 1001)
1602 log_error (_("secret parts of key are not available\n"));
1603 goto leave;
1605 if (sk->protect.s2k.mode == 1002)
1607 log_error (_("secret key already stored on a card\n"));
1608 goto leave;
1610 /* We better copy the key before we unprotect it. */
1611 copied_sk = sk = copy_secret_key (NULL, sk);
1612 rc = check_secret_key (sk, 0);
1613 if (rc)
1614 goto leave;
1617 rc = save_unprotected_key_to_card (sk, keyno);
1618 if (rc)
1620 log_error (_("error writing key to card: %s\n"), gpg_strerror (rc));
1621 goto leave;
1624 /* Get back to the maybe protected original secret key. */
1625 if (copied_sk)
1627 free_secret_key (copied_sk);
1628 copied_sk = NULL;
1630 sk = node->pkt->pkt.secret_key;
1632 /* Get rid of the secret key parameters and store the serial numer. */
1633 n = pubkey_get_nskey (sk->pubkey_algo);
1634 for (i=pubkey_get_npkey (sk->pubkey_algo); i < n; i++)
1636 gcry_mpi_release (sk->skey[i]);
1637 sk->skey[i] = NULL;
1639 i = pubkey_get_npkey (sk->pubkey_algo);
1640 sk->skey[i] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
1641 sk->is_protected = 1;
1642 sk->protect.s2k.mode = 1002;
1643 s = info.serialno;
1644 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
1645 sk->protect.ivlen++, s += 2)
1646 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
1648 okay = 1;
1650 leave:
1651 if (copied_sk)
1652 free_secret_key (copied_sk);
1653 agent_release_card_info (&info);
1654 return okay;
1659 /* Data used by the command parser. This needs to be outside of the
1660 function scope to allow readline based command completion. */
1661 enum cmdids
1663 cmdNOP = 0,
1664 cmdQUIT, cmdADMIN, cmdHELP, cmdLIST, cmdDEBUG, cmdVERIFY,
1665 cmdNAME, cmdURL, cmdFETCH, cmdLOGIN, cmdLANG, cmdSEX, cmdCAFPR,
1666 cmdFORCESIG, cmdGENERATE, cmdPASSWD, cmdPRIVATEDO, cmdWRITECERT,
1667 cmdREADCERT, cmdUNBLOCK,
1668 cmdINVCMD
1671 static struct
1673 const char *name;
1674 enum cmdids id;
1675 int admin_only;
1676 const char *desc;
1677 } cmds[] =
1679 { "quit" , cmdQUIT , 0, N_("quit this menu")},
1680 { "q" , cmdQUIT , 0, NULL },
1681 { "admin" , cmdADMIN , 0, N_("show admin commands")},
1682 { "help" , cmdHELP , 0, N_("show this help")},
1683 { "?" , cmdHELP , 0, NULL },
1684 { "list" , cmdLIST , 0, N_("list all available data")},
1685 { "l" , cmdLIST , 0, NULL },
1686 { "debug" , cmdDEBUG , 0, NULL },
1687 { "name" , cmdNAME , 1, N_("change card holder's name")},
1688 { "url" , cmdURL , 1, N_("change URL to retrieve key")},
1689 { "fetch" , cmdFETCH , 0, N_("fetch the key specified in the card URL")},
1690 { "login" , cmdLOGIN , 1, N_("change the login name")},
1691 { "lang" , cmdLANG , 1, N_("change the language preferences")},
1692 { "sex" , cmdSEX , 1, N_("change card holder's sex")},
1693 { "cafpr" , cmdCAFPR , 1, N_("change a CA fingerprint")},
1694 { "forcesig", cmdFORCESIG, 1, N_("toggle the signature force PIN flag")},
1695 { "generate", cmdGENERATE, 1, N_("generate new keys")},
1696 { "passwd" , cmdPASSWD, 0, N_("menu to change or unblock the PIN")},
1697 { "verify" , cmdVERIFY, 0, N_("verify the PIN and list all data")},
1698 { "unblock" , cmdUNBLOCK,0, N_("unblock the PIN using a Reset Code") },
1699 /* Note, that we do not announce these command yet. */
1700 { "privatedo", cmdPRIVATEDO, 0, NULL },
1701 { "readcert", cmdREADCERT, 0, NULL },
1702 { "writecert", cmdWRITECERT, 1, NULL },
1703 { NULL, cmdINVCMD, 0, NULL }
1707 #ifdef HAVE_LIBREADLINE
1709 /* These two functions are used by readline for command completion. */
1711 static char *
1712 command_generator(const char *text,int state)
1714 static int list_index,len;
1715 const char *name;
1717 /* If this is a new word to complete, initialize now. This includes
1718 saving the length of TEXT for efficiency, and initializing the
1719 index variable to 0. */
1720 if(!state)
1722 list_index=0;
1723 len=strlen(text);
1726 /* Return the next partial match */
1727 while((name=cmds[list_index].name))
1729 /* Only complete commands that have help text */
1730 if(cmds[list_index++].desc && strncmp(name,text,len)==0)
1731 return strdup(name);
1734 return NULL;
1737 static char **
1738 card_edit_completion(const char *text, int start, int end)
1740 (void)end;
1741 /* If we are at the start of a line, we try and command-complete.
1742 If not, just do nothing for now. */
1744 if(start==0)
1745 return rl_completion_matches(text,command_generator);
1747 rl_attempted_completion_over=1;
1749 return NULL;
1751 #endif /*HAVE_LIBREADLINE*/
1753 /* Menu to edit all user changeable values on an OpenPGP card. Only
1754 Key creation is not handled here. */
1755 void
1756 card_edit (strlist_t commands)
1758 enum cmdids cmd = cmdNOP;
1759 int have_commands = !!commands;
1760 int redisplay = 1;
1761 char *answer = NULL;
1762 int allow_admin=0;
1763 char serialnobuf[50];
1766 if (opt.command_fd != -1)
1768 else if (opt.batch && !have_commands)
1770 log_error(_("can't do this in batch mode\n"));
1771 goto leave;
1774 for (;;)
1776 int arg_number;
1777 const char *arg_string = "";
1778 const char *arg_rest = "";
1779 char *p;
1780 int i;
1781 int cmd_admin_only;
1783 tty_printf("\n");
1784 if (redisplay )
1786 if (opt.with_colons)
1788 card_status (stdout, serialnobuf, DIM (serialnobuf));
1789 fflush (stdout);
1791 else
1793 card_status (NULL, serialnobuf, DIM (serialnobuf));
1794 tty_printf("\n");
1796 redisplay = 0;
1801 xfree (answer);
1802 if (have_commands)
1804 if (commands)
1806 answer = xstrdup (commands->d);
1807 commands = commands->next;
1809 else if (opt.batch)
1811 answer = xstrdup ("quit");
1813 else
1814 have_commands = 0;
1817 if (!have_commands)
1819 tty_enable_completion (card_edit_completion);
1820 answer = cpr_get_no_help("cardedit.prompt", _("Command> "));
1821 cpr_kill_prompt();
1822 tty_disable_completion ();
1824 trim_spaces(answer);
1826 while ( *answer == '#' );
1828 arg_number = 0; /* Yes, here is the init which egcc complains about */
1829 cmd_admin_only = 0;
1830 if (!*answer)
1831 cmd = cmdLIST; /* Default to the list command */
1832 else if (*answer == CONTROL_D)
1833 cmd = cmdQUIT;
1834 else
1836 if ((p=strchr (answer,' ')))
1838 *p++ = 0;
1839 trim_spaces (answer);
1840 trim_spaces (p);
1841 arg_number = atoi(p);
1842 arg_string = p;
1843 arg_rest = p;
1844 while (digitp (arg_rest))
1845 arg_rest++;
1846 while (spacep (arg_rest))
1847 arg_rest++;
1850 for (i=0; cmds[i].name; i++ )
1851 if (!ascii_strcasecmp (answer, cmds[i].name ))
1852 break;
1854 cmd = cmds[i].id;
1855 cmd_admin_only = cmds[i].admin_only;
1858 if (!allow_admin && cmd_admin_only)
1860 tty_printf ("\n");
1861 tty_printf (_("Admin-only command\n"));
1862 continue;
1865 switch (cmd)
1867 case cmdHELP:
1868 for (i=0; cmds[i].name; i++ )
1869 if(cmds[i].desc
1870 && (!cmds[i].admin_only || (cmds[i].admin_only && allow_admin)))
1871 tty_printf("%-10s %s\n", cmds[i].name, _(cmds[i].desc) );
1872 break;
1874 case cmdADMIN:
1875 if ( !strcmp (arg_string, "on") )
1876 allow_admin = 1;
1877 else if ( !strcmp (arg_string, "off") )
1878 allow_admin = 0;
1879 else if ( !strcmp (arg_string, "verify") )
1881 /* Force verification of the Admin Command. However,
1882 this is only done if the retry counter is at initial
1883 state. */
1884 char *tmp = xmalloc (strlen (serialnobuf) + 6 + 1);
1885 strcpy (stpcpy (tmp, serialnobuf), "[CHV3]");
1886 allow_admin = !agent_scd_checkpin (tmp);
1887 xfree (tmp);
1889 else /* Toggle. */
1890 allow_admin=!allow_admin;
1891 if(allow_admin)
1892 tty_printf(_("Admin commands are allowed\n"));
1893 else
1894 tty_printf(_("Admin commands are not allowed\n"));
1895 break;
1897 case cmdVERIFY:
1898 agent_scd_checkpin (serialnobuf);
1899 redisplay = 1;
1900 break;
1902 case cmdLIST:
1903 redisplay = 1;
1904 break;
1906 case cmdNAME:
1907 change_name ();
1908 break;
1910 case cmdURL:
1911 change_url ();
1912 break;
1914 case cmdFETCH:
1915 fetch_url();
1916 break;
1918 case cmdLOGIN:
1919 change_login (arg_string);
1920 break;
1922 case cmdLANG:
1923 change_lang ();
1924 break;
1926 case cmdSEX:
1927 change_sex ();
1928 break;
1930 case cmdCAFPR:
1931 if ( arg_number < 1 || arg_number > 3 )
1932 tty_printf ("usage: cafpr N\n"
1933 " 1 <= N <= 3\n");
1934 else
1935 change_cafpr (arg_number);
1936 break;
1938 case cmdPRIVATEDO:
1939 if ( arg_number < 1 || arg_number > 4 )
1940 tty_printf ("usage: privatedo N\n"
1941 " 1 <= N <= 4\n");
1942 else
1943 change_private_do (arg_string, arg_number);
1944 break;
1946 case cmdWRITECERT:
1947 if ( arg_number != 3 )
1948 tty_printf ("usage: writecert 3 < FILE\n");
1949 else
1950 change_cert (arg_rest);
1951 break;
1953 case cmdREADCERT:
1954 if ( arg_number != 3 )
1955 tty_printf ("usage: readcert 3 > FILE\n");
1956 else
1957 read_cert (arg_rest);
1958 break;
1960 case cmdFORCESIG:
1961 toggle_forcesig ();
1962 break;
1964 case cmdGENERATE:
1965 generate_card_keys ();
1966 break;
1968 case cmdPASSWD:
1969 change_pin (0, allow_admin);
1970 break;
1972 case cmdUNBLOCK:
1973 change_pin (1, allow_admin);
1974 break;
1976 case cmdQUIT:
1977 goto leave;
1979 case cmdNOP:
1980 break;
1982 case cmdINVCMD:
1983 default:
1984 tty_printf ("\n");
1985 tty_printf (_("Invalid command (try \"help\")\n"));
1986 break;
1987 } /* End command switch. */
1988 } /* End of main menu loop. */
1990 leave:
1991 xfree (answer);