2007-07-05 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / sm / export.c
blobdd87246eb636022e0dd3d78403dea7429c1f2bcb
1 /* export.c
2 * Copyright (C) 2002, 2003, 2004 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 #include <config.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <errno.h>
25 #include <time.h>
26 #include <assert.h>
28 #include "gpgsm.h"
29 #include <gcrypt.h>
30 #include <ksba.h>
32 #include "keydb.h"
33 #include "exechelp.h"
34 #include "i18n.h"
38 /* A table to store a fingerprint as used in a duplicates table. We
39 don't need to hash here because a fingerprint is alrady a perfect
40 hash value. This we use the most significant bits to index the
41 table and then use a linked list for the overflow. Possible
42 enhancement for very large number of certictates: Add a second
43 level table and then resort to a linked list. */
44 struct duptable_s
46 struct duptable_s *next;
48 /* Note that we only need to store 19 bytes because the first byte
49 is implictly given by the table index (we require at least 8
50 bits). */
51 unsigned char fpr[19];
53 typedef struct duptable_s *duptable_t;
54 #define DUPTABLE_BITS 12
55 #define DUPTABLE_SIZE (1 << DUPTABLE_BITS)
58 static void print_short_info (ksba_cert_t cert, FILE *fp, estream_t stream);
59 static gpg_error_t export_p12 (ctrl_t ctrl,
60 const unsigned char *certimg, size_t certimglen,
61 const char *prompt, const char *keygrip,
62 FILE **retfp);
65 /* Create a table used to indetify duplicated certificates. */
66 static duptable_t *
67 create_duptable (void)
69 return xtrycalloc (DUPTABLE_SIZE, sizeof (duptable_t));
72 static void
73 destroy_duptable (duptable_t *table)
75 int idx;
76 duptable_t t, t2;
78 if (table)
80 for (idx=0; idx < DUPTABLE_SIZE; idx++)
81 for (t = table[idx]; t; t = t2)
83 t2 = t->next;
84 xfree (t);
86 xfree (table);
90 /* Insert the 20 byte fingerprint FPR into TABLE. Sets EXITS to true
91 if the fingerprint already exists in the table. */
92 static gpg_error_t
93 insert_duptable (duptable_t *table, unsigned char *fpr, int *exists)
95 size_t idx;
96 duptable_t t;
98 *exists = 0;
99 idx = fpr[0];
100 #if DUPTABLE_BITS > 16 || DUPTABLE_BITS < 8
101 #error cannot handle a table larger than 16 bits or smaller than 8 bits
102 #elif DUPTABLE_BITS > 8
103 idx <<= (DUPTABLE_BITS - 8);
104 idx |= (fpr[1] & ~(~0 << 4));
105 #endif
107 for (t = table[idx]; t; t = t->next)
108 if (!memcmp (t->fpr, fpr+1, 19))
109 break;
110 if (t)
112 *exists = 1;
113 return 0;
115 /* Insert that fingerprint. */
116 t = xtrymalloc (sizeof *t);
117 if (!t)
118 return gpg_error_from_syserror ();
119 memcpy (t->fpr, fpr+1, 19);
120 t->next = table[idx];
121 table[idx] = t;
122 return 0;
128 /* Export all certificates or just those given in NAMES. If STREAM is
129 not NULL the output is send to this extended stream. */
130 void
131 gpgsm_export (ctrl_t ctrl, strlist_t names, FILE *fp, estream_t stream)
133 KEYDB_HANDLE hd = NULL;
134 KEYDB_SEARCH_DESC *desc = NULL;
135 int ndesc;
136 Base64Context b64writer = NULL;
137 ksba_writer_t writer;
138 strlist_t sl;
139 ksba_cert_t cert = NULL;
140 int rc=0;
141 int count = 0;
142 int i;
143 duptable_t *dtable;
146 dtable = create_duptable ();
147 if (!dtable)
149 log_error ("creating duplicates table failed: %s\n", strerror (errno));
150 goto leave;
153 hd = keydb_new (0);
154 if (!hd)
156 log_error ("keydb_new failed\n");
157 goto leave;
160 if (!names)
161 ndesc = 1;
162 else
164 for (sl=names, ndesc=0; sl; sl = sl->next, ndesc++)
168 desc = xtrycalloc (ndesc, sizeof *desc);
169 if (!ndesc)
171 log_error ("allocating memory for export failed: %s\n",
172 gpg_strerror (out_of_core ()));
173 goto leave;
176 if (!names)
177 desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
178 else
180 for (ndesc=0, sl=names; sl; sl = sl->next)
182 rc = keydb_classify_name (sl->d, desc+ndesc);
183 if (rc)
185 log_error ("key `%s' not found: %s\n",
186 sl->d, gpg_strerror (rc));
187 rc = 0;
189 else
190 ndesc++;
194 /* If all specifications are done by fingerprint, we switch to
195 ephemeral mode so that _all_ currently available and matching
196 certificates are exported.
198 fixme: we should in this case keep a list of certificates to
199 avoid accidential export of duplicate certificates. */
200 if (names && ndesc)
202 for (i=0; (i < ndesc
203 && (desc[i].mode == KEYDB_SEARCH_MODE_FPR
204 || desc[i].mode == KEYDB_SEARCH_MODE_FPR20
205 || desc[i].mode == KEYDB_SEARCH_MODE_FPR16)); i++)
207 if (i == ndesc)
208 keydb_set_ephemeral (hd, 1);
211 while (!(rc = keydb_search (hd, desc, ndesc)))
213 unsigned char fpr[20];
214 int exists;
216 if (!names)
217 desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
219 rc = keydb_get_cert (hd, &cert);
220 if (rc)
222 log_error ("keydb_get_cert failed: %s\n", gpg_strerror (rc));
223 goto leave;
226 gpgsm_get_fingerprint (cert, 0, fpr, NULL);
227 rc = insert_duptable (dtable, fpr, &exists);
228 if (rc)
230 log_error ("inserting into duplicates table fauiled: %s\n",
231 gpg_strerror (rc));
232 goto leave;
235 if (!exists && count && !ctrl->create_pem)
237 log_info ("exporting more than one certificate "
238 "is not possible in binary mode\n");
239 log_info ("ignoring other certificates\n");
240 break;
243 if (!exists)
245 const unsigned char *image;
246 size_t imagelen;
248 image = ksba_cert_get_image (cert, &imagelen);
249 if (!image)
251 log_error ("ksba_cert_get_image failed\n");
252 goto leave;
256 if (ctrl->create_pem)
258 if (count)
260 if (stream)
261 es_putc ('\n', stream);
262 else
263 putc ('\n', fp);
265 print_short_info (cert, fp, stream);
266 if (stream)
267 es_putc ('\n', stream);
268 else
269 putc ('\n', fp);
271 count++;
273 if (!b64writer)
275 ctrl->pem_name = "CERTIFICATE";
276 rc = gpgsm_create_writer (&b64writer, ctrl, fp, stream, &writer);
277 if (rc)
279 log_error ("can't create writer: %s\n", gpg_strerror (rc));
280 goto leave;
284 rc = ksba_writer_write (writer, image, imagelen);
285 if (rc)
287 log_error ("write error: %s\n", gpg_strerror (rc));
288 goto leave;
291 if (ctrl->create_pem)
293 /* We want one certificate per PEM block */
294 rc = gpgsm_finish_writer (b64writer);
295 if (rc)
297 log_error ("write failed: %s\n", gpg_strerror (rc));
298 goto leave;
300 gpgsm_destroy_writer (b64writer);
301 b64writer = NULL;
305 ksba_cert_release (cert);
306 cert = NULL;
308 if (rc && rc != -1)
309 log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
310 else if (b64writer)
312 rc = gpgsm_finish_writer (b64writer);
313 if (rc)
315 log_error ("write failed: %s\n", gpg_strerror (rc));
316 goto leave;
320 leave:
321 gpgsm_destroy_writer (b64writer);
322 ksba_cert_release (cert);
323 xfree (desc);
324 keydb_release (hd);
325 destroy_duptable (dtable);
329 /* Export a certificates and its private key. */
330 void
331 gpgsm_p12_export (ctrl_t ctrl, const char *name, FILE *fp)
333 KEYDB_HANDLE hd;
334 KEYDB_SEARCH_DESC *desc = NULL;
335 Base64Context b64writer = NULL;
336 ksba_writer_t writer;
337 ksba_cert_t cert = NULL;
338 int rc=0;
339 const unsigned char *image;
340 size_t imagelen;
341 char *keygrip = NULL;
342 char *prompt;
343 char buffer[1024];
344 int nread;
345 FILE *datafp = NULL;
348 hd = keydb_new (0);
349 if (!hd)
351 log_error ("keydb_new failed\n");
352 goto leave;
355 desc = xtrycalloc (1, sizeof *desc);
356 if (!desc)
358 log_error ("allocating memory for export failed: %s\n",
359 gpg_strerror (out_of_core ()));
360 goto leave;
363 rc = keydb_classify_name (name, desc);
364 if (rc)
366 log_error ("key `%s' not found: %s\n",
367 name, gpg_strerror (rc));
368 goto leave;
371 /* Lookup the certificate an make sure that it is unique. */
372 rc = keydb_search (hd, desc, 1);
373 if (!rc)
375 rc = keydb_get_cert (hd, &cert);
376 if (rc)
378 log_error ("keydb_get_cert failed: %s\n", gpg_strerror (rc));
379 goto leave;
382 rc = keydb_search (hd, desc, 1);
383 if (!rc)
384 rc = gpg_error (GPG_ERR_AMBIGUOUS_NAME);
385 else if (rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF)
386 rc = 0;
387 if (rc)
389 log_error ("key `%s' not found: %s\n",
390 name, gpg_strerror (rc));
391 goto leave;
395 keygrip = gpgsm_get_keygrip_hexstring (cert);
396 if (!keygrip || gpgsm_agent_havekey (ctrl, keygrip))
398 /* Note, that the !keygrip case indicates a bad certificate. */
399 rc = gpg_error (GPG_ERR_NO_SECKEY);
400 log_error ("can't export key `%s': %s\n", name, gpg_strerror (rc));
401 goto leave;
404 image = ksba_cert_get_image (cert, &imagelen);
405 if (!image)
407 log_error ("ksba_cert_get_image failed\n");
408 goto leave;
411 if (ctrl->create_pem)
413 print_short_info (cert, fp, NULL);
414 putc ('\n', fp);
417 if (opt.p12_charset && ctrl->create_pem)
419 fprintf (fp, "The passphrase is %s encoded.\n\n",
420 opt.p12_charset);
423 ctrl->pem_name = "PKCS12";
424 rc = gpgsm_create_writer (&b64writer, ctrl, fp, NULL, &writer);
425 if (rc)
427 log_error ("can't create writer: %s\n", gpg_strerror (rc));
428 goto leave;
432 prompt = gpgsm_format_keydesc (cert);
433 rc = export_p12 (ctrl, image, imagelen, prompt, keygrip, &datafp);
434 xfree (prompt);
435 if (rc)
436 goto leave;
437 rewind (datafp);
438 while ( (nread = fread (buffer, 1, sizeof buffer, datafp)) > 0 )
439 if ((rc = ksba_writer_write (writer, buffer, nread)))
441 log_error ("write failed: %s\n", gpg_strerror (rc));
442 goto leave;
444 if (ferror (datafp))
446 rc = gpg_error_from_errno (rc);
447 log_error ("error reading temporary file: %s\n", gpg_strerror (rc));
448 goto leave;
451 if (ctrl->create_pem)
453 /* We want one certificate per PEM block */
454 rc = gpgsm_finish_writer (b64writer);
455 if (rc)
457 log_error ("write failed: %s\n", gpg_strerror (rc));
458 goto leave;
460 gpgsm_destroy_writer (b64writer);
461 b64writer = NULL;
464 ksba_cert_release (cert);
465 cert = NULL;
467 leave:
468 if (datafp)
469 fclose (datafp);
470 gpgsm_destroy_writer (b64writer);
471 ksba_cert_release (cert);
472 xfree (desc);
473 keydb_release (hd);
477 /* Call either es_putc or the plain putc. */
478 static void
479 do_putc (int value, FILE *fp, estream_t stream)
481 if (stream)
482 es_putc (value, stream);
483 else
484 putc (value, fp);
487 /* Call either es_fputs or the plain fputs. */
488 static void
489 do_fputs (const char *string, FILE *fp, estream_t stream)
491 if (stream)
492 es_fputs (string, stream);
493 else
494 fputs (string, fp);
498 /* Print some info about the certifciate CERT to FP or STREAM */
499 static void
500 print_short_info (ksba_cert_t cert, FILE *fp, estream_t stream)
502 char *p;
503 ksba_sexp_t sexp;
504 int idx;
506 for (idx=0; (p = ksba_cert_get_issuer (cert, idx)); idx++)
508 do_fputs ((!idx
509 ? "Issuer ...: "
510 : "\n aka ...: "), fp, stream);
511 if (stream)
512 gpgsm_es_print_name (stream, p);
513 else
514 gpgsm_print_name (fp, p);
515 xfree (p);
517 do_putc ('\n', fp, stream);
519 do_fputs ("Serial ...: ", fp, stream);
520 sexp = ksba_cert_get_serial (cert);
521 if (sexp)
523 int len;
524 const unsigned char *s = sexp;
526 if (*s == '(')
528 s++;
529 for (len=0; *s && *s != ':' && digitp (s); s++)
530 len = len*10 + atoi_1 (s);
531 if (*s == ':')
533 if (stream)
534 es_write_hexstring (stream, s+1, len, 0, NULL);
535 else
536 print_hexstring (fp, s+1, len, 0);
539 xfree (sexp);
541 do_putc ('\n', fp, stream);
543 for (idx=0; (p = ksba_cert_get_subject (cert, idx)); idx++)
545 do_fputs ((!idx
546 ? "Subject ..: "
547 : "\n aka ..: "), fp, stream);
548 if (stream)
549 gpgsm_es_print_name (stream, p);
550 else
551 gpgsm_print_name (fp, p);
552 xfree (p);
554 do_putc ('\n', fp, stream);
558 static gpg_error_t
559 popen_protect_tool (const char *pgmname,
560 FILE *infile, FILE *outfile, FILE **statusfile,
561 const char *prompt, const char *keygrip,
562 pid_t *pid)
564 const char *argv[20];
565 int i=0;
567 argv[i++] = "--homedir";
568 argv[i++] = opt.homedir;
569 argv[i++] = "--p12-export";
570 argv[i++] = "--have-cert";
571 argv[i++] = "--prompt";
572 argv[i++] = prompt?prompt:"";
573 argv[i++] = "--enable-status-msg";
574 if (opt.p12_charset)
576 argv[i++] = "--p12-charset";
577 argv[i++] = opt.p12_charset;
579 argv[i++] = "--",
580 argv[i++] = keygrip,
581 argv[i] = NULL;
582 assert (i < sizeof argv);
584 return gnupg_spawn_process (pgmname, argv, infile, outfile,
585 setup_pinentry_env,
586 statusfile, pid);
590 static gpg_error_t
591 export_p12 (ctrl_t ctrl, const unsigned char *certimg, size_t certimglen,
592 const char *prompt, const char *keygrip,
593 FILE **retfp)
595 const char *pgmname;
596 gpg_error_t err = 0, child_err = 0;
597 int c, cont_line;
598 unsigned int pos;
599 FILE *infp = NULL, *outfp = NULL, *fp = NULL;
600 char buffer[1024];
601 pid_t pid = -1;
602 int bad_pass = 0;
604 if (!opt.protect_tool_program || !*opt.protect_tool_program)
605 pgmname = gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL);
606 else
607 pgmname = opt.protect_tool_program;
609 infp = tmpfile ();
610 if (!infp)
612 err = gpg_error_from_syserror ();
613 log_error (_("error creating temporary file: %s\n"), strerror (errno));
614 goto cleanup;
617 if (fwrite (certimg, certimglen, 1, infp) != 1)
619 err = gpg_error_from_syserror ();
620 log_error (_("error writing to temporary file: %s\n"),
621 strerror (errno));
622 goto cleanup;
625 outfp = tmpfile ();
626 if (!outfp)
628 err = gpg_error_from_syserror ();
629 log_error (_("error creating temporary file: %s\n"), strerror (errno));
630 goto cleanup;
633 err = popen_protect_tool (pgmname, infp, outfp, &fp, prompt, keygrip, &pid);
634 if (err)
636 pid = -1;
637 goto cleanup;
639 fclose (infp);
640 infp = NULL;
642 /* Read stderr of the protect tool. */
643 pos = 0;
644 cont_line = 0;
645 while ((c=getc (fp)) != EOF)
647 /* fixme: We could here grep for status information of the
648 protect tool to figure out better error codes for
649 CHILD_ERR. */
650 buffer[pos++] = c;
651 if (pos >= sizeof buffer - 5 || c == '\n')
653 buffer[pos - (c == '\n')] = 0;
654 if (cont_line)
655 log_printf ("%s", buffer);
656 else
658 if (!strncmp (buffer, "gpg-protect-tool: [PROTECT-TOOL:] ",34))
660 char *p, *pend;
662 p = buffer + 34;
663 pend = strchr (p, ' ');
664 if (pend)
665 *pend = 0;
666 if ( !strcmp (p, "bad-passphrase"))
667 bad_pass++;
669 else
670 log_info ("%s", buffer);
672 pos = 0;
673 cont_line = (c != '\n');
677 if (pos)
679 buffer[pos] = 0;
680 if (cont_line)
681 log_printf ("%s\n", buffer);
682 else
683 log_info ("%s\n", buffer);
685 else if (cont_line)
686 log_printf ("\n");
688 /* If we found no error in the output of the child, setup a suitable
689 error code, which will later be reset if the exit status of the
690 child is 0. */
691 if (!child_err)
692 child_err = gpg_error (GPG_ERR_DECRYPT_FAILED);
694 cleanup:
695 if (infp)
696 fclose (infp);
697 if (fp)
698 fclose (fp);
699 if (pid != -1)
701 if (!gnupg_wait_process (pgmname, pid))
702 child_err = 0;
704 if (!err)
705 err = child_err;
706 if (err)
708 if (outfp)
709 fclose (outfp);
711 else
712 *retfp = outfp;
713 if (bad_pass)
715 /* During export this is the passphrase used to unprotect the
716 key and not the pkcs#12 thing as in export. Therefore we can
717 issue the regular passphrase status. FIXME: replace the all
718 zero keyid by a regular one. */
719 gpgsm_status (ctrl, STATUS_BAD_PASSPHRASE, "0000000000000000");
721 return err;