app-openpgp changes
[gnupg.git] / scd / sc-copykeys.c
blob275bcf8773e4ccab182e4ca219daa6e2e1f07439
1 /* sc-copykeys.c - A tool to store keys on a smartcard.
2 * Copyright (C) 2003 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>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <assert.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <unistd.h>
30 #define JNLIB_NEED_LOG_LOGV
31 #include "scdaemon.h"
32 #include <gcrypt.h>
34 #include "../common/ttyio.h"
35 #include "../common/simple-pwquery.h"
36 #include "apdu.h" /* for open_reader */
37 #include "atr.h"
38 #include "app-common.h"
40 #define _(a) (a)
43 enum cmd_and_opt_values
44 { oVerbose = 'v',
45 oReaderPort = 500,
46 octapiDriver,
47 oDebug,
48 oDebugAll,
50 aTest };
53 static ARGPARSE_OPTS opts[] = {
55 { 301, NULL, 0, "@Options:\n " },
57 { oVerbose, "verbose", 0, "verbose" },
58 { oReaderPort, "reader-port", 2, "|N|connect to reader at port N"},
59 { octapiDriver, "ctapi-driver", 2, "NAME|use NAME as ctAPI driver"},
60 { oDebug, "debug" ,4|16, "set debugging flags"},
61 { oDebugAll, "debug-all" ,0, "enable full debugging"},
62 {0}
66 static void copykeys (APP app, const char *fname);
69 static const char *
70 my_strusage (int level)
72 const char *p;
73 switch (level)
75 case 11: p = "sc-copykeys (GnuPG)";
76 break;
77 case 13: p = VERSION; break;
78 case 17: p = PRINTABLE_OS_NAME; break;
79 case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
80 break;
81 case 1:
82 case 40: p = _("Usage: sc-copykeys [options] (-h for help)\n");
83 break;
84 case 41: p = _("Syntax: sc-copykeys [options] "
85 "file-with-key\n"
86 "Copy keys to a smartcards\n");
87 break;
89 default: p = NULL;
91 return p;
95 int
96 main (int argc, char **argv )
98 ARGPARSE_ARGS pargs;
99 int slot, rc;
100 const char *reader_port = NULL;
101 struct app_ctx_s appbuf;
103 memset (&appbuf, 0, sizeof appbuf);
105 set_strusage (my_strusage);
106 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
107 log_set_prefix ("sc-copykeys", 1);
109 /* check that the libraries are suitable. Do it here because
110 the option parsing may need services of the library */
111 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
113 log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
114 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
117 setup_libgcrypt_logging ();
118 gcry_control (GCRYCTL_DISABLE_SECMEM, 0); /* FIXME - we want to use it */
119 /* FIXME? gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);*/
121 pargs.argc = &argc;
122 pargs.argv = &argv;
123 pargs.flags= 1; /* do not remove the args */
124 while (arg_parse (&pargs, opts) )
126 switch (pargs.r_opt)
128 case oVerbose: opt.verbose++; break;
129 case oDebug: opt.debug |= pargs.r.ret_ulong; break;
130 case oDebugAll: opt.debug = ~0; break;
131 case oReaderPort: reader_port = pargs.r.ret_str; break;
132 case octapiDriver: opt.ctapi_driver = pargs.r.ret_str; break;
133 default : pargs.err = 2; break;
136 if (log_get_errorcount(0))
137 exit(2);
139 if (argc != 1)
140 usage (1);
142 slot = apdu_open_reader (reader_port);
143 if (slot == -1)
144 exit (1);
145 if (apdu_connect (slot))
146 exit (1);
148 /* FIXME: Use select_application. */
149 appbuf.slot = slot;
150 rc = app_select_openpgp (&appbuf);
151 if (rc)
153 log_error ("selecting openpgp failed: %s\n", gpg_strerror (rc));
154 exit (1);
156 appbuf.initialized = 1;
157 log_info ("openpgp application selected\n");
159 copykeys (&appbuf, *argv);
162 return 0;
167 void
168 send_status_info (CTRL ctrl, const char *keyword, ...)
170 /* DUMMY */
175 static char *
176 read_file (const char *fname, size_t *r_length)
178 FILE *fp;
179 struct stat st;
180 char *buf;
181 size_t buflen;
183 fp = fname? fopen (fname, "rb") : stdin;
184 if (!fp)
186 log_error ("can't open `%s': %s\n",
187 fname? fname: "[stdin]", strerror (errno));
188 return NULL;
191 if (fstat (fileno(fp), &st))
193 log_error ("can't stat `%s': %s\n",
194 fname? fname: "[stdin]", strerror (errno));
195 if (fname)
196 fclose (fp);
197 return NULL;
200 buflen = st.st_size;
201 buf = xmalloc (buflen+1);
202 if (fread (buf, buflen, 1, fp) != 1)
204 log_error ("error reading `%s': %s\n",
205 fname? fname: "[stdin]", strerror (errno));
206 if (fname)
207 fclose (fp);
208 xfree (buf);
209 return NULL;
211 if (fname)
212 fclose (fp);
214 *r_length = buflen;
215 return buf;
219 static gcry_sexp_t
220 read_key (const char *fname)
222 char *buf;
223 size_t buflen;
224 gcry_sexp_t private;
225 int rc;
227 buf = read_file (fname, &buflen);
228 if (!buf)
229 return NULL;
231 rc = gcry_sexp_new (&private, buf, buflen, 1);
232 if (rc)
234 log_error ("gcry_sexp_new failed: %s\n", gpg_strerror (rc));
235 return NULL;
237 xfree (buf);
239 return private;
244 static gcry_mpi_t *
245 sexp_to_kparms (gcry_sexp_t sexp, unsigned long *created)
247 gcry_sexp_t list, l2;
248 const char *name;
249 const char *s;
250 size_t n;
251 int i, idx;
252 const char *elems;
253 gcry_mpi_t *array;
255 *created = 0;
256 list = gcry_sexp_find_token (sexp, "private-key", 0 );
257 if(!list)
258 return NULL;
260 /* quick hack to get the creation time. */
261 l2 = gcry_sexp_find_token (list, "created", 0);
262 if (l2 && (name = gcry_sexp_nth_data (l2, 1, &n)))
264 char *tmp = xmalloc (n+1);
265 memcpy (tmp, name, n);
266 tmp[n] = 0;
267 *created = strtoul (tmp, NULL, 10);
268 xfree (tmp);
270 gcry_sexp_release (l2);
271 l2 = gcry_sexp_cadr (list);
272 gcry_sexp_release (list);
273 list = l2;
274 name = gcry_sexp_nth_data (list, 0, &n);
275 if(!name || n != 3 || memcmp (name, "rsa", 3))
277 gcry_sexp_release (list);
278 return NULL;
281 /* Parameter names used with RSA. */
282 elems = "nedpqu";
283 array = xcalloc (strlen(elems) + 1, sizeof *array);
284 for (idx=0, s=elems; *s; s++, idx++ )
286 l2 = gcry_sexp_find_token (list, s, 1);
287 if (!l2)
289 for (i=0; i<idx; i++)
290 gcry_mpi_release (array[i]);
291 xfree (array);
292 gcry_sexp_release (list);
293 return NULL; /* required parameter not found */
295 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
296 gcry_sexp_release (l2);
297 if (!array[idx])
299 for (i=0; i<idx; i++)
300 gcry_mpi_release (array[i]);
301 xfree (array);
302 gcry_sexp_release (list);
303 return NULL; /* required parameter is invalid */
307 gcry_sexp_release (list);
308 return array;
312 /* Return true if the SHA1 fingerprint FPR consists only of zeroes. */
313 static int
314 fpr_is_zero (const char *fpr)
316 int i;
318 for (i=0; i < 20 && !fpr[i]; i++)
320 return (i == 20);
324 static void
325 show_sha1_fpr (const unsigned char *fpr)
327 int i;
329 if (fpr)
331 for (i=0; i < 20 ; i+=2, fpr += 2 )
333 if (i == 10 )
334 tty_printf (" ");
335 tty_printf (" %02X%02X", *fpr, fpr[1]);
338 else
339 tty_printf (" [none]");
340 tty_printf ("\n");
343 /* Query the card, show a list of already stored keys and ask the user
344 where to store the key. Returns the key number or 0 for cancel
345 operation. */
346 static int
347 query_card (APP app)
349 int keyno = 0;
350 char *serialno, *disp_name, *pubkey_url;
351 unsigned char *fpr1, *fpr2, *fpr3;
354 if (app_openpgp_cardinfo (app,
355 &serialno,
356 &disp_name,
357 &pubkey_url,
358 &fpr1, &fpr2, &fpr3))
359 return 0;
362 for (;;)
364 char *answer;
366 tty_printf ("\n");
368 tty_printf ("Serial number ....: %s\n",
369 serialno? serialno : "[none]");
370 tty_printf ("Name of cardholder: %s\n",
371 disp_name && *disp_name? disp_name : "[not set]");
372 tty_printf ("URL of public key : %s\n",
373 pubkey_url && *pubkey_url? pubkey_url : "[not set]");
374 tty_printf ("Signature key ....:");
375 show_sha1_fpr (fpr1);
376 tty_printf ("Encryption key....:");
377 show_sha1_fpr (fpr2);
378 tty_printf ("Authentication key:");
379 show_sha1_fpr (fpr3);
381 tty_printf ("\n"
382 "1 - store as signature key and reset usage counter\n"
383 "2 - store as encryption key\n"
384 "3 - store as authentication key\n"
385 "Q - quit\n"
386 "\n");
388 answer = tty_get("Your selection? ");
389 tty_kill_prompt();
390 if (strlen (answer) != 1)
392 else if ( *answer == '1' )
394 if ( (fpr1 && !fpr_is_zero (fpr1)) )
396 tty_printf ("\n");
397 log_error ("WARNING: signature key does already exists!\n");
398 tty_printf ("\n");
399 if ( tty_get_answer_is_yes ("Replace existing key? ") )
401 keyno = 1;
402 break;
405 else
407 keyno = 1;
408 break;
411 else if ( *answer == '2' )
413 if ( (fpr2 && !fpr_is_zero (fpr2)) )
415 tty_printf ("\n");
416 log_error ("WARNING: encryption key does already exists!\n");
417 tty_printf ("\n");
418 if ( tty_get_answer_is_yes ("Replace existing key? ") )
420 keyno = 2;
421 break;
424 else
426 keyno = 2;
427 break;
430 else if ( *answer == '3' )
432 if ( (fpr3 && !fpr_is_zero (fpr3)) )
434 tty_printf ("\n");
435 log_error ("WARNING: authentication key does already exists!\n");
436 tty_printf ("\n");
437 if ( tty_get_answer_is_yes ("Replace existing key? ") )
439 keyno = 3;
440 break;
443 else
445 keyno = 3;
446 break;
449 else if ( *answer == 'q' || *answer == 'Q')
451 keyno = 0;
452 break;
456 xfree (serialno);
457 xfree (disp_name);
458 xfree (pubkey_url);
459 xfree (fpr1);
460 xfree (fpr2);
461 xfree (fpr3);
463 return keyno;
467 /* Callback function to ask for a PIN. */
468 static gpg_error_t
469 pincb (void *arg, const char *prompt, char **pinvalue)
471 char *pin = xstrdup ("12345678");
473 /* pin = simple_pwquery (NULL, NULL, prompt, */
474 /* "We need the admin's PIN to store the key on the card", */
475 /* 0, NULL); */
476 /* if (!pin) */
477 /* return gpg_error (GPG_ERR_CANCELED); */
481 *pinvalue = pin;
482 return 0;
486 /* This function expects a file (or NULL for stdin) with the secret
487 and public key parameters. This file should consist of an
488 S-expression as used by gpg-agent. Only the unprotected format is
489 supported. Example:
491 (private-key
492 (rsa
493 (n #00e0ce9..[some bytes not shown]..51#)
494 (e #010001#)
495 (d #046129F..[some bytes not shown]..81#)
496 (p #00e861b..[some bytes not shown]..f1#)
497 (q #00f7a7c..[some bytes not shown]..61#)
498 (u #304559a..[some bytes not shown]..9b#))
499 (uri http://foo.bar x-foo:whatever_you_want))
502 static void
503 copykeys (APP app, const char *fname)
505 int rc;
506 gcry_sexp_t private;
507 gcry_mpi_t *mpis, rsa_n, rsa_e, rsa_p, rsa_q;
508 unsigned int nbits;
509 size_t n;
510 unsigned char *template, *tp;
511 unsigned char m[128], e[4];
512 size_t mlen, elen;
513 unsigned long creation_date;
514 time_t created_at;
515 int keyno;
517 if (!strcmp (fname, "-"))
518 fname = NULL;
520 private = read_key (fname);
521 if (!private)
522 exit (1);
524 mpis = sexp_to_kparms (private, &creation_date);
525 if (!creation_date)
527 log_info ("no creation date found - assuming current date\n");
528 created_at = time (NULL);
530 else
531 created_at = creation_date;
532 gcry_sexp_release (private);
533 if (!mpis)
535 log_error ("invalid structure of key file or not RSA\n");
536 exit (1);
538 /* MPIS is now an array with the key parameters as defined by OpenPGP. */
539 rsa_n = mpis[0];
540 rsa_e = mpis[1];
541 gcry_mpi_release (mpis[2]);
542 rsa_p = mpis[3];
543 rsa_q = mpis[4];
544 gcry_mpi_release (mpis[5]);
545 xfree (mpis);
547 nbits = gcry_mpi_get_nbits (rsa_e);
548 if (nbits < 2 || nbits > 32)
550 log_error ("public exponent too large (more than 32 bits)\n");
551 goto failure;
553 nbits = gcry_mpi_get_nbits (rsa_p);
554 if (nbits != 512)
556 log_error ("length of first RSA prime is not 512\n");
557 goto failure;
559 nbits = gcry_mpi_get_nbits (rsa_q);
560 if (nbits != 512)
562 log_error ("length of second RSA prime is not 512\n");
563 goto failure;
566 nbits = gcry_mpi_get_nbits (rsa_n);
567 if (nbits != 1024)
569 log_error ("length of RSA modulus is not 1024\n");
570 goto failure;
573 keyno = query_card (app);
574 if (!keyno)
575 goto failure;
577 /* Build the private key template as described in section 4.3.3.6 of
578 the specs.
579 0xC0 <length> public exponent
580 0xC1 <length> prime p
581 0xC2 <length> prime q */
582 template = tp = xmalloc (1+2 + 1+1+4 + 1+1+64 + 1+1+64);
583 *tp++ = 0xC0;
584 *tp++ = 4;
585 rc = gcry_mpi_print (GCRYMPI_FMT_USG, tp, 4, &n, rsa_e);
586 if (rc)
588 log_error ("mpi_print failed: %s\n", gpg_strerror (rc));
589 goto failure;
591 assert (n <= 4);
592 memcpy (e, tp, n);
593 elen = n;
594 if (n != 4)
596 memmove (tp+4-n, tp, 4-n);
597 memset (tp, 0, 4-n);
599 tp += 4;
601 *tp++ = 0xC1;
602 *tp++ = 64;
603 rc = gcry_mpi_print (GCRYMPI_FMT_USG, tp, 64, &n, rsa_p);
604 if (rc)
606 log_error ("mpi_print failed: %s\n", gpg_strerror (rc));
607 goto failure;
609 assert (n == 64);
610 tp += 64;
612 *tp++ = 0xC2;
613 *tp++ = 64;
614 rc = gcry_mpi_print (GCRYMPI_FMT_USG, tp, 64, &n, rsa_q);
615 if (rc)
617 log_error ("mpi_print failed: %s\n", gpg_strerror (rc));
618 goto failure;
620 assert (n == 64);
621 tp += 64;
622 assert (tp - template == 138);
624 /* (we need the modulus to calculate the fingerprint) */
625 rc = gcry_mpi_print (GCRYMPI_FMT_USG, m, 128, &n, rsa_n);
626 if (rc)
628 log_error ("mpi_print failed: %s\n", gpg_strerror (rc));
629 goto failure;
631 assert (n == 128);
632 mlen = 128;
635 rc = app_openpgp_storekey (app, keyno,
636 template, tp - template,
637 created_at,
638 m, mlen,
639 e, elen,
640 pincb, NULL);
642 if (rc)
644 log_error ("error storing key: %s\n", gpg_strerror (rc));
645 goto failure;
647 log_info ("key successfully stored\n");
649 unsigned char *mm, *ee;
650 size_t mmlen, eelen;
651 int i;
653 rc = app_openpgp_readkey (app, keyno, &mm, &mmlen, &ee, &eelen);
654 if (rc)
656 log_error ("error reading key back: %s\n", gpg_strerror (rc));
657 goto failure;
660 /* Strip leading zeroes. */
661 for (i=0; i < mmlen && !mm[i]; i++)
663 mmlen -= i;
664 memmove (mm, mm+i, mmlen);
665 for (i=0; i < eelen && !ee[i]; i++)
667 eelen -= i;
668 memmove (ee, ee+i, eelen);
670 if (eelen != elen || mmlen != mlen)
672 log_error ("key parameter length mismatch (n=%u/%u, e=%u/%u)\n",
673 (unsigned int)mlen, (unsigned int)mmlen,
674 (unsigned int)elen, (unsigned int)eelen);
675 xfree (mm);
676 xfree (ee);
677 goto failure;
680 if (memcmp (m, mm, mlen))
682 log_error ("key parameter n mismatch\n");
683 log_printhex ("original n: ", m, mlen);
684 log_printhex (" copied n: ", mm, mlen);
685 xfree (mm);
686 xfree (ee);
687 goto failure;
689 if (memcmp (e, ee, elen))
691 log_error ("key parameter e mismatch\n");
692 log_printhex ("original e: ", e, elen);
693 log_printhex (" copied e: ", ee, elen);
694 xfree (mm);
695 xfree (ee);
696 goto failure;
698 xfree (mm);
699 xfree (ee);
703 gcry_mpi_release (rsa_e);
704 gcry_mpi_release (rsa_p);
705 gcry_mpi_release (rsa_q);
706 gcry_mpi_release (rsa_n);
707 return;
709 failure:
710 gcry_mpi_release (rsa_e);
711 gcry_mpi_release (rsa_p);
712 gcry_mpi_release (rsa_q);
713 gcry_mpi_release (rsa_n);
714 exit (1);