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
4 *
5 * This file is part of GnuPG.
6 *
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.
11 *
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.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <https://www.gnu.org/licenses/>.
19 */
20
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #ifdef HAVE_LIBREADLINE
27 # define GNUPG_LIBREADLINE_H_INCLUDED
28 # include <readline/readline.h>
29 #endif /*HAVE_LIBREADLINE*/
30
31 #if GNUPG_MAJOR_VERSION != 1
32 # include "gpg.h"
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"
38 #include "options.h"
39 #include "main.h"
40 #include "keyserver-internal.h"
41
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*/
47
48 #define CONTROL_D ('D' - 'A' + 1)
49
50
51 static void
write_sc_op_status(gpg_error_t err)52 write_sc_op_status (gpg_error_t err)
53 {
54 switch (gpg_err_code (err))
55 {
56 case 0:
57 write_status (STATUS_SC_OP_SUCCESS);
58 break;
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");
63 break;
64 case GPG_ERR_BAD_PIN:
65 write_status_text (STATUS_SC_OP_FAILURE, "2");
66 break;
67 default:
68 write_status (STATUS_SC_OP_FAILURE);
69 break;
70 #endif /* GNUPG_MAJOR_VERSION != 1 */
71 }
72 }
73
74
75 /* Change the PIN of an OpenPGP card. This is an interactive
76 function. */
77 void
change_pin(int unblock_v2,int allow_admin)78 change_pin (int unblock_v2, int allow_admin)
79 {
80 struct agent_card_info_s info;
81 int rc;
82
83 rc = agent_scd_learn (&info, 0);
84 if (rc)
85 {
86 log_error (_("OpenPGP card not available: %s\n"),
87 gpg_strerror (rc));
88 return;
89 }
90
91 log_info (_("OpenPGP card no. %s detected\n"),
92 info.serialno? info.serialno : "[none]");
93
94 if (opt.batch)
95 {
96 agent_release_card_info (&info);
97 log_error (_("can't do this in batch mode\n"));
98 return;
99 }
100
101
102 if (unblock_v2)
103 {
104 if (!info.is_v2)
105 log_error (_("This command is only available for version 2 cards\n"));
106 else if (!info.chvretry[1])
107 log_error (_("Reset Code not or not anymore available\n"));
108 else
109 {
110 rc = agent_scd_change_pin (2, info.serialno);
111 write_sc_op_status (rc);
112 if (rc)
113 tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc));
114 else
115 tty_printf ("PIN changed.\n");
116 }
117 }
118 else if (!allow_admin)
119 {
120 rc = agent_scd_change_pin (1, info.serialno);
121 write_sc_op_status (rc);
122 if (rc)
123 tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc));
124 else
125 tty_printf ("PIN changed.\n");
126 }
127 else
128 for (;;)
129 {
130 char *answer;
131
132 tty_printf ("\n");
133 tty_printf ("1 - change PIN\n"
134 "2 - unblock PIN\n"
135 "3 - change Admin PIN\n"
136 "4 - set the Reset Code\n"
137 "Q - quit\n");
138 tty_printf ("\n");
139
140 answer = cpr_get("cardutil.change_pin.menu",_("Your selection? "));
141 cpr_kill_prompt();
142 if (strlen (answer) != 1)
143 {
144 xfree (answer);
145 continue;
146 }
147
148 if (*answer == '1')
149 {
150 /* Change PIN. */
151 rc = agent_scd_change_pin (1, info.serialno);
152 write_sc_op_status (rc);
153 if (rc)
154 tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc));
155 else
156 tty_printf ("PIN changed.\n");
157 }
158 else if (*answer == '2')
159 {
160 /* Unblock PIN. */
161 rc = agent_scd_change_pin (101, info.serialno);
162 write_sc_op_status (rc);
163 if (rc)
164 tty_printf ("Error unblocking the PIN: %s\n", gpg_strerror (rc));
165 else
166 tty_printf ("PIN unblocked and new PIN set.\n");
167 }
168 else if (*answer == '3')
169 {
170 /* Change Admin PIN. */
171 rc = agent_scd_change_pin (3, info.serialno);
172 write_sc_op_status (rc);
173 if (rc)
174 tty_printf ("Error changing the PIN: %s\n", gpg_strerror (rc));
175 else
176 tty_printf ("PIN changed.\n");
177 }
178 else if (*answer == '4')
179 {
180 /* Set a new Reset Code. */
181 rc = agent_scd_change_pin (102, info.serialno);
182 write_sc_op_status (rc);
183 if (rc)
184 tty_printf ("Error setting the Reset Code: %s\n",
185 gpg_strerror (rc));
186 else
187 tty_printf ("Reset Code set.\n");
188 }
189 else if (*answer == 'q' || *answer == 'Q')
190 {
191 xfree (answer);
192 break;
193 }
194 xfree (answer);
195 }
196
197 agent_release_card_info (&info);
198 }
199
200
201 static void
print_shax_fpr(estream_t fp,const unsigned char * fpr,unsigned int fprlen)202 print_shax_fpr (estream_t fp, const unsigned char *fpr, unsigned int fprlen)
203 {
204 int i;
205
206 if (fpr)
207 {
208 /* FIXME: Fix formatting for FPRLEN != 20 */
209 for (i=0; i < fprlen ; i+=2, fpr += 2 )
210 {
211 if (i == 10 )
212 tty_fprintf (fp, " ");
213 tty_fprintf (fp, " %02X%02X", *fpr, fpr[1]);
214 }
215 }
216 else
217 tty_fprintf (fp, " [none]");
218 tty_fprintf (fp, "\n");
219 }
220
221
222 static void
print_shax_fpr_colon(estream_t fp,const unsigned char * fpr,unsigned int fprlen)223 print_shax_fpr_colon (estream_t fp,
224 const unsigned char *fpr, unsigned int fprlen)
225 {
226 int i;
227
228 if (fpr)
229 {
230 for (i=0; i < fprlen ; i++, fpr++)
231 es_fprintf (fp, "%02X", *fpr);
232 }
233 es_putc (':', fp);
234 }
235
236
237 static void
print_keygrip(estream_t fp,const unsigned char * grp)238 print_keygrip (estream_t fp, const unsigned char *grp)
239 {
240 int i;
241
242 if (opt.with_keygrip)
243 {
244 tty_fprintf (fp, " keygrip ....: ");
245 for (i=0; i < 20 ; i++, grp++)
246 tty_fprintf (fp, "%02X", *grp);
247 tty_fprintf (fp, "\n");
248 }
249 }
250
251
252 static void
print_name(estream_t fp,const char * text,const char * name)253 print_name (estream_t fp, const char *text, const char *name)
254 {
255 tty_fprintf (fp, "%s", text);
256
257 /* FIXME: tty_printf_utf8_string2 eats everything after and
258 including an @ - e.g. when printing an url. */
259 if (name && *name)
260 {
261 if (fp)
262 print_utf8_buffer2 (fp, name, strlen (name), '\n');
263 else
264 tty_print_utf8_string2 (NULL, name, strlen (name), 0);
265 }
266 else
267 tty_fprintf (fp, _("[not set]"));
268 tty_fprintf (fp, "\n");
269 }
270
271 static void
print_isoname(estream_t fp,const char * text,const char * tag,const char * name)272 print_isoname (estream_t fp, const char *text,
273 const char *tag, const char *name)
274 {
275 if (opt.with_colons)
276 es_fprintf (fp, "%s:", tag);
277 else
278 tty_fprintf (fp, "%s", text);
279
280 if (name && *name)
281 {
282 char *p, *given, *buf = xstrdup (name);
283
284 given = strstr (buf, "<<");
285 for (p=buf; *p; p++)
286 if (*p == '<')
287 *p = ' ';
288 if (given && given[2])
289 {
290 *given = 0;
291 given += 2;
292 if (opt.with_colons)
293 es_write_sanitized (fp, given, strlen (given), ":", NULL);
294 else if (fp)
295 print_utf8_buffer2 (fp, given, strlen (given), '\n');
296 else
297 tty_print_utf8_string2 (NULL, given, strlen (given), 0);
298
299 if (opt.with_colons)
300 es_putc (':', fp);
301 else if (*buf)
302 tty_fprintf (fp, " ");
303 }
304
305 if (opt.with_colons)
306 es_write_sanitized (fp, buf, strlen (buf), ":", NULL);
307 else if (fp)
308 print_utf8_buffer2 (fp, buf, strlen (buf), '\n');
309 else
310 tty_print_utf8_string2 (NULL, buf, strlen (buf), 0);
311 xfree (buf);
312 }
313 else
314 {
315 if (opt.with_colons)
316 es_putc (':', fp);
317 else
318 tty_fprintf (fp, _("[not set]"));
319 }
320
321 if (opt.with_colons)
322 es_fputs (":\n", fp);
323 else
324 tty_fprintf (fp, "\n");
325 }
326
327 /* Return true if the SHA1 fingerprint FPR consists only of zeroes. */
328 static int
fpr_is_zero(const char * fpr,unsigned int fprlen)329 fpr_is_zero (const char *fpr, unsigned int fprlen)
330 {
331 int i;
332
333 for (i=0; i < fprlen && !fpr[i]; i++)
334 ;
335 return (i == fprlen);
336 }
337
338
339 /* Return true if the fingerprint FPR consists only of 0xFF. */
340 static int
fpr_is_ff(const char * fpr,unsigned int fprlen)341 fpr_is_ff (const char *fpr, unsigned int fprlen)
342 {
343 int i;
344
345 for (i=0; i < fprlen && fpr[i] == '\xff'; i++)
346 ;
347 return (i == fprlen);
348 }
349
350
351 /* Print all available information about the current card. */
352 static void
current_card_status(ctrl_t ctrl,estream_t fp,char * serialno,size_t serialnobuflen)353 current_card_status (ctrl_t ctrl, estream_t fp,
354 char *serialno, size_t serialnobuflen)
355 {
356 struct agent_card_info_s info;
357 PKT_public_key *pk = xcalloc (1, sizeof *pk);
358 kbnode_t keyblock = NULL;
359 int rc;
360 unsigned int uval;
361 const unsigned char *thefpr;
362 unsigned int thefprlen;
363 int i;
364 char *pesc;
365
366 if (serialno && serialnobuflen)
367 *serialno = 0;
368
369 rc = agent_scd_learn (&info, 0);
370 if (rc)
371 {
372 if (opt.with_colons)
373 es_fputs ("AID:::\n", fp);
374 log_error (_("OpenPGP card not available: %s\n"), gpg_strerror (rc));
375 xfree (pk);
376 return;
377 }
378
379 if (opt.with_colons)
380 es_fprintf (fp, "Reader:%s:", info.reader? info.reader : "");
381 else
382 tty_fprintf (fp, "Reader ...........: %s\n",
383 info.reader? info.reader : "[none]");
384 if (opt.with_colons)
385 es_fprintf (fp, "AID:%s:", info.serialno? info.serialno : "");
386 else
387 tty_fprintf (fp, "Application ID ...: %s\n",
388 info.serialno? info.serialno : "[none]");
389 if (!info.serialno || strncmp (info.serialno, "D27600012401", 12)
390 || strlen (info.serialno) != 32 )
391 {
392 const char *name1, *name2;
393 if (info.apptype && !strcmp (info.apptype, "openpgp"))
394 goto openpgp;
395 else if (info.apptype && !strcmp (info.apptype, "NKS"))
396 {
397 name1 = "netkey";
398 name2 = "NetKey";
399 }
400 else if (info.apptype && !strcmp (info.apptype, "DINSIG"))
401 {
402 name1 = "dinsig";
403 name2 = "DINSIG";
404 }
405 else if (info.apptype && !strcmp (info.apptype, "P15"))
406 {
407 name1 = "pkcs15";
408 name2 = "PKCS#15";
409 }
410 else if (info.apptype && !strcmp (info.apptype, "GELDKARTE"))
411 {
412 name1 = "geldkarte";
413 name2 = "Geldkarte";
414 }
415 else if (info.apptype && !strcmp (info.apptype, "PIV"))
416 {
417 name1 = "piv";
418 name2 = "PIV";
419 }
420 else
421 {
422 name1 = "unknown";
423 name2 = "Unknown";
424 }
425
426 if (opt.with_colons)
427 es_fprintf (fp, "%s-card:\n", name1);
428 else
429 tty_fprintf (fp, "Application type .: %s\n", name2);
430
431 agent_release_card_info (&info);
432 xfree (pk);
433 return;
434 }
435 openpgp:
436 if (!serialno)
437 ;
438 else if (strlen (info.serialno)+1 > serialnobuflen)
439 log_error ("serial number longer than expected\n");
440 else
441 strcpy (serialno, info.serialno);
442
443 if (opt.with_colons)
444 es_fputs ("openpgp-card:\n", fp);
445 else
446 tty_fprintf (fp, "Application type .: %s\n", "OpenPGP");
447
448
449 if (opt.with_colons)
450 {
451 es_fprintf (fp, "version:%.4s:\n", info.serialno+12);
452 uval = xtoi_2(info.serialno+16)*256 + xtoi_2 (info.serialno+18);
453 pesc = (info.manufacturer_name
454 ? percent_escape (info.manufacturer_name, NULL) : NULL);
455 es_fprintf (fp, "vendor:%04x:%s:\n", uval, pesc? pesc:"");
456 xfree (pesc);
457 es_fprintf (fp, "serial:%.8s:\n", info.serialno+20);
458
459 print_isoname (fp, "Name of cardholder: ", "name", info.disp_name);
460
461 es_fputs ("lang:", fp);
462 if (info.disp_lang)
463 es_write_sanitized (fp, info.disp_lang, strlen (info.disp_lang),
464 ":", NULL);
465 es_fputs (":\n", fp);
466
467 es_fprintf (fp, "sex:%c:\n", (info.disp_sex == 1? 'm':
468 info.disp_sex == 2? 'f' : 'u'));
469
470 es_fputs ("url:", fp);
471 if (info.pubkey_url)
472 es_write_sanitized (fp, info.pubkey_url, strlen (info.pubkey_url),
473 ":", NULL);
474 es_fputs (":\n", fp);
475
476 es_fputs ("login:", fp);
477 if (info.login_data)
478 es_write_sanitized (fp, info.login_data, strlen (info.login_data),
479 ":", NULL);
480 es_fputs (":\n", fp);
481
482 es_fprintf (fp, "forcepin:%d:::\n", !info.chv1_cached);
483 for (i=0; i < DIM (info.key_attr); i++)
484 if (info.key_attr[i].algo == PUBKEY_ALGO_RSA)
485 es_fprintf (fp, "keyattr:%d:%d:%u:\n", i+1,
486 info.key_attr[i].algo, info.key_attr[i].nbits);
487 else if (info.key_attr[i].algo == PUBKEY_ALGO_ECDH
488 || info.key_attr[i].algo == PUBKEY_ALGO_ECDSA
489 || info.key_attr[i].algo == PUBKEY_ALGO_EDDSA)
490 es_fprintf (fp, "keyattr:%d:%d:%s:\n", i+1,
491 info.key_attr[i].algo, info.key_attr[i].curve);
492 es_fprintf (fp, "maxpinlen:%d:%d:%d:\n",
493 info.chvmaxlen[0], info.chvmaxlen[1], info.chvmaxlen[2]);
494 es_fprintf (fp, "pinretry:%d:%d:%d:\n",
495 info.chvretry[0], info.chvretry[1], info.chvretry[2]);
496 es_fprintf (fp, "sigcount:%lu:::\n", info.sig_counter);
497 if (info.extcap.kdf)
498 {
499 const char *setup;
500
501 if (info.kdf_do_enabled == 0)
502 setup = "off";
503 else if (info.kdf_do_enabled == 1)
504 setup = "single";
505 else
506 setup = "on";
507
508 es_fprintf (fp, "kdf:%s:\n", setup);
509 }
510 if (info.extcap.bt)
511 {
512 es_fprintf (fp, "uif:%d:%d:%d:\n",
513 info.uif[0], info.uif[1], info.uif[2]);
514 }
515
516 for (i=0; i < 4; i++)
517 {
518 if (info.private_do[i])
519 {
520 es_fprintf (fp, "private_do:%d:", i+1);
521 es_write_sanitized (fp, info.private_do[i],
522 strlen (info.private_do[i]), ":", NULL);
523 es_fputs (":\n", fp);
524 }
525 }
526
527 es_fputs ("cafpr:", fp);
528 print_shax_fpr_colon (fp, info.cafpr1len? info.cafpr1:NULL,
529 info.cafpr2len);
530 print_shax_fpr_colon (fp, info.cafpr2len? info.cafpr2:NULL,
531 info.cafpr2len);
532 print_shax_fpr_colon (fp, info.cafpr3len? info.cafpr3:NULL,
533 info.cafpr3len);
534 es_putc ('\n', fp);
535 es_fputs ("fpr:", fp);
536 print_shax_fpr_colon (fp, info.fpr1len? info.fpr1:NULL, info.fpr1len);
537 print_shax_fpr_colon (fp, info.fpr2len? info.fpr2:NULL, info.fpr2len);
538 print_shax_fpr_colon (fp, info.fpr3len? info.fpr3:NULL, info.fpr3len);
539 es_putc ('\n', fp);
540 es_fprintf (fp, "fprtime:%lu:%lu:%lu:\n",
541 (unsigned long)info.fpr1time, (unsigned long)info.fpr2time,
542 (unsigned long)info.fpr3time);
543 es_fputs ("grp:", fp);
544 print_shax_fpr_colon (fp, info.grp1, sizeof info.grp1);
545 print_shax_fpr_colon (fp, info.grp2, sizeof info.grp2);
546 print_shax_fpr_colon (fp, info.grp3, sizeof info.grp3);
547 es_putc ('\n', fp);
548 }
549 else
550 {
551 tty_fprintf (fp, "Version ..........: %.1s%c.%.1s%c\n",
552 info.serialno[12] == '0'?"":info.serialno+12,
553 info.serialno[13],
554 info.serialno[14] == '0'?"":info.serialno+14,
555 info.serialno[15]);
556 tty_fprintf (fp, "Manufacturer .....: %s\n",
557 info.manufacturer_name? info.manufacturer_name : "?");
558 tty_fprintf (fp, "Serial number ....: %.8s\n", info.serialno+20);
559
560 print_isoname (fp, "Name of cardholder: ", "name", info.disp_name);
561 print_name (fp, "Language prefs ...: ", info.disp_lang);
562 tty_fprintf (fp, "Salutation .......: %s\n",
563 info.disp_sex == 1? _("Mr."):
564 info.disp_sex == 2? _("Ms.") : "");
565 print_name (fp, "URL of public key : ", info.pubkey_url);
566 print_name (fp, "Login data .......: ", info.login_data);
567 if (info.private_do[0])
568 print_name (fp, "Private DO 1 .....: ", info.private_do[0]);
569 if (info.private_do[1])
570 print_name (fp, "Private DO 2 .....: ", info.private_do[1]);
571 if (info.private_do[2])
572 print_name (fp, "Private DO 3 .....: ", info.private_do[2]);
573 if (info.private_do[3])
574 print_name (fp, "Private DO 4 .....: ", info.private_do[3]);
575 if (info.cafpr1len)
576 {
577 tty_fprintf (fp, "CA fingerprint %d .:", 1);
578 print_shax_fpr (fp, info.cafpr1, info.cafpr1len);
579 }
580 if (info.cafpr2len)
581 {
582 tty_fprintf (fp, "CA fingerprint %d .:", 2);
583 print_shax_fpr (fp, info.cafpr2, info.cafpr2len);
584 }
585 if (info.cafpr3len)
586 {
587 tty_fprintf (fp, "CA fingerprint %d .:", 3);
588 print_shax_fpr (fp, info.cafpr3, info.cafpr3len);
589 }
590 tty_fprintf (fp, "Signature PIN ....: %s\n",
591 info.chv1_cached? _("not forced"): _("forced"));
592 if (info.key_attr[0].algo)
593 {
594 tty_fprintf (fp, "Key attributes ...:");
595 for (i=0; i < DIM (info.key_attr); i++)
596 if (info.key_attr[i].algo == PUBKEY_ALGO_RSA)
597 tty_fprintf (fp, " rsa%u", info.key_attr[i].nbits);
598 else if (info.key_attr[i].algo == PUBKEY_ALGO_ECDH
599 || info.key_attr[i].algo == PUBKEY_ALGO_ECDSA
600 || info.key_attr[i].algo == PUBKEY_ALGO_EDDSA)
601 {
602 const char *curve_for_print = "?";
603
604 if (info.key_attr[i].curve)
605 {
606 const char *oid;
607 oid = openpgp_curve_to_oid (info.key_attr[i].curve,
608 NULL, NULL);
609 if (oid)
610 curve_for_print = openpgp_oid_to_curve (oid, 0);
611 }
612 tty_fprintf (fp, " %s", curve_for_print);
613 }
614 tty_fprintf (fp, "\n");
615 }
616 tty_fprintf (fp, "Max. PIN lengths .: %d %d %d\n",
617 info.chvmaxlen[0], info.chvmaxlen[1], info.chvmaxlen[2]);
618 tty_fprintf (fp, "PIN retry counter : %d %d %d\n",
619 info.chvretry[0], info.chvretry[1], info.chvretry[2]);
620 tty_fprintf (fp, "Signature counter : %lu\n", info.sig_counter);
621 if (info.extcap.kdf)
622 {
623 const char *setup;
624
625 if (info.kdf_do_enabled == 0)
626 setup = "off";
627 else if (info.kdf_do_enabled == 1)
628 setup = "single";
629 else
630 setup = "on";
631
632 tty_fprintf (fp, "KDF setting ......: %s\n", setup);
633 }
634 if (info.extcap.bt)
635 {
636 tty_fprintf (fp, "UIF setting ......: Sign=%s Decrypt=%s Auth=%s\n",
637 info.uif[0] ? "on" : "off", info.uif[1] ? "on" : "off",
638 info.uif[2] ? "on" : "off");
639 }
640 tty_fprintf (fp, "Signature key ....:");
641 print_shax_fpr (fp, info.fpr1len? info.fpr1:NULL, info.fpr1len);
642 if (info.fpr1len && info.fpr1time)
643 {
644 tty_fprintf (fp, " created ....: %s\n",
645 isotimestamp (info.fpr1time));
646 print_keygrip (fp, info.grp1);
647 }
648 tty_fprintf (fp, "Encryption key....:");
649 print_shax_fpr (fp, info.fpr2len? info.fpr2:NULL, info.fpr2len);
650 if (info.fpr2len && info.fpr2time)
651 {
652 tty_fprintf (fp, " created ....: %s\n",
653 isotimestamp (info.fpr2time));
654 print_keygrip (fp, info.grp2);
655 }
656 tty_fprintf (fp, "Authentication key:");
657 print_shax_fpr (fp, info.fpr3len? info.fpr3:NULL, info.fpr3len);
658 if (info.fpr3len && info.fpr3time)
659 {
660 tty_fprintf (fp, " created ....: %s\n",
661 isotimestamp (info.fpr3time));
662 print_keygrip (fp, info.grp3);
663 }
664 tty_fprintf (fp, "General key info..: ");
665
666 thefpr = (info.fpr1len? info.fpr1 : info.fpr2len? info.fpr2 :
667 info.fpr3len? info.fpr3 : NULL);
668 thefprlen = (info.fpr1len? info.fpr1len : info.fpr2len? info.fpr2len :
669 info.fpr3len? info.fpr3len : 0);
670 /* If the fingerprint is all 0xff, the key has no associated
671 OpenPGP certificate. */
672 if ( thefpr && !fpr_is_ff (thefpr, thefprlen)
673 && !get_pubkey_byfprint (ctrl, pk, &keyblock, thefpr, thefprlen))
674 {
675 print_key_info (ctrl, fp, 0, pk, 0);
676 print_card_key_info (fp, keyblock);
677 }
678 else
679 tty_fprintf (fp, "[none]\n");
680 }
681
682 release_kbnode (keyblock);
683 free_public_key (pk);
684 agent_release_card_info (&info);
685 }
686
687
688 /* Print all available information for specific card with SERIALNO.
689 Print all available information for current card when SERIALNO is NULL.
690 Or print for all cards when SERIALNO is "all". */
691 void
card_status(ctrl_t ctrl,estream_t fp,const char * serialno)692 card_status (ctrl_t ctrl, estream_t fp, const char *serialno)
693 {
694 int err;
695 strlist_t card_list, sl;
696 char *serialno0 = NULL;
697 int all_cards = 0;
698 int any_card = 0;
699
700 if (serialno == NULL)
701 {
702 current_card_status (ctrl, fp, NULL, 0);
703 return;
704 }
705
706 if (!strcmp (serialno, "all"))
707 all_cards = 1;
708
709 err = agent_scd_serialno (&serialno0, NULL);
710 if (err)
711 {
712 if (gpg_err_code (err) != GPG_ERR_ENODEV && opt.verbose)
713 log_info (_("error getting serial number of card: %s\n"),
714 gpg_strerror (err));
715 /* Nothing available. */
716 return;
717 }
718
719 err = agent_scd_cardlist (&card_list);
720
721 for (sl = card_list; sl; sl = sl->next)
722 {
723 if (!all_cards && strcmp (serialno, sl->d))
724 continue;
725
726 if (any_card && !opt.with_colons)
727 tty_fprintf (fp, "\n");
728 any_card = 1;
729
730 err = agent_scd_serialno (NULL, sl->d);
731 if (err)
732 {
733 if (opt.verbose)
734 log_info (_("error getting serial number of card: %s\n"),
735 gpg_strerror (err));
736 continue;
737 }
738
739 current_card_status (ctrl, fp, NULL, 0);
740
741 if (!all_cards)
742 goto leave;
743 }
744
745 /* Select the original card again. */
746 err = agent_scd_serialno (NULL, serialno0);
747
748 leave:
749 xfree (serialno0);
750 free_strlist (card_list);
751 }
752
753
754 static char *
get_one_name(const char * prompt1,const char * prompt2)755 get_one_name (const char *prompt1, const char *prompt2)
756 {
757 char *name;
758 int i;
759
760 for (;;)
761 {
762 name = cpr_get (prompt1, prompt2);
763 if (!name)
764 return NULL;
765 trim_spaces (name);
766 cpr_kill_prompt ();
767 for (i=0; name[i] && name[i] >= ' ' && name[i] <= 126; i++)
768 ;
769
770 /* The name must be in Latin-1 and not UTF-8 - lacking the code
771 to ensure this we restrict it to ASCII. */
772 if (name[i])
773 tty_printf (_("Error: Only plain ASCII is currently allowed.\n"));
774 else if (strchr (name, '<'))
775 tty_printf (_("Error: The \"<\" character may not be used.\n"));
776 else if (strstr (name, " "))
777 tty_printf (_("Error: Double spaces are not allowed.\n"));
778 else
779 return name;
780 xfree (name);
781 }
782 }
783
784
785
786 static int
change_name(void)787 change_name (void)
788 {
789 char *surname = NULL, *givenname = NULL;
790 char *isoname = NULL;
791 char *p;
792 int rc;
793
794 surname = get_one_name ("keygen.smartcard.surname",
795 _("Cardholder's surname: "));
796 givenname = get_one_name ("keygen.smartcard.givenname",
797 _("Cardholder's given name: "));
798 if (!surname || !givenname || (!*surname && !*givenname))
799 {
800 xfree (surname);
801 xfree (givenname);
802 rc = gpg_error (GPG_ERR_CANCELED);
803 goto leave;
804 }
805
806 isoname = xmalloc ( strlen (surname) + 2 + strlen (givenname) + 1);
807 strcpy (stpcpy (stpcpy (isoname, surname), "<<"), givenname);
808 xfree (surname);
809 xfree (givenname);
810 for (p=isoname; *p; p++)
811 if (*p == ' ')
812 *p = '<';
813
814 if (strlen (isoname) > 39 )
815 {
816 tty_printf (_("Error: Combined name too long "
817 "(limit is %d characters).\n"), 39);
818 xfree (isoname);
819 rc = gpg_error (GPG_ERR_TOO_LARGE);
820 goto leave;
821 }
822
823 rc = agent_scd_setattr ("DISP-NAME", isoname, strlen (isoname));
824 if (rc)
825 log_error ("error setting Name: %s\n", gpg_strerror (rc));
826
827 leave:
828 xfree (isoname);
829 write_sc_op_status (rc);
830 return rc;
831 }
832
833
834 static int
change_url(void)835 change_url (void)
836 {
837 char *url;
838 int rc;
839
840 url = cpr_get ("cardedit.change_url", _("URL to retrieve public key: "));
841 if (!url)
842 return -1;
843 trim_spaces (url);
844 cpr_kill_prompt ();
845
846 rc = agent_scd_setattr ("PUBKEY-URL", url, strlen (url));
847 if (rc)
848 log_error ("error setting URL: %s\n", gpg_strerror (rc));
849 xfree (url);
850 write_sc_op_status (rc);
851 return rc;
852 }
853
854
855 /* Fetch the key from the URL given on the card or try to get it from
856 the default keyserver. */
857 static int
fetch_url(ctrl_t ctrl)858 fetch_url (ctrl_t ctrl)
859 {
860 int rc;
861 struct agent_card_info_s info;
862
863 memset(&info,0,sizeof(info));
864
865 rc=agent_scd_getattr("PUBKEY-URL",&info);
866 if(rc)
867 log_error("error retrieving URL from card: %s\n",gpg_strerror(rc));
868 else
869 {
870 rc=agent_scd_getattr("KEY-FPR",&info);
871 if(rc)
872 log_error("error retrieving key fingerprint from card: %s\n",
873 gpg_strerror(rc));
874 else if (info.pubkey_url && *info.pubkey_url)
875 {
876 strlist_t sl = NULL;
877
878 add_to_strlist (&sl, info.pubkey_url);
879 rc = keyserver_fetch (ctrl, sl, KEYORG_URL);
880 free_strlist (sl);
881 }
882 else if (info.fpr1len)
883 {
884 rc = keyserver_import_fprint (ctrl, info.fpr1, info.fpr1len,
885 opt.keyserver, 0);
886 }
887 }
888
889 agent_release_card_info (&info);
890 return rc;
891 }
892
893
894 #define MAX_GET_DATA_FROM_FILE 16384
895
896 /* Read data from file FNAME up to MAX_GET_DATA_FROM_FILE characters.
897 On error return -1 and store NULL at R_BUFFER; on success return
898 the number of bytes read and store the address of a newly allocated
899 buffer at R_BUFFER. */
900 static int
get_data_from_file(const char * fname,char ** r_buffer)901 get_data_from_file (const char *fname, char **r_buffer)
902 {
903 estream_t fp;
904 char *data;
905 int n;
906
907 *r_buffer = NULL;
908
909 fp = es_fopen (fname, "rb");
910 #if GNUPG_MAJOR_VERSION == 1
911 if (fp && is_secured_file (fileno (fp)))
912 {
913 fclose (fp);
914 fp = NULL;
915 errno = EPERM;
916 }
917 #endif
918 if (!fp)
919 {
920 tty_printf (_("can't open '%s': %s\n"), fname, strerror (errno));
921 return -1;
922 }
923
924 data = xtrymalloc (MAX_GET_DATA_FROM_FILE);
925 if (!data)
926 {
927 tty_printf (_("error allocating enough memory: %s\n"), strerror (errno));
928 es_fclose (fp);
929 return -1;
930 }
931
932 n = es_fread (data, 1, MAX_GET_DATA_FROM_FILE, fp);
933 es_fclose (fp);
934 if (n < 0)
935 {
936 tty_printf (_("error reading '%s': %s\n"), fname, strerror (errno));
937 xfree (data);
938 return -1;
939 }
940 *r_buffer = data;
941 return n;
942 }
943
944
945 /* Write LENGTH bytes from BUFFER to file FNAME. Return 0 on
946 success. */
947 static int
put_data_to_file(const char * fname,const void * buffer,size_t length)948 put_data_to_file (const char *fname, const void *buffer, size_t length)
949 {
950 estream_t fp;
951
952 fp = es_fopen (fname, "wb");
953 #if GNUPG_MAJOR_VERSION == 1
954 if (fp && is_secured_file (fileno (fp)))
955 {
956 fclose (fp);
957 fp = NULL;
958 errno = EPERM;
959 }
960 #endif
961 if (!fp)
962 {
963 tty_printf (_("can't create '%s': %s\n"), fname, strerror (errno));
964 return -1;
965 }
966
967 if (length && es_fwrite (buffer, length, 1, fp) != 1)
968 {
969 tty_printf (_("error writing '%s': %s\n"), fname, strerror (errno));
970 es_fclose (fp);
971 return -1;
972 }
973 es_fclose (fp);
974 return 0;
975 }
976
977
978 static int
change_login(const char * args)979 change_login (const char *args)
980 {
981 char *data;
982 int n;
983 int rc;
984
985 if (args && *args == '<') /* Read it from a file */
986 {
987 for (args++; spacep (args); args++)
988 ;
989 n = get_data_from_file (args, &data);
990 if (n < 0)
991 return -1;
992 }
993 else
994 {
995 data = cpr_get ("cardedit.change_login",
996 _("Login data (account name): "));
997 if (!data)
998 return -1;
999 trim_spaces (data);
1000 cpr_kill_prompt ();
1001 n = strlen (data);
1002 }
1003
1004 rc = agent_scd_setattr ("LOGIN-DATA", data, n);
1005 if (rc)
1006 log_error ("error setting login data: %s\n", gpg_strerror (rc));
1007 xfree (data);
1008 write_sc_op_status (rc);
1009 return rc;
1010 }
1011
1012 static int
change_private_do(const char * args,int nr)1013 change_private_do (const char *args, int nr)
1014 {
1015 char do_name[] = "PRIVATE-DO-X";
1016 char *data;
1017 int n;
1018 int rc;
1019
1020 log_assert (nr >= 1 && nr <= 4);
1021 do_name[11] = '0' + nr;
1022
1023 if (args && (args = strchr (args, '<'))) /* Read it from a file */
1024 {
1025 for (args++; spacep (args); args++)
1026 ;
1027 n = get_data_from_file (args, &data);
1028 if (n < 0)
1029 return -1;
1030 }
1031 else
1032 {
1033 data = cpr_get ("cardedit.change_private_do",
1034 _("Private DO data: "));
1035 if (!data)
1036 return -1;
1037 trim_spaces (data);
1038 cpr_kill_prompt ();
1039 n = strlen (data);
1040 }
1041
1042 rc = agent_scd_setattr (do_name, data, n);
1043 if (rc)
1044 log_error ("error setting private DO: %s\n", gpg_strerror (rc));
1045 xfree (data);
1046 write_sc_op_status (rc);
1047 return rc;
1048 }
1049
1050
1051 static int
change_cert(const char * args)1052 change_cert (const char *args)
1053 {
1054 char *data;
1055 int n;
1056 int rc;
1057
1058 if (args && *args == '<') /* Read it from a file */
1059 {
1060 for (args++; spacep (args); args++)
1061 ;
1062 n = get_data_from_file (args, &data);
1063 if (n < 0)
1064 return -1;
1065 }
1066 else
1067 {
1068 tty_printf ("usage error: redirection to file required\n");
1069 return -1;
1070 }
1071
1072 rc = agent_scd_writecert ("OPENPGP.3", data, n);
1073 if (rc)
1074 log_error ("error writing certificate to card: %s\n", gpg_strerror (rc));
1075 xfree (data);
1076 write_sc_op_status (rc);
1077 return rc;
1078 }
1079
1080
1081 static int
read_cert(const char * args)1082 read_cert (const char *args)
1083 {
1084 const char *fname;
1085 void *buffer;
1086 size_t length;
1087 int rc;
1088
1089 if (args && *args == '>') /* Write it to a file */
1090 {
1091 for (args++; spacep (args); args++)
1092 ;
1093 fname = args;
1094 }
1095 else
1096 {
1097 tty_printf ("usage error: redirection to file required\n");
1098 return -1;
1099 }
1100
1101 rc = agent_scd_readcert ("OPENPGP.3", &buffer, &length);
1102 if (rc)
1103 log_error ("error reading certificate from card: %s\n", gpg_strerror (rc));
1104 else
1105 rc = put_data_to_file (fname, buffer, length);
1106 xfree (buffer);
1107 write_sc_op_status (rc);
1108 return rc;
1109 }
1110
1111
1112 static int
change_lang(void)1113 change_lang (void)
1114 {
1115 char *data, *p;
1116 int rc;
1117
1118 data = cpr_get ("cardedit.change_lang",
1119 _("Language preferences: "));
1120 if (!data)
1121 return -1;
1122 trim_spaces (data);
1123 cpr_kill_prompt ();
1124
1125 if (strlen (data) > 8 || (strlen (data) & 1))
1126 {
1127 tty_printf (_("Error: invalid length of preference string.\n"));
1128 xfree (data);
1129 return -1;
1130 }
1131
1132 for (p=data; *p && *p >= 'a' && *p <= 'z'; p++)
1133 ;
1134 if (*p)
1135 {
1136 tty_printf (_("Error: invalid characters in preference string.\n"));
1137 xfree (data);
1138 return -1;
1139 }
1140
1141 rc = agent_scd_setattr ("DISP-LANG", data, strlen (data));
1142 if (rc)
1143 log_error ("error setting lang: %s\n", gpg_strerror (rc));
1144 xfree (data);
1145 write_sc_op_status (rc);
1146 return rc;
1147 }
1148
1149
1150 static int
change_sex(void)1151 change_sex (void)
1152 {
1153 char *data;
1154 const char *str;
1155 int rc;
1156
1157 data = cpr_get ("cardedit.change_sex",
1158 _("Salutation (M = Mr., F = Ms., or space): "));
1159 if (!data)
1160 return -1;
1161 trim_spaces (data);
1162 cpr_kill_prompt ();
1163
1164 if (!*data)
1165 str = "9";
1166 else if ((*data == 'M' || *data == 'm') && !data[1])
1167 str = "1";
1168 else if ((*data == 'F' || *data == 'f') && !data[1])
1169 str = "2";
1170 else
1171 {
1172 tty_printf (_("Error: invalid response.\n"));
1173 xfree (data);
1174 return -1;
1175 }
1176
1177 rc = agent_scd_setattr ("DISP-SEX", str, 1);
1178 if (rc)
1179 log_error ("error setting salutation: %s\n", gpg_strerror (rc));
1180 xfree (data);
1181 write_sc_op_status (rc);
1182 return rc;
1183 }
1184
1185
1186 static int
change_cafpr(int fprno)1187 change_cafpr (int fprno)
1188 {
1189 char *data;
1190 const char *s;
1191 int i, c, rc;
1192 unsigned char fpr[MAX_FINGERPRINT_LEN];
1193 int fprlen;
1194
1195 data = cpr_get ("cardedit.change_cafpr", _("CA fingerprint: "));
1196 if (!data)
1197 return -1;
1198 trim_spaces (data);
1199 cpr_kill_prompt ();
1200
1201 for (i=0, s=data; i < MAX_FINGERPRINT_LEN && *s; )
1202 {
1203 while (spacep(s))
1204 s++;
1205 if (*s == ':')
1206 s++;
1207 while (spacep(s))
1208 s++;
1209 c = hextobyte (s);
1210 if (c == -1)
1211 break;
1212 fpr[i++] = c;
1213 s += 2;
1214 }
1215 fprlen = i;
1216 xfree (data);
1217 if ((fprlen != 20 && fprlen != 32) || *s)
1218 {
1219 tty_printf (_("Error: invalid formatted fingerprint.\n"));
1220 return -1;
1221 }
1222
1223 rc = agent_scd_setattr (fprno==1?"CA-FPR-1":
1224 fprno==2?"CA-FPR-2":
1225 fprno==3?"CA-FPR-3":"x", fpr, fprlen);
1226 if (rc)
1227 log_error ("error setting cafpr: %s\n", gpg_strerror (rc));
1228 write_sc_op_status (rc);
1229 return rc;
1230 }
1231
1232
1233
1234 static void
toggle_forcesig(void)1235 toggle_forcesig (void)
1236 {
1237 struct agent_card_info_s info;
1238 int rc;
1239 int newstate;
1240
1241 memset (&info, 0, sizeof info);
1242 rc = agent_scd_getattr ("CHV-STATUS", &info);
1243 if (rc)
1244 {
1245 log_error ("error getting current status: %s\n", gpg_strerror (rc));
1246 return;
1247 }
1248 newstate = !info.chv1_cached;
1249 agent_release_card_info (&info);
1250
1251 rc = agent_scd_setattr ("CHV-STATUS-1", newstate? "\x01":"", 1);
1252 if (rc)
1253 log_error ("error toggling signature PIN flag: %s\n", gpg_strerror (rc));
1254 write_sc_op_status (rc);
1255 }
1256
1257
1258 /* Helper for the key generation/edit functions. */
1259 static int
get_info_for_key_operation(struct agent_card_info_s * info)1260 get_info_for_key_operation (struct agent_card_info_s *info)
1261 {
1262 int rc;
1263
1264 memset (info, 0, sizeof *info);
1265 rc = agent_scd_getattr ("SERIALNO", info);
1266 if (rc || !info->serialno || strncmp (info->serialno, "D27600012401", 12)
1267 || strlen (info->serialno) != 32 )
1268 {
1269 log_error (_("key operation not possible: %s\n"),
1270 rc ? gpg_strerror (rc) : _("not an OpenPGP card"));
1271 return rc? rc: -1;
1272 }
1273 rc = agent_scd_getattr ("KEY-FPR", info);
1274 if (!rc)
1275 rc = agent_scd_getattr ("CHV-STATUS", info);
1276 if (!rc)
1277 rc = agent_scd_getattr ("DISP-NAME", info);
1278 if (!rc)
1279 rc = agent_scd_getattr ("EXTCAP", info);
1280 if (!rc)
1281 rc = agent_scd_getattr ("KEY-ATTR", info);
1282 if (rc)
1283 log_error (_("error getting current key info: %s\n"), gpg_strerror (rc));
1284 return rc;
1285 }
1286
1287
1288 /* Helper for the key generation/edit functions. */
1289 static int
check_pin_for_key_operation(struct agent_card_info_s * info,int * forced_chv1)1290 check_pin_for_key_operation (struct agent_card_info_s *info, int *forced_chv1)
1291 {
1292 int rc = 0;
1293
1294 *forced_chv1 = !info->chv1_cached;
1295 if (*forced_chv1)
1296 { /* Switch off the forced mode so that during key generation we
1297 don't get bothered with PIN queries for each
1298 self-signature. */
1299 rc = agent_scd_setattr ("CHV-STATUS-1", "\x01", 1);
1300 if (rc)
1301 {
1302 log_error ("error clearing forced signature PIN flag: %s\n",
1303 gpg_strerror (rc));
1304 *forced_chv1 = 0;
1305 }
1306 }
1307
1308 if (!rc)
1309 {
1310 /* Check the PIN now, so that we won't get asked later for each
1311 binding signature. */
1312 rc = agent_scd_checkpin (info->serialno);
1313 if (rc)
1314 {
1315 log_error ("error checking the PIN: %s\n", gpg_strerror (rc));
1316 write_sc_op_status (rc);
1317 }
1318 }
1319 return rc;
1320 }
1321
1322 /* Helper for the key generation/edit functions. */
1323 static void
restore_forced_chv1(int * forced_chv1)1324 restore_forced_chv1 (int *forced_chv1)
1325 {
1326 int rc;
1327
1328 if (*forced_chv1)
1329 { /* Switch back to forced state. */
1330 rc = agent_scd_setattr ("CHV-STATUS-1", "", 1);
1331 if (rc)
1332 {
1333 log_error ("error setting forced signature PIN flag: %s\n",
1334 gpg_strerror (rc));
1335 }
1336 }
1337 }
1338
1339
1340 /* Helper for the key generation/edit functions. */
1341 static void
show_card_key_info(struct agent_card_info_s * info)1342 show_card_key_info (struct agent_card_info_s *info)
1343 {
1344 tty_fprintf (NULL, "Signature key ....:");
1345 print_shax_fpr (NULL, info->fpr1len? info->fpr1:NULL, info->fpr1len);
1346 tty_fprintf (NULL, "Encryption key....:");
1347 print_shax_fpr (NULL, info->fpr2len? info->fpr2:NULL, info->fpr2len);
1348 tty_fprintf (NULL, "Authentication key:");
1349 print_shax_fpr (NULL, info->fpr3len? info->fpr3:NULL, info->fpr3len);
1350 tty_printf ("\n");
1351 }
1352
1353
1354 /* Helper for the key generation/edit functions. */
1355 static int
replace_existing_key_p(struct agent_card_info_s * info,int keyno)1356 replace_existing_key_p (struct agent_card_info_s *info, int keyno)
1357 {
1358 log_assert (keyno >= 0 && keyno <= 3);
1359
1360 if ((keyno == 1 && info->fpr1len)
1361 || (keyno == 2 && info->fpr2len)
1362 || (keyno == 3 && info->fpr3len))
1363 {
1364 tty_printf ("\n");
1365 log_info ("WARNING: such a key has already been stored on the card!\n");
1366 tty_printf ("\n");
1367 if ( !cpr_get_answer_is_yes( "cardedit.genkeys.replace_key",
1368 _("Replace existing key? (y/N) ")))
1369 return -1;
1370 return 1;
1371 }
1372 return 0;
1373 }
1374
1375
1376 static void
show_keysize_warning(void)1377 show_keysize_warning (void)
1378 {
1379 static int shown;
1380
1381 if (shown)
1382 return;
1383 shown = 1;
1384 tty_printf
1385 (_("Note: There is no guarantee that the card supports the requested\n"
1386 " key type or size. If the key generation does not succeed,\n"
1387 " please check the documentation of your card to see which\n"
1388 " key types and sizes are supported.\n")
1389 );
1390 }
1391
1392
1393 /* Ask for the size of a card key. NBITS is the current size
1394 configured for the card. Returns 0 to use the default size
1395 (i.e. NBITS) or the selected size. */
1396 static unsigned int
ask_card_rsa_keysize(unsigned int nbits)1397 ask_card_rsa_keysize (unsigned int nbits)
1398 {
1399 unsigned int min_nbits = 1024;
1400 unsigned int max_nbits = 4096;
1401 char *prompt, *answer;
1402 unsigned int req_nbits;
1403
1404 for (;;)
1405 {
1406 prompt = xasprintf (_("What keysize do you want? (%u) "), nbits);
1407 answer = cpr_get ("cardedit.genkeys.size", prompt);
1408 cpr_kill_prompt ();
1409 req_nbits = *answer? atoi (answer): nbits;
1410 xfree (prompt);
1411 xfree (answer);
1412
1413 if (req_nbits != nbits && (req_nbits % 32) )
1414 {
1415 req_nbits = ((req_nbits + 31) / 32) * 32;
1416 tty_printf (_("rounded up to %u bits\n"), req_nbits);
1417 }
1418
1419 if (req_nbits == nbits)
1420 return 0; /* Use default. */
1421
1422 if (req_nbits < min_nbits || req_nbits > max_nbits)
1423 {
1424 tty_printf (_("%s keysizes must be in the range %u-%u\n"),
1425 "RSA", min_nbits, max_nbits);
1426 }
1427 else
1428 return req_nbits;
1429 }
1430 }
1431
1432 /* Ask for the key attribute of a card key. CURRENT is the current
1433 attribute configured for the card. KEYNO is the number of the key
1434 used to select the prompt. Returns NULL to use the default
1435 attribute or the selected attribute structure. */
1436 static struct key_attr *
ask_card_keyattr(int keyno,const struct key_attr * current)1437 ask_card_keyattr (int keyno, const struct key_attr *current)
1438 {
1439 struct key_attr *key_attr = NULL;
1440 char *answer = NULL;
1441 int algo;
1442
1443 tty_printf (_("Changing card key attribute for: "));
1444 if (keyno == 0)
1445 tty_printf (_("Signature key\n"));
1446 else if (keyno == 1)
1447 tty_printf (_("Encryption key\n"));
1448 else
1449 tty_printf (_("Authentication key\n"));
1450
1451 tty_printf (_("Please select what kind of key you want:\n"));
1452 tty_printf (_(" (%d) RSA\n"), 1 );
1453 tty_printf (_(" (%d) ECC\n"), 2 );
1454
1455 for (;;)
1456 {
1457 xfree (answer);
1458 answer = cpr_get ("cardedit.genkeys.algo", _("Your selection? "));
1459 cpr_kill_prompt ();
1460 algo = *answer? atoi (answer) : 0;
1461
1462 if (!*answer || algo == 1 || algo == 2)
1463 {
1464 xfree (answer);
1465 break;
1466 }
1467 else
1468 tty_printf (_("Invalid selection.\n"));
1469 }
1470
1471 if (algo == 0)
1472 goto leave;
1473
1474 key_attr = xmalloc (sizeof (struct key_attr));
1475
1476 if (algo == 1)
1477 {
1478 unsigned int nbits, result_nbits;
1479
1480 if (current->algo == PUBKEY_ALGO_RSA)
1481 nbits = current->nbits;
1482 else
1483 nbits = 2048;
1484
1485 result_nbits = ask_card_rsa_keysize (nbits);
1486 if (result_nbits == 0)
1487 {
1488 if (current->algo == PUBKEY_ALGO_RSA)
1489 {
1490 xfree (key_attr);
1491 key_attr = NULL;
1492 }
1493 else
1494 result_nbits = nbits;
1495 }
1496
1497 if (key_attr)
1498 {
1499 key_attr->algo = PUBKEY_ALGO_RSA;
1500 key_attr->nbits = result_nbits;
1501 }
1502 }
1503 else
1504 {
1505 const char *curve;
1506 const char *oid_str;
1507
1508 if (current->algo == PUBKEY_ALGO_RSA)
1509 {
1510 if (keyno == 1)
1511 /* Encryption key */
1512 algo = PUBKEY_ALGO_ECDH;
1513 else /* Signature key or Authentication key */
1514 algo = PUBKEY_ALGO_ECDSA;
1515 curve = NULL;
1516 }
1517 else
1518 {
1519 algo = current->algo;
1520 curve = current->curve;
1521 }
1522
1523 curve = ask_curve (&algo, NULL, curve);
1524 if (curve)
1525 {
1526 key_attr->algo = algo;
1527 oid_str = openpgp_curve_to_oid (curve, NULL, NULL);
1528 key_attr->curve = openpgp_oid_to_curve (oid_str, 0);
1529 }
1530 else
1531 {
1532 xfree (key_attr);
1533 key_attr = NULL;
1534 }
1535 }
1536
1537 leave:
1538 if (key_attr)
1539 {
1540 if (key_attr->algo == PUBKEY_ALGO_RSA)
1541 tty_printf (_("The card will now be re-configured"
1542 " to generate a key of %u bits\n"), key_attr->nbits);
1543 else if (key_attr->algo == PUBKEY_ALGO_ECDH
1544 || key_attr->algo == PUBKEY_ALGO_ECDSA
1545 || key_attr->algo == PUBKEY_ALGO_EDDSA)
1546 tty_printf (_("The card will now be re-configured"
1547 " to generate a key of type: %s\n"), key_attr->curve),
1548
1549 show_keysize_warning ();
1550 }
1551
1552 return key_attr;
1553 }
1554
1555
1556
1557 /* Change the key attribute of key KEYNO (0..2) and show an error
1558 * message if that fails. */
1559 static gpg_error_t
do_change_keyattr(int keyno,const struct key_attr * key_attr)1560 do_change_keyattr (int keyno, const struct key_attr *key_attr)
1561 {
1562 gpg_error_t err = 0;
1563 char args[100];
1564
1565 if (key_attr->algo == PUBKEY_ALGO_RSA)
1566 snprintf (args, sizeof args, "--force %d 1 rsa%u", keyno+1,
1567 key_attr->nbits);
1568 else if (key_attr->algo == PUBKEY_ALGO_ECDH
1569 || key_attr->algo == PUBKEY_ALGO_ECDSA
1570 || key_attr->algo == PUBKEY_ALGO_EDDSA)
1571 snprintf (args, sizeof args, "--force %d %d %s",
1572 keyno+1, key_attr->algo, key_attr->curve);
1573 else
1574 {
1575 log_error (_("public key algorithm %d (%s) is not supported\n"),
1576 key_attr->algo, gcry_pk_algo_name (key_attr->algo));
1577 return gpg_error (GPG_ERR_PUBKEY_ALGO);
1578 }
1579
1580 err = agent_scd_setattr ("KEY-ATTR", args, strlen (args));
1581 if (err)
1582 log_error (_("error changing key attribute for key %d: %s\n"),
1583 keyno+1, gpg_strerror (err));
1584 return err;
1585 }
1586
1587
1588 static void
key_attr(void)1589 key_attr (void)
1590 {
1591 struct agent_card_info_s info;
1592 gpg_error_t err;
1593 int keyno;
1594
1595 err = get_info_for_key_operation (&info);
1596 if (err)
1597 {
1598 log_error (_("error getting card info: %s\n"), gpg_strerror (err));
1599 return;
1600 }
1601
1602 if (!(info.is_v2 && info.extcap.aac))
1603 {
1604 log_error (_("This command is not supported by this card\n"));
1605 goto leave;
1606 }
1607
1608 for (keyno = 0; keyno < DIM (info.key_attr); keyno++)
1609 {
1610 struct key_attr *key_attr;
1611
1612 if ((key_attr = ask_card_keyattr (keyno, &info.key_attr[keyno])))
1613 {
1614 err = do_change_keyattr (keyno, key_attr);
1615 xfree (key_attr);
1616 if (err)
1617 {
1618 /* Error: Better read the default key attribute again. */
1619 agent_release_card_info (&info);
1620 if (get_info_for_key_operation (&info))
1621 goto leave;
1622 /* Ask again for this key. */
1623 keyno--;
1624 }
1625 }
1626 }
1627
1628 leave:
1629 agent_release_card_info (&info);
1630 }
1631
1632
1633 static void
generate_card_keys(ctrl_t ctrl)1634 generate_card_keys (ctrl_t ctrl)
1635 {
1636 struct agent_card_info_s info;
1637 int forced_chv1;
1638 int want_backup;
1639
1640 if (get_info_for_key_operation (&info))
1641 return;
1642
1643 if (info.extcap.ki)
1644 {
1645 char *answer;
1646
1647 /* FIXME: Should be something like cpr_get_bool so that a status
1648 GET_BOOL will be emitted. */
1649 answer = cpr_get ("cardedit.genkeys.backup_enc",
1650 _("Make off-card backup of encryption key? (Y/n) "));
1651
1652 want_backup = answer_is_yes_no_default (answer, 1/*(default to Yes)*/);
1653 cpr_kill_prompt ();
1654 xfree (answer);
1655 }
1656 else
1657 want_backup = 0;
1658
1659 if ( (info.fpr1len && !fpr_is_zero (info.fpr1, info.fpr1len))
1660 || (info.fpr2len && !fpr_is_zero (info.fpr2, info.fpr2len))
1661 || (info.fpr3len && !fpr_is_zero (info.fpr3, info.fpr3len)))
1662 {
1663 tty_printf ("\n");
1664 log_info (_("Note: keys are already stored on the card!\n"));
1665 tty_printf ("\n");
1666 if ( !cpr_get_answer_is_yes ("cardedit.genkeys.replace_keys",
1667 _("Replace existing keys? (y/N) ")))
1668 {
1669 agent_release_card_info (&info);
1670 return;
1671 }
1672 }
1673
1674 /* If no displayed name has been set, we assume that this is a fresh
1675 card and print a hint about the default PINs. */
1676 if (!info.disp_name || !*info.disp_name)
1677 {
1678 tty_printf ("\n");
1679 tty_printf (_("Please note that the factory settings of the PINs are\n"
1680 " PIN = '%s' Admin PIN = '%s'\n"
1681 "You should change them using the command --change-pin\n"),
1682 "123456", "12345678");
1683 tty_printf ("\n");
1684 }
1685
1686
1687 if (check_pin_for_key_operation (&info, &forced_chv1))
1688 goto leave;
1689
1690 generate_keypair (ctrl, 1, NULL, info.serialno, want_backup);
1691
1692 leave:
1693 agent_release_card_info (&info);
1694 restore_forced_chv1 (&forced_chv1);
1695 }
1696
1697
1698 /* This function is used by the key edit menu to generate an arbitrary
1699 subkey. */
1700 gpg_error_t
card_generate_subkey(ctrl_t ctrl,kbnode_t pub_keyblock)1701 card_generate_subkey (ctrl_t ctrl, kbnode_t pub_keyblock)
1702 {
1703 gpg_error_t err;
1704 struct agent_card_info_s info;
1705 int forced_chv1 = 0;
1706 int keyno;
1707
1708 err = get_info_for_key_operation (&info);
1709 if (err)
1710 return err;
1711
1712 show_card_key_info (&info);
1713
1714 tty_printf (_("Please select the type of key to generate:\n"));
1715
1716 tty_printf (_(" (1) Signature key\n"));
1717 tty_printf (_(" (2) Encryption key\n"));
1718 tty_printf (_(" (3) Authentication key\n"));
1719
1720 for (;;)
1721 {
1722 char *answer = cpr_get ("cardedit.genkeys.subkeytype",
1723 _("Your selection? "));
1724 cpr_kill_prompt();
1725 if (*answer == CONTROL_D)
1726 {
1727 xfree (answer);
1728 err = gpg_error (GPG_ERR_CANCELED);
1729 goto leave;
1730 }
1731 keyno = *answer? atoi(answer): 0;
1732 xfree(answer);
1733 if (keyno >= 1 && keyno <= 3)
1734 break; /* Okay. */
1735 tty_printf(_("Invalid selection.\n"));
1736 }
1737
1738 if (replace_existing_key_p (&info, keyno) < 0)
1739 {
1740 err = gpg_error (GPG_ERR_CANCELED);
1741 goto leave;
1742 }
1743
1744 err = check_pin_for_key_operation (&info, &forced_chv1);
1745 if (err)
1746 goto leave;
1747
1748 err = generate_card_subkeypair (ctrl, pub_keyblock, keyno, info.serialno);
1749
1750 leave:
1751 agent_release_card_info (&info);
1752 restore_forced_chv1 (&forced_chv1);
1753 return err;
1754 }
1755
1756
1757 /* Store the key at NODE into the smartcard and modify NODE to
1758 carry the serialno stuff instead of the actual secret key
1759 parameters. USE is the usage for that key; 0 means any
1760 usage. */
1761 int
card_store_subkey(KBNODE node,int use)1762 card_store_subkey (KBNODE node, int use)
1763 {
1764 struct agent_card_info_s info;
1765 int okay = 0;
1766 unsigned int nbits;
1767 int allow_keyno[3];
1768 int keyno;
1769 PKT_public_key *pk;
1770 gpg_error_t err;
1771 char *hexgrip;
1772 int rc;
1773 gnupg_isotime_t timebuf;
1774
1775 log_assert (node->pkt->pkttype == PKT_PUBLIC_KEY
1776 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
1777
1778 pk = node->pkt->pkt.public_key;
1779
1780 if (get_info_for_key_operation (&info))
1781 return 0;
1782
1783 if (!info.extcap.ki)
1784 {
1785 tty_printf ("The card does not support the import of keys\n");
1786 tty_printf ("\n");
1787 goto leave;
1788 }
1789
1790 nbits = nbits_from_pk (pk);
1791
1792 if (!info.is_v2 && nbits != 1024)
1793 {
1794 tty_printf ("You may only store a 1024 bit RSA key on the card\n");
1795 tty_printf ("\n");
1796 goto leave;
1797 }
1798
1799 allow_keyno[0] = (!use || (use & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_CERT)));
1800 allow_keyno[1] = (!use || (use & (PUBKEY_USAGE_ENC)));
1801 allow_keyno[2] = (!use || (use & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_AUTH)));
1802
1803 tty_printf (_("Please select where to store the key:\n"));
1804
1805 if (allow_keyno[0])
1806 tty_printf (_(" (1) Signature key\n"));
1807 if (allow_keyno[1])
1808 tty_printf (_(" (2) Encryption key\n"));
1809 if (allow_keyno[2])
1810 tty_printf (_(" (3) Authentication key\n"));
1811
1812 for (;;)
1813 {
1814 char *answer = cpr_get ("cardedit.genkeys.storekeytype",
1815 _("Your selection? "));
1816 cpr_kill_prompt();
1817 if (*answer == CONTROL_D || !*answer)
1818 {
1819 xfree (answer);
1820 goto leave;
1821 }
1822 keyno = *answer? atoi(answer): 0;
1823 xfree(answer);
1824 if (keyno >= 1 && keyno <= 3 && allow_keyno[keyno-1])
1825 {
1826 if (info.is_v2 && !info.extcap.aac
1827 && info.key_attr[keyno-1].nbits != nbits)
1828 {
1829 tty_printf ("Key does not match the card's capability.\n");
1830 }
1831 else
1832 break; /* Okay. */
1833 }
1834 else
1835 tty_printf(_("Invalid selection.\n"));
1836 }
1837
1838 if ((rc = replace_existing_key_p (&info, keyno)) < 0)
1839 goto leave;
1840
1841 err = hexkeygrip_from_pk (pk, &hexgrip);
1842 if (err)
1843 goto leave;
1844
1845 epoch2isotime (timebuf, (time_t)pk->timestamp);
1846 rc = agent_keytocard (hexgrip, keyno, rc, info.serialno, timebuf);
1847
1848 if (rc)
1849 log_error (_("KEYTOCARD failed: %s\n"), gpg_strerror (rc));
1850 else
1851 okay = 1;
1852 xfree (hexgrip);
1853
1854 leave:
1855 agent_release_card_info (&info);
1856 return okay;
1857 }
1858
1859
1860
1861 /* Direct sending of an hex encoded APDU with error printing. */
1862 static gpg_error_t
send_apdu(const char * hexapdu,const char * desc,unsigned int ignore)1863 send_apdu (const char *hexapdu, const char *desc, unsigned int ignore)
1864 {
1865 gpg_error_t err;
1866 unsigned int sw;
1867
1868 err = agent_scd_apdu (hexapdu, &sw);
1869 if (err)
1870 tty_printf ("sending card command %s failed: %s\n", desc,
1871 gpg_strerror (err));
1872 else if (!hexapdu
1873 || !strcmp (hexapdu, "undefined")
1874 || !strcmp (hexapdu, "reset-keep-lock")
1875 || !strcmp (hexapdu, "lock")
1876 || !strcmp (hexapdu, "trylock")
1877 || !strcmp (hexapdu, "unlock"))
1878 ; /* Ignore pseudo APDUs. */
1879 else if (ignore == 0xffff)
1880 ; /* Ignore all status words. */
1881 else if (sw != 0x9000)
1882 {
1883 switch (sw)
1884 {
1885 case 0x6285: err = gpg_error (GPG_ERR_OBJ_TERM_STATE); break;
1886 case 0x6982: err = gpg_error (GPG_ERR_BAD_PIN); break;
1887 case 0x6985: err = gpg_error (GPG_ERR_USE_CONDITIONS); break;
1888 default: err = gpg_error (GPG_ERR_CARD);
1889 }
1890 if (!(ignore && ignore == sw))
1891 tty_printf ("card command %s failed: %s (0x%04x)\n", desc,
1892 gpg_strerror (err), sw);
1893 }
1894 return err;
1895 }
1896
1897
1898 /* Do a factory reset after confirmation. */
1899 static void
factory_reset(void)1900 factory_reset (void)
1901 {
1902 struct agent_card_info_s info;
1903 gpg_error_t err;
1904 char *answer = NULL;
1905 int termstate = 0;
1906 int i;
1907 int locked = 0;
1908
1909 /* The code below basically does the same what this
1910 gpg-connect-agent script does:
1911
1912 scd reset
1913 scd serialno undefined
1914 scd apdu 00 A4 04 00 06 D2 76 00 01 24 01
1915 scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40
1916 scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40
1917 scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40
1918 scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40
1919 scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40
1920 scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40
1921 scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40
1922 scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40
1923 scd apdu 00 e6 00 00
1924 scd apdu 00 44 00 00
1925 scd reset
1926 /echo Card has been reset to factory defaults
1927
1928 but tries to find out something about the card first.
1929 */
1930
1931 err = agent_scd_learn (&info, 0);
1932 if (gpg_err_code (err) == GPG_ERR_OBJ_TERM_STATE
1933 && gpg_err_source (err) == GPG_ERR_SOURCE_SCD)
1934 termstate = 1;
1935 else if (err)
1936 {
1937 log_error (_("OpenPGP card not available: %s\n"), gpg_strerror (err));
1938 goto leave;
1939 }
1940
1941 if (!termstate)
1942 {
1943 log_info (_("OpenPGP card no. %s detected\n"),
1944 info.serialno? info.serialno : "[none]");
1945 if (!(info.status_indicator == 3 || info.status_indicator == 5))
1946 {
1947 /* Note: We won't see status-indicator 3 here because it is not
1948 possible to select a card application in termination state. */
1949 log_error (_("This command is not supported by this card\n"));
1950 goto leave;
1951 }
1952
1953 tty_printf ("\n");
1954 log_info (_("Note: This command destroys all keys stored on the card!\n"));
1955 tty_printf ("\n");
1956 if (!cpr_get_answer_is_yes ("cardedit.factory-reset.proceed",
1957 _("Continue? (y/N) ")))
1958 goto leave;
1959
1960
1961 answer = cpr_get ("cardedit.factory-reset.really",
1962 _("Really do a factory reset? (enter \"yes\") "));
1963 cpr_kill_prompt ();
1964 trim_spaces (answer);
1965 if (strcmp (answer, "yes"))
1966 goto leave;
1967
1968 /* We need to select a card application before we can send APDUs
1969 to the card without scdaemon doing anything on its own. We
1970 then lock the connection so that other tools (e.g. Kleopatra)
1971 don't try a new select. */
1972 err = send_apdu ("lock", "locking connection ", 0);
1973 if (err)
1974 goto leave;
1975 locked = 1;
1976 err = send_apdu ("reset-keep-lock", "reset", 0);
1977 if (err)
1978 goto leave;
1979 err = send_apdu ("undefined", "dummy select ", 0);
1980 if (err)
1981 goto leave;
1982
1983 /* Select the OpenPGP application. */
1984 err = send_apdu ("00A4040006D27600012401", "SELECT AID", 0);
1985 if (err)
1986 goto leave;
1987
1988 /* Do some dummy verifies with wrong PINs to set the retry
1989 counter to zero. We can't easily use the card version 2.1
1990 feature of presenting the admin PIN to allow the terminate
1991 command because there is no machinery in scdaemon to catch
1992 the verify command and ask for the PIN when the "APDU"
1993 command is used. */
1994 /* Here, the length of dummy wrong PIN is 32-byte, also
1995 supporting authentication with KDF DO. */
1996 for (i=0; i < 4; i++)
1997 send_apdu ("0020008120"
1998 "40404040404040404040404040404040"
1999 "40404040404040404040404040404040", "VERIFY", 0xffff);
2000 for (i=0; i < 4; i++)
2001 send_apdu ("0020008320"
2002 "40404040404040404040404040404040"
2003 "40404040404040404040404040404040", "VERIFY", 0xffff);
2004
2005 /* Send terminate datafile command. */
2006 err = send_apdu ("00e60000", "TERMINATE DF", 0x6985);
2007 if (err)
2008 goto leave;
2009 }
2010
2011 /* Send activate datafile command. This is used without
2012 confirmation if the card is already in termination state. */
2013 err = send_apdu ("00440000", "ACTIVATE DF", 0);
2014 if (err)
2015 goto leave;
2016
2017 /* Finally we reset the card reader once more. */
2018 err = send_apdu ("reset-keep-lock", "reset", 0);
2019
2020 /* Then, connect the card again. */
2021 if (!err)
2022 err = agent_scd_serialno (NULL, NULL);
2023
2024 leave:
2025 if (locked)
2026 send_apdu ("unlock", "unlocking connection ", 0);
2027 xfree (answer);
2028 agent_release_card_info (&info);
2029 }
2030
2031
2032 #define USER_PIN_DEFAULT "123456"
2033 #define ADMIN_PIN_DEFAULT "12345678"
2034 #define KDF_DATA_LENGTH_MIN 90
2035 #define KDF_DATA_LENGTH_MAX 110
2036
2037 /* Generate KDF data. */
2038 static gpg_error_t
gen_kdf_data(unsigned char * data,int single_salt)2039 gen_kdf_data (unsigned char *data, int single_salt)
2040 {
2041 const unsigned char h0[] = { 0x81, 0x01, 0x03,
2042 0x82, 0x01, 0x08,
2043 0x83, 0x04 };
2044 const unsigned char h1[] = { 0x84, 0x08 };
2045 const unsigned char h2[] = { 0x85, 0x08 };
2046 const unsigned char h3[] = { 0x86, 0x08 };
2047 const unsigned char h4[] = { 0x87, 0x20 };
2048 const unsigned char h5[] = { 0x88, 0x20 };
2049 unsigned char *p, *salt_user, *salt_admin;
2050 unsigned char s2k_char;
2051 unsigned int iterations;
2052 unsigned char count_4byte[4];
2053 gpg_error_t err = 0;
2054
2055 p = data;
2056
2057 s2k_char = encode_s2k_iterations (agent_get_s2k_count ());
2058 iterations = S2K_DECODE_COUNT (s2k_char);
2059 count_4byte[0] = (iterations >> 24) & 0xff;
2060 count_4byte[1] = (iterations >> 16) & 0xff;
2061 count_4byte[2] = (iterations >> 8) & 0xff;
2062 count_4byte[3] = (iterations & 0xff);
2063
2064 memcpy (p, h0, sizeof h0);
2065 p += sizeof h0;
2066 memcpy (p, count_4byte, sizeof count_4byte);
2067 p += sizeof count_4byte;
2068 memcpy (p, h1, sizeof h1);
2069 salt_user = (p += sizeof h1);
2070 gcry_randomize (p, 8, GCRY_STRONG_RANDOM);
2071 p += 8;
2072
2073 if (single_salt)
2074 salt_admin = salt_user;
2075 else
2076 {
2077 memcpy (p, h2, sizeof h2);
2078 p += sizeof h2;
2079 gcry_randomize (p, 8, GCRY_STRONG_RANDOM);
2080 p += 8;
2081 memcpy (p, h3, sizeof h3);
2082 salt_admin = (p += sizeof h3);
2083 gcry_randomize (p, 8, GCRY_STRONG_RANDOM);
2084 p += 8;
2085 }
2086
2087 memcpy (p, h4, sizeof h4);
2088 p += sizeof h4;
2089 err = gcry_kdf_derive (USER_PIN_DEFAULT, strlen (USER_PIN_DEFAULT),
2090 GCRY_KDF_ITERSALTED_S2K, DIGEST_ALGO_SHA256,
2091 salt_user, 8, iterations, 32, p);
2092 p += 32;
2093 if (!err)
2094 {
2095 memcpy (p, h5, sizeof h5);
2096 p += sizeof h5;
2097 err = gcry_kdf_derive (ADMIN_PIN_DEFAULT, strlen (ADMIN_PIN_DEFAULT),
2098 GCRY_KDF_ITERSALTED_S2K, DIGEST_ALGO_SHA256,
2099 salt_admin, 8, iterations, 32, p);
2100 }
2101
2102 return err;
2103 }
2104
2105 /* Setup KDF data object which is used for PIN authentication. */
2106 static void
kdf_setup(const char * args)2107 kdf_setup (const char *args)
2108 {
2109 struct agent_card_info_s info;
2110 gpg_error_t err;
2111 unsigned char kdf_data[KDF_DATA_LENGTH_MAX];
2112 size_t len;
2113
2114 memset (&info, 0, sizeof info);
2115
2116 err = agent_scd_getattr ("EXTCAP", &info);
2117 if (err)
2118 {
2119 log_error (_("error getting card info: %s\n"), gpg_strerror (err));
2120 return;
2121 }
2122
2123 if (!info.extcap.kdf)
2124 {
2125 log_error (_("This command is not supported by this card\n"));
2126 goto leave;
2127 }
2128
2129 if (!strcmp (args, "off"))
2130 {
2131 len = 3;
2132 memcpy (kdf_data, "\x81\x01\x00", len);
2133 }
2134 else
2135 {
2136 int single = 0;
2137
2138 if (*args != 0)
2139 single = 1;
2140
2141 len = single ? KDF_DATA_LENGTH_MIN: KDF_DATA_LENGTH_MAX;
2142 err = gen_kdf_data (kdf_data, single);
2143 if (err)
2144 goto leave_error;
2145 }
2146
2147 err = agent_scd_setattr ("KDF", kdf_data, len);
2148 if (err)
2149 goto leave_error;
2150
2151 err = agent_scd_getattr ("KDF", &info);
2152
2153 leave_error:
2154 if (err)
2155 log_error (_("error for setup KDF: %s\n"), gpg_strerror (err));
2156
2157 leave:
2158 agent_release_card_info (&info);
2159 }
2160
2161 static void
uif(int arg_number,const char * arg_rest)2162 uif (int arg_number, const char *arg_rest)
2163 {
2164 struct agent_card_info_s info;
2165 int feature_available;
2166 gpg_error_t err;
2167 char name[100];
2168 unsigned char data[2];
2169
2170 memset (&info, 0, sizeof info);
2171
2172 err = agent_scd_getattr ("EXTCAP", &info);
2173 if (err)
2174 {
2175 log_error (_("error getting card info: %s\n"), gpg_strerror (err));
2176 return;
2177 }
2178
2179 feature_available = info.extcap.bt;
2180 agent_release_card_info (&info);
2181
2182 if (!feature_available)
2183 {
2184 log_error (_("This command is not supported by this card\n"));
2185 tty_printf ("\n");
2186 return;
2187 }
2188
2189 snprintf (name, sizeof name, "UIF-%d", arg_number);
2190 if ( !strcmp (arg_rest, "off") )
2191 data[0] = 0x00;
2192 else if ( !strcmp (arg_rest, "on") )
2193 data[0] = 0x01;
2194 else if ( !strcmp (arg_rest, "permanent") )
2195 data[0] = 0x02;
2196
2197 data[1] = 0x20;
2198
2199 err = agent_scd_setattr (name, data, 2);
2200 if (err)
2201 log_error (_("error for setup UIF: %s\n"), gpg_strerror (err));
2202 }
2203
2204 /* Data used by the command parser. This needs to be outside of the
2205 function scope to allow readline based command completion. */
2206 enum cmdids
2207 {
2208 cmdNOP = 0,
2209 cmdQUIT, cmdADMIN, cmdHELP, cmdLIST, cmdDEBUG, cmdVERIFY,
2210 cmdNAME, cmdURL, cmdFETCH, cmdLOGIN, cmdLANG, cmdSEX, cmdCAFPR,
2211 cmdFORCESIG, cmdGENERATE, cmdPASSWD, cmdPRIVATEDO, cmdWRITECERT,
2212 cmdREADCERT, cmdUNBLOCK, cmdFACTORYRESET, cmdKDFSETUP,
2213 cmdKEYATTR, cmdUIF,
2214 cmdINVCMD
2215 };
2216
2217 static struct
2218 {
2219 const char *name;
2220 enum cmdids id;
2221 int admin_only;
2222 const char *desc;
2223 } cmds[] =
2224 {
2225 { "quit" , cmdQUIT , 0, N_("quit this menu")},
2226 { "q" , cmdQUIT , 0, NULL },
2227 { "admin" , cmdADMIN , 0, N_("show admin commands")},
2228 { "help" , cmdHELP , 0, N_("show this help")},
2229 { "?" , cmdHELP , 0, NULL },
2230 { "list" , cmdLIST , 0, N_("list all available data")},
2231 { "l" , cmdLIST , 0, NULL },
2232 { "debug" , cmdDEBUG , 0, NULL },
2233 { "name" , cmdNAME , 1, N_("change card holder's name")},
2234 { "url" , cmdURL , 1, N_("change URL to retrieve key")},
2235 { "fetch" , cmdFETCH , 0, N_("fetch the key specified in the card URL")},
2236 { "login" , cmdLOGIN , 1, N_("change the login name")},
2237 { "lang" , cmdLANG , 1, N_("change the language preferences")},
2238 { "salutation",cmdSEX , 1, N_("change card holder's salutation")},
2239 { "sex" ,cmdSEX , 1, NULL }, /* Backward compatibility. */
2240 { "cafpr" , cmdCAFPR , 1, N_("change a CA fingerprint")},
2241 { "forcesig", cmdFORCESIG, 1, N_("toggle the signature force PIN flag")},
2242 { "generate", cmdGENERATE, 1, N_("generate new keys")},
2243 { "passwd" , cmdPASSWD, 0, N_("menu to change or unblock the PIN")},
2244 { "verify" , cmdVERIFY, 0, N_("verify the PIN and list all data")},
2245 { "unblock" , cmdUNBLOCK,0, N_("unblock the PIN using a Reset Code")},
2246 { "factory-reset", cmdFACTORYRESET, 1, N_("destroy all keys and data")},
2247 { "kdf-setup", cmdKDFSETUP, 1,
2248 N_("setup KDF for PIN authentication (on/single/off)")},
2249 { "key-attr", cmdKEYATTR, 1, N_("change the key attribute")},
2250 { "uif", cmdUIF, 1, N_("change the User Interaction Flag")},
2251 /* Note, that we do not announce these command yet. */
2252 { "privatedo", cmdPRIVATEDO, 0, NULL },
2253 { "readcert", cmdREADCERT, 0, NULL },
2254 { "writecert", cmdWRITECERT, 1, NULL },
2255 { NULL, cmdINVCMD, 0, NULL }
2256 };
2257
2258
2259 #ifdef HAVE_LIBREADLINE
2260
2261 /* These two functions are used by readline for command completion. */
2262
2263 static char *
command_generator(const char * text,int state)2264 command_generator(const char *text,int state)
2265 {
2266 static int list_index,len;
2267 const char *name;
2268
2269 /* If this is a new word to complete, initialize now. This includes
2270 saving the length of TEXT for efficiency, and initializing the
2271 index variable to 0. */
2272 if(!state)
2273 {
2274 list_index=0;
2275 len=strlen(text);
2276 }
2277
2278 /* Return the next partial match */
2279 while((name=cmds[list_index].name))
2280 {
2281 /* Only complete commands that have help text */
2282 if(cmds[list_index++].desc && strncmp(name,text,len)==0)
2283 return strdup(name);
2284 }
2285
2286 return NULL;
2287 }
2288
2289 static char **
card_edit_completion(const char * text,int start,int end)2290 card_edit_completion(const char *text, int start, int end)
2291 {
2292 (void)end;
2293 /* If we are at the start of a line, we try and command-complete.
2294 If not, just do nothing for now. */
2295
2296 if(start==0)
2297 return rl_completion_matches(text,command_generator);
2298
2299 rl_attempted_completion_over=1;
2300
2301 return NULL;
2302 }
2303 #endif /*HAVE_LIBREADLINE*/
2304
2305 /* Menu to edit all user changeable values on an OpenPGP card. Only
2306 Key creation is not handled here. */
2307 void
card_edit(ctrl_t ctrl,strlist_t commands)2308 card_edit (ctrl_t ctrl, strlist_t commands)
2309 {
2310 enum cmdids cmd = cmdNOP;
2311 int have_commands = !!commands;
2312 int redisplay = 1;
2313 char *answer = NULL;
2314 int allow_admin=0;
2315 char serialnobuf[50];
2316
2317
2318 if (opt.command_fd != -1)
2319 ;
2320 else if (opt.batch && !have_commands)
2321 {
2322 log_error(_("can't do this in batch mode\n"));
2323 goto leave;
2324 }
2325
2326 for (;;)
2327 {
2328 int arg_number;
2329 const char *arg_string = "";
2330 const char *arg_rest = "";
2331 char *p;
2332 int i;
2333 int cmd_admin_only;
2334
2335 tty_printf("\n");
2336 if (redisplay)
2337 {
2338 if (opt.with_colons)
2339 {
2340 current_card_status (ctrl, es_stdout,
2341 serialnobuf, DIM (serialnobuf));
2342 fflush (stdout);
2343 }
2344 else
2345 {
2346 current_card_status (ctrl, NULL,
2347 serialnobuf, DIM (serialnobuf));
2348 tty_printf("\n");
2349 }
2350 redisplay = 0;
2351 }
2352
2353 do
2354 {
2355 xfree (answer);
2356 if (have_commands)
2357 {
2358 if (commands)
2359 {
2360 answer = xstrdup (commands->d);
2361 commands = commands->next;
2362 }
2363 else if (opt.batch)
2364 {
2365 answer = xstrdup ("quit");
2366 }
2367 else
2368 have_commands = 0;
2369 }
2370
2371 if (!have_commands)
2372 {
2373 tty_enable_completion (card_edit_completion);
2374 answer = cpr_get_no_help("cardedit.prompt", _("gpg/card> "));
2375 cpr_kill_prompt();
2376 tty_disable_completion ();
2377 }
2378 trim_spaces(answer);
2379 }
2380 while ( *answer == '#' );
2381
2382 arg_number = 0; /* Yes, here is the init which egcc complains about */
2383 cmd_admin_only = 0;
2384 if (!*answer)
2385 cmd = cmdLIST; /* Default to the list command */
2386 else if (*answer == CONTROL_D)
2387 cmd = cmdQUIT;
2388 else
2389 {
2390 if ((p=strchr (answer,' ')))
2391 {
2392 *p++ = 0;
2393 trim_spaces (answer);
2394 trim_spaces (p);
2395 arg_number = atoi(p);
2396 arg_string = p;
2397 arg_rest = p;
2398 while (digitp (arg_rest))
2399 arg_rest++;
2400 while (spacep (arg_rest))
2401 arg_rest++;
2402 }
2403
2404 for (i=0; cmds[i].name; i++ )
2405 if (!ascii_strcasecmp (answer, cmds[i].name ))
2406 break;
2407
2408 cmd = cmds[i].id;
2409 cmd_admin_only = cmds[i].admin_only;
2410 }
2411
2412 if (!allow_admin && cmd_admin_only)
2413 {
2414 tty_printf ("\n");
2415 tty_printf (_("Admin-only command\n"));
2416 continue;
2417 }
2418
2419 switch (cmd)
2420 {
2421 case cmdHELP:
2422 for (i=0; cmds[i].name; i++ )
2423 if(cmds[i].desc
2424 && (!cmds[i].admin_only || (cmds[i].admin_only && allow_admin)))
2425 tty_printf("%-14s %s\n", cmds[i].name, _(cmds[i].desc) );
2426 break;
2427
2428 case cmdADMIN:
2429 if ( !strcmp (arg_string, "on") )
2430 allow_admin = 1;
2431 else if ( !strcmp (arg_string, "off") )
2432 allow_admin = 0;
2433 else if ( !strcmp (arg_string, "verify") )
2434 {
2435 /* Force verification of the Admin Command. However,
2436 this is only done if the retry counter is at initial
2437 state. */
2438 char *tmp = xmalloc (strlen (serialnobuf) + 6 + 1);
2439 strcpy (stpcpy (tmp, serialnobuf), "[CHV3]");
2440 allow_admin = !agent_scd_checkpin (tmp);
2441 xfree (tmp);
2442 }
2443 else /* Toggle. */
2444 allow_admin=!allow_admin;
2445 if(allow_admin)
2446 tty_printf(_("Admin commands are allowed\n"));
2447 else
2448 tty_printf(_("Admin commands are not allowed\n"));
2449 break;
2450
2451 case cmdVERIFY:
2452 agent_scd_checkpin (serialnobuf);
2453 redisplay = 1;
2454 break;
2455
2456 case cmdLIST:
2457 redisplay = 1;
2458 break;
2459
2460 case cmdNAME:
2461 change_name ();
2462 break;
2463
2464 case cmdURL:
2465 change_url ();
2466 break;
2467
2468 case cmdFETCH:
2469 fetch_url (ctrl);
2470 break;
2471
2472 case cmdLOGIN:
2473 change_login (arg_string);
2474 break;
2475
2476 case cmdLANG:
2477 change_lang ();
2478 break;
2479
2480 case cmdSEX:
2481 change_sex ();
2482 break;
2483
2484 case cmdCAFPR:
2485 if ( arg_number < 1 || arg_number > 3 )
2486 tty_printf ("usage: cafpr N\n"
2487 " 1 <= N <= 3\n");
2488 else
2489 change_cafpr (arg_number);
2490 break;
2491
2492 case cmdPRIVATEDO:
2493 if ( arg_number < 1 || arg_number > 4 )
2494 tty_printf ("usage: privatedo N\n"
2495 " 1 <= N <= 4\n");
2496 else
2497 change_private_do (arg_string, arg_number);
2498 break;
2499
2500 case cmdWRITECERT:
2501 if ( arg_number != 3 )
2502 tty_printf ("usage: writecert 3 < FILE\n");
2503 else
2504 change_cert (arg_rest);
2505 break;
2506
2507 case cmdREADCERT:
2508 if ( arg_number != 3 )
2509 tty_printf ("usage: readcert 3 > FILE\n");
2510 else
2511 read_cert (arg_rest);
2512 break;
2513
2514 case cmdFORCESIG:
2515 toggle_forcesig ();
2516 break;
2517
2518 case cmdGENERATE:
2519 generate_card_keys (ctrl);
2520 break;
2521
2522 case cmdPASSWD:
2523 change_pin (0, allow_admin);
2524 break;
2525
2526 case cmdUNBLOCK:
2527 change_pin (1, allow_admin);
2528 break;
2529
2530 case cmdFACTORYRESET:
2531 factory_reset ();
2532 break;
2533
2534 case cmdKDFSETUP:
2535 kdf_setup (arg_string);
2536 break;
2537
2538 case cmdKEYATTR:
2539 key_attr ();
2540 break;
2541
2542 case cmdUIF:
2543 if ( arg_number < 1 || arg_number > 3 )
2544 tty_printf ("usage: uif N [on|off|permanent]\n"
2545 " 1 <= N <= 3\n");
2546 else
2547 uif (arg_number, arg_rest);
2548 break;
2549
2550 case cmdQUIT:
2551 goto leave;
2552
2553 case cmdNOP:
2554 break;
2555
2556 case cmdINVCMD:
2557 default:
2558 tty_printf ("\n");
2559 tty_printf (_("Invalid command (try \"help\")\n"));
2560 break;
2561 } /* End command switch. */
2562 } /* End of main menu loop. */
2563
2564 leave:
2565 xfree (answer);
2566 }
2567