Move password repetition from gpg to gpg-agent.
[gnupg.git] / agent / protect-tool.c
blob848ad9f4bcd17d9f8d5605afbb1315fad881dc7a
1 /* protect-tool.c - A tool to test the secret key protection
2 * Copyright (C) 2002, 2003, 2004, 2006 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 <stddef.h>
25 #include <stdarg.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <assert.h>
29 #include <sys/stat.h>
30 #include <unistd.h>
31 #ifdef HAVE_LOCALE_H
32 #include <locale.h>
33 #endif
34 #ifdef HAVE_LANGINFO_CODESET
35 #include <langinfo.h>
36 #endif
37 #ifdef HAVE_DOSISH_SYSTEM
38 #include <fcntl.h> /* for setmode() */
39 #endif
41 #define JNLIB_NEED_LOG_LOGV
42 #include "agent.h"
43 #include "minip12.h"
44 #include "simple-pwquery.h"
45 #include "i18n.h"
46 #include "sysutils.h"
49 enum cmd_and_opt_values
50 { aNull = 0,
51 oVerbose = 'v',
52 oArmor = 'a',
53 oPassphrase = 'P',
55 oProtect = 'p',
56 oUnprotect = 'u',
58 oNoVerbose = 500,
59 oShadow,
60 oShowShadowInfo,
61 oShowKeygrip,
62 oCanonical,
64 oP12Import,
65 oP12Export,
66 oP12Charset,
67 oStore,
68 oForce,
69 oHaveCert,
70 oNoFailOnExist,
71 oHomedir,
72 oPrompt,
73 oStatusMsg,
75 aTest };
77 struct rsa_secret_key_s
79 gcry_mpi_t n; /* public modulus */
80 gcry_mpi_t e; /* public exponent */
81 gcry_mpi_t d; /* exponent */
82 gcry_mpi_t p; /* prime p. */
83 gcry_mpi_t q; /* prime q. */
84 gcry_mpi_t u; /* inverse of p mod q. */
88 static const char *opt_homedir;
89 static int opt_armor;
90 static int opt_canonical;
91 static int opt_store;
92 static int opt_force;
93 static int opt_no_fail_on_exist;
94 static int opt_have_cert;
95 static const char *opt_passphrase;
96 static char *opt_prompt;
97 static int opt_status_msg;
98 static const char *opt_p12_charset;
100 static char *get_passphrase (int promptno, int opt_check);
101 static char *get_new_passphrase (int promptno);
102 static void release_passphrase (char *pw);
103 static int store_private_key (const unsigned char *grip,
104 const void *buffer, size_t length, int force);
107 static ARGPARSE_OPTS opts[] = {
109 { 301, NULL, 0, N_("@Options:\n ") },
111 { oVerbose, "verbose", 0, "verbose" },
112 { oArmor, "armor", 0, "write output in advanced format" },
113 { oCanonical, "canonical", 0, "write output in canonical format" },
114 { oPassphrase, "passphrase", 2, "|STRING|use passphrase STRING" },
115 { oProtect, "protect", 256, "protect a private key"},
116 { oUnprotect, "unprotect", 256, "unprotect a private key"},
117 { oShadow, "shadow", 256, "create a shadow entry for a public key"},
118 { oShowShadowInfo, "show-shadow-info", 256, "return the shadow info"},
119 { oShowKeygrip, "show-keygrip", 256, "show the \"keygrip\""},
121 { oP12Import, "p12-import", 256, "import a pkcs#12 encoded private key"},
122 { oP12Export, "p12-export", 256, "export a private key pkcs#12 encoded"},
123 { oP12Charset,"p12-charset", 2,
124 "|NAME|set charset for a new PKCS#12 passphrase to NAME" },
125 { oHaveCert, "have-cert", 0, "certificate to export provided on STDIN"},
126 { oStore, "store", 0, "store the created key in the appropriate place"},
127 { oForce, "force", 0, "force overwriting"},
128 { oNoFailOnExist, "no-fail-on-exist", 0, "@" },
129 { oHomedir, "homedir", 2, "@" },
130 { oPrompt, "prompt", 2, "|ESCSTRING|use ESCSTRING as prompt in pinentry"},
131 { oStatusMsg, "enable-status-msg", 0, "@"},
136 static const char *
137 my_strusage (int level)
139 const char *p;
140 switch (level)
142 case 11: p = "gpg-protect-tool (GnuPG)";
143 break;
144 case 13: p = VERSION; break;
145 case 17: p = PRINTABLE_OS_NAME; break;
146 case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
147 break;
148 case 1:
149 case 40: p = _("Usage: gpg-protect-tool [options] (-h for help)\n");
150 break;
151 case 41: p = _("Syntax: gpg-protect-tool [options] [args]\n"
152 "Secret key maintenance tool\n");
153 break;
155 default: p = NULL;
157 return p;
161 /* Include the implementation of map_spwq_error. */
162 MAP_SPWQ_ERROR_IMPL
164 /* static void */
165 /* print_mpi (const char *text, gcry_mpi_t a) */
166 /* { */
167 /* char *buf; */
168 /* void *bufaddr = &buf; */
169 /* int rc; */
171 /* rc = gcry_mpi_aprint (GCRYMPI_FMT_HEX, bufaddr, NULL, a); */
172 /* if (rc) */
173 /* log_info ("%s: [error printing number: %s]\n", text, gpg_strerror (rc)); */
174 /* else */
175 /* { */
176 /* log_info ("%s: %s\n", text, buf); */
177 /* gcry_free (buf); */
178 /* } */
179 /* } */
183 static unsigned char *
184 make_canonical (const char *fname, const char *buf, size_t buflen)
186 int rc;
187 size_t erroff, len;
188 gcry_sexp_t sexp;
189 unsigned char *result;
191 rc = gcry_sexp_sscan (&sexp, &erroff, buf, buflen);
192 if (rc)
194 log_error ("invalid S-Expression in `%s' (off=%u): %s\n",
195 fname, (unsigned int)erroff, gpg_strerror (rc));
196 return NULL;
198 len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_CANON, NULL, 0);
199 assert (len);
200 result = xmalloc (len);
201 len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_CANON, result, len);
202 assert (len);
203 gcry_sexp_release (sexp);
204 return result;
207 static char *
208 make_advanced (const unsigned char *buf, size_t buflen)
210 int rc;
211 size_t erroff, len;
212 gcry_sexp_t sexp;
213 char *result;
215 rc = gcry_sexp_sscan (&sexp, &erroff, (const char*)buf, buflen);
216 if (rc)
218 log_error ("invalid canonical S-Expression (off=%u): %s\n",
219 (unsigned int)erroff, gpg_strerror (rc));
220 return NULL;
222 len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_ADVANCED, NULL, 0);
223 assert (len);
224 result = xmalloc (len);
225 len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_ADVANCED, result, len);
226 assert (len);
227 gcry_sexp_release (sexp);
228 return result;
232 static char *
233 read_file (const char *fname, size_t *r_length)
235 FILE *fp;
236 char *buf;
237 size_t buflen;
239 if (!strcmp (fname, "-"))
241 size_t nread, bufsize = 0;
243 fp = stdin;
244 #ifdef HAVE_DOSISH_SYSTEM
245 setmode ( fileno(fp) , O_BINARY );
246 #endif
247 buf = NULL;
248 buflen = 0;
249 #define NCHUNK 8192
252 bufsize += NCHUNK;
253 if (!buf)
254 buf = xmalloc (bufsize);
255 else
256 buf = xrealloc (buf, bufsize);
258 nread = fread (buf+buflen, 1, NCHUNK, fp);
259 if (nread < NCHUNK && ferror (fp))
261 log_error ("error reading `[stdin]': %s\n", strerror (errno));
262 xfree (buf);
263 return NULL;
265 buflen += nread;
267 while (nread == NCHUNK);
268 #undef NCHUNK
271 else
273 struct stat st;
275 fp = fopen (fname, "rb");
276 if (!fp)
278 log_error ("can't open `%s': %s\n", fname, strerror (errno));
279 return NULL;
282 if (fstat (fileno(fp), &st))
284 log_error ("can't stat `%s': %s\n", fname, strerror (errno));
285 fclose (fp);
286 return NULL;
289 buflen = st.st_size;
290 buf = xmalloc (buflen+1);
291 if (fread (buf, buflen, 1, fp) != 1)
293 log_error ("error reading `%s': %s\n", fname, strerror (errno));
294 fclose (fp);
295 xfree (buf);
296 return NULL;
298 fclose (fp);
301 *r_length = buflen;
302 return buf;
306 static unsigned char *
307 read_key (const char *fname)
309 char *buf;
310 size_t buflen;
311 unsigned char *key;
313 buf = read_file (fname, &buflen);
314 if (!buf)
315 return NULL;
316 key = make_canonical (fname, buf, buflen);
317 xfree (buf);
318 return key;
323 static void
324 read_and_protect (const char *fname)
326 int rc;
327 unsigned char *key;
328 unsigned char *result;
329 size_t resultlen;
330 char *pw;
332 key = read_key (fname);
333 if (!key)
334 return;
336 pw = get_passphrase (1, 0);
337 rc = agent_protect (key, pw, &result, &resultlen);
338 release_passphrase (pw);
339 xfree (key);
340 if (rc)
342 log_error ("protecting the key failed: %s\n", gpg_strerror (rc));
343 return;
346 if (opt_armor)
348 char *p = make_advanced (result, resultlen);
349 xfree (result);
350 if (!p)
351 return;
352 result = (unsigned char*)p;
353 resultlen = strlen (p);
356 fwrite (result, resultlen, 1, stdout);
357 xfree (result);
361 static void
362 read_and_unprotect (const char *fname)
364 int rc;
365 unsigned char *key;
366 unsigned char *result;
367 size_t resultlen;
368 char *pw;
369 gnupg_isotime_t protected_at;
371 key = read_key (fname);
372 if (!key)
373 return;
375 rc = agent_unprotect (key, (pw=get_passphrase (1, 0)),
376 protected_at, &result, &resultlen);
377 release_passphrase (pw);
378 xfree (key);
379 if (rc)
381 if (opt_status_msg)
382 log_info ("[PROTECT-TOOL:] bad-passphrase\n");
383 log_error ("unprotecting the key failed: %s\n", gpg_strerror (rc));
384 return;
386 if (opt.verbose)
387 log_info ("key protection done at %.4s-%.2s-%.2s %.2s:%.2s:%s\n",
388 protected_at, protected_at+4, protected_at+6,
389 protected_at+9, protected_at+11, protected_at+13);
392 if (opt_armor)
394 char *p = make_advanced (result, resultlen);
395 xfree (result);
396 if (!p)
397 return;
398 result = (unsigned char*)p;
399 resultlen = strlen (p);
402 fwrite (result, resultlen, 1, stdout);
403 xfree (result);
408 static void
409 read_and_shadow (const char *fname)
411 int rc;
412 unsigned char *key;
413 unsigned char *result;
414 size_t resultlen;
415 unsigned char dummy_info[] = "(8:313233342:43)";
417 key = read_key (fname);
418 if (!key)
419 return;
421 rc = agent_shadow_key (key, dummy_info, &result);
422 xfree (key);
423 if (rc)
425 log_error ("shadowing the key failed: %s\n", gpg_strerror (rc));
426 return;
428 resultlen = gcry_sexp_canon_len (result, 0, NULL,NULL);
429 assert (resultlen);
431 if (opt_armor)
433 char *p = make_advanced (result, resultlen);
434 xfree (result);
435 if (!p)
436 return;
437 result = (unsigned char*)p;
438 resultlen = strlen (p);
441 fwrite (result, resultlen, 1, stdout);
442 xfree (result);
445 static void
446 show_shadow_info (const char *fname)
448 int rc;
449 unsigned char *key;
450 const unsigned char *info;
451 size_t infolen;
453 key = read_key (fname);
454 if (!key)
455 return;
457 rc = agent_get_shadow_info (key, &info);
458 xfree (key);
459 if (rc)
461 log_error ("get_shadow_info failed: %s\n", gpg_strerror (rc));
462 return;
464 infolen = gcry_sexp_canon_len (info, 0, NULL,NULL);
465 assert (infolen);
467 if (opt_armor)
469 char *p = make_advanced (info, infolen);
470 if (!p)
471 return;
472 fwrite (p, strlen (p), 1, stdout);
473 xfree (p);
475 else
476 fwrite (info, infolen, 1, stdout);
480 static void
481 show_file (const char *fname)
483 unsigned char *key;
484 size_t keylen;
485 char *p;
487 key = read_key (fname);
488 if (!key)
489 return;
491 keylen = gcry_sexp_canon_len (key, 0, NULL,NULL);
492 assert (keylen);
494 if (opt_canonical)
496 fwrite (key, keylen, 1, stdout);
498 else
500 p = make_advanced (key, keylen);
501 if (p)
503 fwrite (p, strlen (p), 1, stdout);
504 xfree (p);
507 xfree (key);
510 static void
511 show_keygrip (const char *fname)
513 unsigned char *key;
514 gcry_sexp_t private;
515 unsigned char grip[20];
516 int i;
518 key = read_key (fname);
519 if (!key)
520 return;
522 if (gcry_sexp_new (&private, key, 0, 0))
524 log_error ("gcry_sexp_new failed\n");
525 return;
527 xfree (key);
529 if (!gcry_pk_get_keygrip (private, grip))
531 log_error ("can't calculate keygrip\n");
532 return;
534 gcry_sexp_release (private);
536 for (i=0; i < 20; i++)
537 printf ("%02X", grip[i]);
538 putchar ('\n');
542 static int
543 rsa_key_check (struct rsa_secret_key_s *skey)
545 int err = 0;
546 gcry_mpi_t t = gcry_mpi_snew (0);
547 gcry_mpi_t t1 = gcry_mpi_snew (0);
548 gcry_mpi_t t2 = gcry_mpi_snew (0);
549 gcry_mpi_t phi = gcry_mpi_snew (0);
551 /* check that n == p * q */
552 gcry_mpi_mul (t, skey->p, skey->q);
553 if (gcry_mpi_cmp( t, skey->n) )
555 log_error ("RSA oops: n != p * q\n");
556 err++;
559 /* check that p is less than q */
560 if (gcry_mpi_cmp (skey->p, skey->q) > 0)
562 gcry_mpi_t tmp;
564 log_info ("swapping secret primes\n");
565 tmp = gcry_mpi_copy (skey->p);
566 gcry_mpi_set (skey->p, skey->q);
567 gcry_mpi_set (skey->q, tmp);
568 gcry_mpi_release (tmp);
569 /* and must recompute u of course */
570 gcry_mpi_invm (skey->u, skey->p, skey->q);
573 /* check that e divides neither p-1 nor q-1 */
574 gcry_mpi_sub_ui (t, skey->p, 1 );
575 gcry_mpi_div (NULL, t, t, skey->e, 0);
576 if (!gcry_mpi_cmp_ui( t, 0) )
578 log_error ("RSA oops: e divides p-1\n");
579 err++;
581 gcry_mpi_sub_ui (t, skey->q, 1);
582 gcry_mpi_div (NULL, t, t, skey->e, 0);
583 if (!gcry_mpi_cmp_ui( t, 0))
585 log_info ( "RSA oops: e divides q-1\n" );
586 err++;
589 /* check that d is correct. */
590 gcry_mpi_sub_ui (t1, skey->p, 1);
591 gcry_mpi_sub_ui (t2, skey->q, 1);
592 gcry_mpi_mul (phi, t1, t2);
593 gcry_mpi_invm (t, skey->e, phi);
594 if (gcry_mpi_cmp (t, skey->d))
595 { /* no: try universal exponent. */
596 gcry_mpi_gcd (t, t1, t2);
597 gcry_mpi_div (t, NULL, phi, t, 0);
598 gcry_mpi_invm (t, skey->e, t);
599 if (gcry_mpi_cmp (t, skey->d))
601 log_error ("RSA oops: bad secret exponent\n");
602 err++;
606 /* check for correctness of u */
607 gcry_mpi_invm (t, skey->p, skey->q);
608 if (gcry_mpi_cmp (t, skey->u))
610 log_info ( "RSA oops: bad u parameter\n");
611 err++;
614 if (err)
615 log_info ("RSA secret key check failed\n");
617 gcry_mpi_release (t);
618 gcry_mpi_release (t1);
619 gcry_mpi_release (t2);
620 gcry_mpi_release (phi);
622 return err? -1:0;
626 /* A callback used by p12_parse to return a certificate. */
627 static void
628 import_p12_cert_cb (void *opaque, const unsigned char *cert, size_t certlen)
630 struct b64state state;
631 gpg_error_t err, err2;
633 (void)opaque;
635 err = b64enc_start (&state, stdout, "CERTIFICATE");
636 if (!err)
637 err = b64enc_write (&state, cert, certlen);
638 err2 = b64enc_finish (&state);
639 if (!err)
640 err = err2;
641 if (err)
642 log_error ("error writing armored certificate: %s\n", gpg_strerror (err));
645 static void
646 import_p12_file (const char *fname)
648 char *buf;
649 unsigned char *result;
650 size_t buflen, resultlen, buf_off;
651 int i;
652 int rc;
653 gcry_mpi_t *kparms;
654 struct rsa_secret_key_s sk;
655 gcry_sexp_t s_key;
656 unsigned char *key;
657 unsigned char grip[20];
658 char *pw;
660 /* fixme: we should release some stuff on error */
662 buf = read_file (fname, &buflen);
663 if (!buf)
664 return;
666 /* GnuPG 2.0.4 accidently created binary P12 files with the string
667 "The passphrase is %s encoded.\n\n" prepended to the ASN.1 data.
668 We fix that here. */
669 if (buflen > 29 && !memcmp (buf, "The passphrase is ", 18))
671 for (buf_off=18; buf_off < buflen && buf[buf_off] != '\n'; buf_off++)
673 buf_off++;
674 if (buf_off < buflen && buf[buf_off] == '\n')
675 buf_off++;
677 else
678 buf_off = 0;
680 kparms = p12_parse ((unsigned char*)buf+buf_off, buflen-buf_off,
681 (pw=get_passphrase (2, 0)),
682 import_p12_cert_cb, NULL);
683 release_passphrase (pw);
684 xfree (buf);
685 if (!kparms)
687 log_error ("error parsing or decrypting the PKCS-12 file\n");
688 return;
690 for (i=0; kparms[i]; i++)
692 if (i != 8)
694 log_error ("invalid structure of private key\n");
695 return;
699 /* print_mpi (" n", kparms[0]); */
700 /* print_mpi (" e", kparms[1]); */
701 /* print_mpi (" d", kparms[2]); */
702 /* print_mpi (" p", kparms[3]); */
703 /* print_mpi (" q", kparms[4]); */
704 /* print_mpi ("dmp1", kparms[5]); */
705 /* print_mpi ("dmq1", kparms[6]); */
706 /* print_mpi (" u", kparms[7]); */
708 sk.n = kparms[0];
709 sk.e = kparms[1];
710 sk.d = kparms[2];
711 sk.q = kparms[3];
712 sk.p = kparms[4];
713 sk.u = kparms[7];
714 if (rsa_key_check (&sk))
715 return;
716 /* print_mpi (" n", sk.n); */
717 /* print_mpi (" e", sk.e); */
718 /* print_mpi (" d", sk.d); */
719 /* print_mpi (" p", sk.p); */
720 /* print_mpi (" q", sk.q); */
721 /* print_mpi (" u", sk.u); */
723 /* Create an S-expresion from the parameters. */
724 rc = gcry_sexp_build (&s_key, NULL,
725 "(private-key(rsa(n%m)(e%m)(d%m)(p%m)(q%m)(u%m)))",
726 sk.n, sk.e, sk.d, sk.p, sk.q, sk.u, NULL);
727 for (i=0; i < 8; i++)
728 gcry_mpi_release (kparms[i]);
729 gcry_free (kparms);
730 if (rc)
732 log_error ("failed to created S-expression from key: %s\n",
733 gpg_strerror (rc));
734 return;
737 /* Compute the keygrip. */
738 if (!gcry_pk_get_keygrip (s_key, grip))
740 log_error ("can't calculate keygrip\n");
741 return;
743 log_info ("keygrip: ");
744 for (i=0; i < 20; i++)
745 log_printf ("%02X", grip[i]);
746 log_printf ("\n");
748 /* Convert to canonical encoding. */
749 buflen = gcry_sexp_sprint (s_key, GCRYSEXP_FMT_CANON, NULL, 0);
750 assert (buflen);
751 key = gcry_xmalloc_secure (buflen);
752 buflen = gcry_sexp_sprint (s_key, GCRYSEXP_FMT_CANON, key, buflen);
753 assert (buflen);
754 gcry_sexp_release (s_key);
757 pw = get_new_passphrase (4);
758 if (!pw)
759 rc = gpg_error (GPG_ERR_CANCELED);
760 else
761 rc = agent_protect (key, pw, &result, &resultlen);
762 release_passphrase (pw);
763 xfree (key);
764 if (rc)
766 log_error ("protecting the key failed: %s\n", gpg_strerror (rc));
767 return;
770 if (opt_armor)
772 char *p = make_advanced (result, resultlen);
773 xfree (result);
774 if (!p)
775 return;
776 result = (unsigned char*)p;
777 resultlen = strlen (p);
780 if (opt_store)
781 store_private_key (grip, result, resultlen, opt_force);
782 else
783 fwrite (result, resultlen, 1, stdout);
785 xfree (result);
790 static gcry_mpi_t *
791 sexp_to_kparms (gcry_sexp_t sexp)
793 gcry_sexp_t list, l2;
794 const char *name;
795 const char *s;
796 size_t n;
797 int i, idx;
798 const char *elems;
799 gcry_mpi_t *array;
801 list = gcry_sexp_find_token (sexp, "private-key", 0 );
802 if(!list)
803 return NULL;
804 l2 = gcry_sexp_cadr (list);
805 gcry_sexp_release (list);
806 list = l2;
807 name = gcry_sexp_nth_data (list, 0, &n);
808 if(!name || n != 3 || memcmp (name, "rsa", 3))
810 gcry_sexp_release (list);
811 return NULL;
814 /* Parameter names used with RSA. */
815 elems = "nedpqu";
816 array = xcalloc (strlen(elems) + 1, sizeof *array);
817 for (idx=0, s=elems; *s; s++, idx++ )
819 l2 = gcry_sexp_find_token (list, s, 1);
820 if (!l2)
822 for (i=0; i<idx; i++)
823 gcry_mpi_release (array[i]);
824 xfree (array);
825 gcry_sexp_release (list);
826 return NULL; /* required parameter not found */
828 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
829 gcry_sexp_release (l2);
830 if (!array[idx])
832 for (i=0; i<idx; i++)
833 gcry_mpi_release (array[i]);
834 xfree (array);
835 gcry_sexp_release (list);
836 return NULL; /* required parameter is invalid */
840 gcry_sexp_release (list);
841 return array;
845 /* Check whether STRING is a KEYGRIP, i.e has the correct length and
846 does only consist of uppercase hex characters. */
847 static int
848 is_keygrip (const char *string)
850 int i;
852 for(i=0; string[i] && i < 41; i++)
853 if (!strchr("01234567890ABCDEF", string[i]))
854 return 0;
855 return i == 40;
859 static void
860 export_p12_file (const char *fname)
862 int rc;
863 gcry_mpi_t kparms[9], *kp;
864 unsigned char *key;
865 size_t keylen;
866 gcry_sexp_t private;
867 struct rsa_secret_key_s sk;
868 int i;
869 unsigned char *cert = NULL;
870 size_t certlen = 0;
871 int keytype;
872 size_t keylen_for_wipe = 0;
873 char *pw;
875 if ( is_keygrip (fname) )
877 char hexgrip[40+4+1];
878 char *p;
880 assert (strlen(fname) == 40);
881 strcpy (stpcpy (hexgrip, fname), ".key");
883 p = make_filename (opt_homedir, GNUPG_PRIVATE_KEYS_DIR, hexgrip, NULL);
884 key = read_key (p);
885 xfree (p);
887 else
888 key = read_key (fname);
890 if (!key)
891 return;
893 keytype = agent_private_key_type (key);
894 if (keytype == PRIVATE_KEY_PROTECTED)
896 unsigned char *tmpkey;
897 size_t tmplen;
899 rc = agent_unprotect (key, (pw=get_passphrase (1, 0)),
900 NULL, &tmpkey, &tmplen);
901 release_passphrase (pw);
902 if (rc)
904 if (opt_status_msg && gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE )
905 log_info ("[PROTECT-TOOL:] bad-passphrase\n");
906 log_error ("unprotecting key `%s' failed: %s\n",
907 fname, gpg_strerror (rc));
908 xfree (key);
909 return;
911 xfree (key);
912 key = tmpkey;
913 keylen_for_wipe = tmplen;
915 keytype = agent_private_key_type (key);
918 if (keytype == PRIVATE_KEY_SHADOWED)
920 log_error ("`%s' is a shadowed private key - can't export it\n", fname);
921 wipememory (key, keylen_for_wipe);
922 xfree (key);
923 return;
925 else if (keytype != PRIVATE_KEY_CLEAR)
927 log_error ("\%s' is not a private key\n", fname);
928 wipememory (key, keylen_for_wipe);
929 xfree (key);
930 return;
934 if (opt_have_cert)
936 cert = (unsigned char*)read_file ("-", &certlen);
937 if (!cert)
939 wipememory (key, keylen_for_wipe);
940 xfree (key);
941 return;
946 if (gcry_sexp_new (&private, key, 0, 0))
948 log_error ("gcry_sexp_new failed\n");
949 wipememory (key, keylen_for_wipe);
950 xfree (key);
951 xfree (cert);
952 return;
954 wipememory (key, keylen_for_wipe);
955 xfree (key);
957 kp = sexp_to_kparms (private);
958 gcry_sexp_release (private);
959 if (!kp)
961 log_error ("error converting key parameters\n");
962 xfree (cert);
963 return;
965 sk.n = kp[0];
966 sk.e = kp[1];
967 sk.d = kp[2];
968 sk.p = kp[3];
969 sk.q = kp[4];
970 sk.u = kp[5];
971 xfree (kp);
974 kparms[0] = sk.n;
975 kparms[1] = sk.e;
976 kparms[2] = sk.d;
977 kparms[3] = sk.q;
978 kparms[4] = sk.p;
979 kparms[5] = gcry_mpi_snew (0); /* compute d mod (p-1) */
980 gcry_mpi_sub_ui (kparms[5], kparms[3], 1);
981 gcry_mpi_mod (kparms[5], sk.d, kparms[5]);
982 kparms[6] = gcry_mpi_snew (0); /* compute d mod (q-1) */
983 gcry_mpi_sub_ui (kparms[6], kparms[4], 1);
984 gcry_mpi_mod (kparms[6], sk.d, kparms[6]);
985 kparms[7] = sk.u;
986 kparms[8] = NULL;
988 pw = get_new_passphrase (3);
989 if (!pw)
990 key = NULL;
991 else
992 key = p12_build (kparms, cert, certlen, pw, opt_p12_charset, &keylen);
993 release_passphrase (pw);
994 xfree (cert);
995 for (i=0; i < 8; i++)
996 gcry_mpi_release (kparms[i]);
997 if (!key)
998 return;
1000 #ifdef HAVE_DOSISH_SYSTEM
1001 setmode ( fileno (stdout) , O_BINARY );
1002 #endif
1003 fwrite (key, keylen, 1, stdout);
1004 xfree (key);
1009 /* Do the percent and plus/space unescaping in place and return the
1010 length of the valid buffer. */
1011 static size_t
1012 percent_plus_unescape (unsigned char *string)
1014 unsigned char *p = string;
1015 size_t n = 0;
1017 while (*string)
1019 if (*string == '%' && string[1] && string[2])
1021 string++;
1022 *p++ = xtoi_2 (string);
1023 n++;
1024 string+= 2;
1026 else if (*string == '+')
1028 *p++ = ' ';
1029 n++;
1030 string++;
1032 else
1034 *p++ = *string++;
1035 n++;
1039 return n;
1042 /* Remove percent and plus escaping and make sure that the reuslt is a
1043 string. This is done in place. Returns STRING. */
1044 static char *
1045 percent_plus_unescape_string (char *string)
1047 unsigned char *p = (unsigned char*)string;
1048 size_t n;
1050 n = percent_plus_unescape (p);
1051 p[n] = 0;
1053 return string;
1058 main (int argc, char **argv )
1060 ARGPARSE_ARGS pargs;
1061 int cmd = 0;
1062 const char *fname;
1064 set_strusage (my_strusage);
1065 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
1066 log_set_prefix ("gpg-protect-tool", 1);
1068 /* Make sure that our subsystems are ready. */
1069 i18n_init ();
1070 init_common_subsystems ();
1072 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
1074 log_fatal( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
1075 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
1078 setup_libgcrypt_logging ();
1079 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
1082 opt_homedir = default_homedir ();
1085 pargs.argc = &argc;
1086 pargs.argv = &argv;
1087 pargs.flags= 1; /* (do not remove the args) */
1088 while (arg_parse (&pargs, opts) )
1090 switch (pargs.r_opt)
1092 case oVerbose: opt.verbose++; break;
1093 case oArmor: opt_armor=1; break;
1094 case oCanonical: opt_canonical=1; break;
1095 case oHomedir: opt_homedir = pargs.r.ret_str; break;
1097 case oProtect: cmd = oProtect; break;
1098 case oUnprotect: cmd = oUnprotect; break;
1099 case oShadow: cmd = oShadow; break;
1100 case oShowShadowInfo: cmd = oShowShadowInfo; break;
1101 case oShowKeygrip: cmd = oShowKeygrip; break;
1102 case oP12Import: cmd = oP12Import; break;
1103 case oP12Export: cmd = oP12Export; break;
1104 case oP12Charset: opt_p12_charset = pargs.r.ret_str; break;
1106 case oPassphrase: opt_passphrase = pargs.r.ret_str; break;
1107 case oStore: opt_store = 1; break;
1108 case oForce: opt_force = 1; break;
1109 case oNoFailOnExist: opt_no_fail_on_exist = 1; break;
1110 case oHaveCert: opt_have_cert = 1; break;
1111 case oPrompt: opt_prompt = pargs.r.ret_str; break;
1112 case oStatusMsg: opt_status_msg = 1; break;
1114 default : pargs.err = 2; break;
1117 if (log_get_errorcount(0))
1118 exit(2);
1120 fname = "-";
1121 if (argc == 1)
1122 fname = *argv;
1123 else if (argc > 1)
1124 usage (1);
1126 /* Tell simple-pwquery about the the standard socket name. */
1128 char *tmp = make_filename (opt_homedir, "S.gpg-agent", NULL);
1129 simple_pw_set_socket (tmp);
1130 xfree (tmp);
1133 if (opt_prompt)
1134 opt_prompt = percent_plus_unescape_string (xstrdup (opt_prompt));
1136 if (cmd == oProtect)
1137 read_and_protect (fname);
1138 else if (cmd == oUnprotect)
1139 read_and_unprotect (fname);
1140 else if (cmd == oShadow)
1141 read_and_shadow (fname);
1142 else if (cmd == oShowShadowInfo)
1143 show_shadow_info (fname);
1144 else if (cmd == oShowKeygrip)
1145 show_keygrip (fname);
1146 else if (cmd == oP12Import)
1147 import_p12_file (fname);
1148 else if (cmd == oP12Export)
1149 export_p12_file (fname);
1150 else
1151 show_file (fname);
1153 agent_exit (0);
1154 return 8; /*NOTREACHED*/
1157 void
1158 agent_exit (int rc)
1160 rc = rc? rc : log_get_errorcount(0)? 2 : 0;
1161 exit (rc);
1165 /* Return the passphrase string and ask the agent if it has not been
1166 set from the command line PROMPTNO select the prompt to display:
1167 0 = default
1168 1 = taken from the option --prompt
1169 2 = for unprotecting a pkcs#12 object
1170 3 = for protecting a new pkcs#12 object
1171 4 = for protecting an imported pkcs#12 in our system
1172 5 = reenter the passphrase
1173 When adding 100 to the values, a "does not match - try again" error
1174 message is shown.
1176 static char *
1177 get_passphrase (int promptno, int opt_check)
1179 char *pw;
1180 int err;
1181 const char *desc;
1182 char *orig_codeset;
1183 int error_msgno;
1185 if (opt_passphrase)
1186 return xstrdup (opt_passphrase);
1188 error_msgno = promptno / 100;
1189 promptno %= 100;
1191 orig_codeset = i18n_switchto_utf8 ();
1193 if (promptno == 1 && opt_prompt)
1194 desc = opt_prompt;
1195 else if (promptno == 2)
1196 desc = _("Please enter the passphrase to unprotect the "
1197 "PKCS#12 object.");
1198 else if (promptno == 3)
1199 desc = _("Please enter the passphrase to protect the "
1200 "new PKCS#12 object.");
1201 else if (promptno == 4)
1202 desc = _("Please enter the passphrase to protect the "
1203 "imported object within the GnuPG system.");
1204 else if (promptno == 5)
1205 desc = _("Please re-enter this passphrase");
1206 else
1207 desc = _("Please enter the passphrase or the PIN\n"
1208 "needed to complete this operation.");
1210 pw = simple_pwquery (NULL,
1211 error_msgno == 1? _("does not match - try again"):NULL,
1212 _("Passphrase:"), desc, opt_check, &err);
1213 err = map_spwq_error (err);
1215 i18n_switchback (orig_codeset);
1217 if (!pw)
1219 if (err)
1220 log_error (_("error while asking for the passphrase: %s\n"),
1221 gpg_strerror (err));
1222 else
1223 log_info (_("cancelled\n"));
1224 agent_exit (0);
1227 return pw;
1231 /* Same as get_passphrase but requests it a second time and compares
1232 it to the one entered the first time. */
1233 static char *
1234 get_new_passphrase (int promptno)
1236 char *pw;
1237 int i, secondpromptno;
1239 pw = get_passphrase (promptno, 1);
1240 if (!pw)
1241 return NULL; /* Canceled. */
1242 if (!*pw)
1243 return pw; /* Empty passphrase - no need to ask for repeating it. */
1245 secondpromptno = 5;
1246 for (i=0; i < 3; i++)
1248 char *pw2 = get_passphrase (secondpromptno, 0);
1249 if (!pw2)
1251 xfree (pw);
1252 return NULL; /* Canceled. */
1254 if (!strcmp (pw, pw2))
1256 xfree (pw2);
1257 return pw; /* Okay. */
1259 secondpromptno = 105;
1260 xfree (pw2);
1262 xfree (pw);
1263 return NULL; /* 3 times repeated wrong - cancel. */
1268 static void
1269 release_passphrase (char *pw)
1271 if (pw)
1273 wipememory (pw, strlen (pw));
1274 xfree (pw);
1278 static int
1279 store_private_key (const unsigned char *grip,
1280 const void *buffer, size_t length, int force)
1282 int i;
1283 char *fname;
1284 FILE *fp;
1285 char hexgrip[40+4+1];
1287 for (i=0; i < 20; i++)
1288 sprintf (hexgrip+2*i, "%02X", grip[i]);
1289 strcpy (hexgrip+40, ".key");
1291 fname = make_filename (opt_homedir, GNUPG_PRIVATE_KEYS_DIR, hexgrip, NULL);
1292 if (force)
1293 fp = fopen (fname, "wb");
1294 else
1296 if (!access (fname, F_OK))
1298 if (opt_status_msg)
1299 log_info ("[PROTECT-TOOL:] secretkey-exists\n");
1300 if (opt_no_fail_on_exist)
1301 log_info ("secret key file `%s' already exists\n", fname);
1302 else
1303 log_error ("secret key file `%s' already exists\n", fname);
1304 xfree (fname);
1305 return opt_no_fail_on_exist? 0 : -1;
1307 fp = fopen (fname, "wbx"); /* FIXME: the x is a GNU extension - let
1308 configure check whether this actually
1309 works */
1312 if (!fp)
1314 log_error ("can't create `%s': %s\n", fname, strerror (errno));
1315 xfree (fname);
1316 return -1;
1319 if (fwrite (buffer, length, 1, fp) != 1)
1321 log_error ("error writing `%s': %s\n", fname, strerror (errno));
1322 fclose (fp);
1323 remove (fname);
1324 xfree (fname);
1325 return -1;
1327 if ( fclose (fp) )
1329 log_error ("error closing `%s': %s\n", fname, strerror (errno));
1330 remove (fname);
1331 xfree (fname);
1332 return -1;
1334 log_info ("secret key stored as `%s'\n", fname);
1336 if (opt_status_msg)
1337 log_info ("[PROTECT-TOOL:] secretkey-stored\n");
1339 xfree (fname);
1340 return 0;