agent/
[gnupg.git] / sm / import.c
blob5a0eded8ff3c9ba1782317ab3391b770dc4b36f0
1 /* import.c - Import certificates
2 * Copyright (C) 2001, 2003, 2004, 2009 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 #include <config.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <errno.h>
25 #include <time.h>
26 #include <assert.h>
27 #include <unistd.h>
29 #include "gpgsm.h"
30 #include <gcrypt.h>
31 #include <ksba.h>
33 #include "keydb.h"
34 #include "exechelp.h"
35 #include "i18n.h"
36 #include "sysutils.h"
37 #include "../kbx/keybox.h" /* for KEYBOX_FLAG_* */
40 struct stats_s {
41 unsigned long count;
42 unsigned long imported;
43 unsigned long unchanged;
44 unsigned long not_imported;
45 unsigned long secret_read;
46 unsigned long secret_imported;
47 unsigned long secret_dups;
51 static gpg_error_t parse_p12 (ctrl_t ctrl, ksba_reader_t reader, FILE **retfp,
52 struct stats_s *stats);
56 static void
57 print_imported_status (ctrl_t ctrl, ksba_cert_t cert, int new_cert)
59 char *fpr;
61 fpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1);
62 if (new_cert)
63 gpgsm_status2 (ctrl, STATUS_IMPORTED, fpr, "[X.509]", NULL);
65 gpgsm_status2 (ctrl, STATUS_IMPORT_OK,
66 new_cert? "1":"0", fpr, NULL);
68 xfree (fpr);
72 /* Print an IMPORT_PROBLEM status. REASON is one of:
73 0 := "No specific reason given".
74 1 := "Invalid Certificate".
75 2 := "Issuer Certificate missing".
76 3 := "Certificate Chain too long".
77 4 := "Error storing certificate".
79 static void
80 print_import_problem (ctrl_t ctrl, ksba_cert_t cert, int reason)
82 char *fpr = NULL;
83 char buf[25];
84 int i;
86 sprintf (buf, "%d", reason);
87 if (cert)
89 fpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1);
90 /* detetect an error (all high) value */
91 for (i=0; fpr[i] == 'F'; i++)
93 if (!fpr[i])
95 xfree (fpr);
96 fpr = NULL;
99 gpgsm_status2 (ctrl, STATUS_IMPORT_PROBLEM, buf, fpr, NULL);
100 xfree (fpr);
104 void
105 print_imported_summary (ctrl_t ctrl, struct stats_s *stats)
107 char buf[14*25];
109 if (!opt.quiet)
111 log_info (_("total number processed: %lu\n"), stats->count);
112 if (stats->imported)
114 log_info (_(" imported: %lu"), stats->imported );
115 log_printf ("\n");
117 if (stats->unchanged)
118 log_info (_(" unchanged: %lu\n"), stats->unchanged);
119 if (stats->secret_read)
120 log_info (_(" secret keys read: %lu\n"), stats->secret_read );
121 if (stats->secret_imported)
122 log_info (_(" secret keys imported: %lu\n"), stats->secret_imported );
123 if (stats->secret_dups)
124 log_info (_(" secret keys unchanged: %lu\n"), stats->secret_dups );
125 if (stats->not_imported)
126 log_info (_(" not imported: %lu\n"), stats->not_imported);
129 sprintf(buf, "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
130 stats->count,
131 0l /*stats->no_user_id*/,
132 stats->imported,
133 0l /*stats->imported_rsa*/,
134 stats->unchanged,
135 0l /*stats->n_uids*/,
136 0l /*stats->n_subk*/,
137 0l /*stats->n_sigs*/,
138 0l /*stats->n_revoc*/,
139 stats->secret_read,
140 stats->secret_imported,
141 stats->secret_dups,
142 0l /*stats->skipped_new_keys*/,
143 stats->not_imported
145 gpgsm_status (ctrl, STATUS_IMPORT_RES, buf);
150 static void
151 check_and_store (ctrl_t ctrl, struct stats_s *stats,
152 ksba_cert_t cert, int depth)
154 int rc;
156 if (stats)
157 stats->count++;
158 if ( depth >= 50 )
160 log_error (_("certificate chain too long\n"));
161 if (stats)
162 stats->not_imported++;
163 print_import_problem (ctrl, cert, 3);
164 return;
167 /* Some basic checks, but don't care about missing certificates;
168 this is so that we are able to import entire certificate chains
169 w/o requiring a special order (i.e. root-CA first). This used
170 to be different but because gpgsm_verify even imports
171 certificates without any checks, it doesn't matter much and the
172 code gets much cleaner. A housekeeping function to remove
173 certificates w/o an anchor would be nice, though.
175 Optionally we do a full validation in addition to the basic test.
177 rc = gpgsm_basic_cert_check (ctrl, cert);
178 if (!rc && ctrl->with_validation)
179 rc = gpgsm_validate_chain (ctrl, cert, "", NULL, 0, NULL, 0, NULL);
180 if (!rc || (!ctrl->with_validation
181 && gpg_err_code (rc) == GPG_ERR_MISSING_CERT) )
183 int existed;
185 if (!keydb_store_cert (cert, 0, &existed))
187 ksba_cert_t next = NULL;
189 if (!existed)
191 print_imported_status (ctrl, cert, 1);
192 if (stats)
193 stats->imported++;
195 else
197 print_imported_status (ctrl, cert, 0);
198 if (stats)
199 stats->unchanged++;
202 if (opt.verbose > 1 && existed)
204 if (depth)
205 log_info ("issuer certificate already in DB\n");
206 else
207 log_info ("certificate already in DB\n");
209 else if (opt.verbose && !existed)
211 if (depth)
212 log_info ("issuer certificate imported\n");
213 else
214 log_info ("certificate imported\n");
217 /* Now lets walk up the chain and import all certificates up
218 the chain. This is required in case we already stored
219 parent certificates in the ephemeral keybox. Do not
220 update the statistics, though. */
221 if (!gpgsm_walk_cert_chain (ctrl, cert, &next))
223 check_and_store (ctrl, NULL, next, depth+1);
224 ksba_cert_release (next);
227 else
229 log_error (_("error storing certificate\n"));
230 if (stats)
231 stats->not_imported++;
232 print_import_problem (ctrl, cert, 4);
235 else
237 log_error (_("basic certificate checks failed - not imported\n"));
238 if (stats)
239 stats->not_imported++;
240 print_import_problem (ctrl, cert,
241 gpg_err_code (rc) == GPG_ERR_MISSING_CERT? 2 :
242 gpg_err_code (rc) == GPG_ERR_BAD_CERT? 1 : 0);
249 static int
250 import_one (ctrl_t ctrl, struct stats_s *stats, int in_fd)
252 int rc;
253 Base64Context b64reader = NULL;
254 ksba_reader_t reader;
255 ksba_cert_t cert = NULL;
256 ksba_cms_t cms = NULL;
257 FILE *fp = NULL;
258 ksba_content_type_t ct;
259 int any = 0;
261 fp = fdopen ( dup (in_fd), "rb");
262 if (!fp)
264 rc = gpg_error (gpg_err_code_from_errno (errno));
265 log_error ("fdopen() failed: %s\n", strerror (errno));
266 goto leave;
269 rc = gpgsm_create_reader (&b64reader, ctrl, fp, 1, &reader);
270 if (rc)
272 log_error ("can't create reader: %s\n", gpg_strerror (rc));
273 goto leave;
277 /* We need to loop here to handle multiple PEM objects in one
278 file. */
281 ksba_cms_release (cms); cms = NULL;
282 ksba_cert_release (cert); cert = NULL;
284 ct = ksba_cms_identify (reader);
285 if (ct == KSBA_CT_SIGNED_DATA)
286 { /* This is probably a signed-only message - import the certs */
287 ksba_stop_reason_t stopreason;
288 int i;
290 rc = ksba_cms_new (&cms);
291 if (rc)
292 goto leave;
294 rc = ksba_cms_set_reader_writer (cms, reader, NULL);
295 if (rc)
297 log_error ("ksba_cms_set_reader_writer failed: %s\n",
298 gpg_strerror (rc));
299 goto leave;
304 rc = ksba_cms_parse (cms, &stopreason);
305 if (rc)
307 log_error ("ksba_cms_parse failed: %s\n", gpg_strerror (rc));
308 goto leave;
311 if (stopreason == KSBA_SR_BEGIN_DATA)
312 log_info ("not a certs-only message\n");
314 while (stopreason != KSBA_SR_READY);
316 for (i=0; (cert=ksba_cms_get_cert (cms, i)); i++)
318 check_and_store (ctrl, stats, cert, 0);
319 ksba_cert_release (cert);
320 cert = NULL;
322 if (!i)
323 log_error ("no certificate found\n");
324 else
325 any = 1;
327 else if (ct == KSBA_CT_PKCS12)
328 { /* This seems to be a pkcs12 message. We use an external
329 tool to parse the message and to store the private keys.
330 We need to use a another reader here to parse the
331 certificate we included in the p12 file; then we continue
332 to look for other pkcs12 files (works only if they are in
333 PEM format. */
334 FILE *certfp;
335 Base64Context b64p12rdr;
336 ksba_reader_t p12rdr;
338 rc = parse_p12 (ctrl, reader, &certfp, stats);
339 if (!rc)
341 any = 1;
343 rewind (certfp);
344 rc = gpgsm_create_reader (&b64p12rdr, ctrl, certfp, 1, &p12rdr);
345 if (rc)
347 log_error ("can't create reader: %s\n", gpg_strerror (rc));
348 fclose (certfp);
349 goto leave;
354 ksba_cert_release (cert); cert = NULL;
355 rc = ksba_cert_new (&cert);
356 if (!rc)
358 rc = ksba_cert_read_der (cert, p12rdr);
359 if (!rc)
360 check_and_store (ctrl, stats, cert, 0);
362 ksba_reader_clear (p12rdr, NULL, NULL);
364 while (!rc && !gpgsm_reader_eof_seen (b64p12rdr));
366 if (gpg_err_code (rc) == GPG_ERR_EOF)
367 rc = 0;
368 gpgsm_destroy_reader (b64p12rdr);
369 fclose (certfp);
370 if (rc)
371 goto leave;
374 else if (ct == KSBA_CT_NONE)
375 { /* Failed to identify this message - assume a certificate */
377 rc = ksba_cert_new (&cert);
378 if (rc)
379 goto leave;
381 rc = ksba_cert_read_der (cert, reader);
382 if (rc)
383 goto leave;
385 check_and_store (ctrl, stats, cert, 0);
386 any = 1;
388 else
390 log_error ("can't extract certificates from input\n");
391 rc = gpg_error (GPG_ERR_NO_DATA);
394 ksba_reader_clear (reader, NULL, NULL);
396 while (!gpgsm_reader_eof_seen (b64reader));
398 leave:
399 if (any && gpg_err_code (rc) == GPG_ERR_EOF)
400 rc = 0;
401 ksba_cms_release (cms);
402 ksba_cert_release (cert);
403 gpgsm_destroy_reader (b64reader);
404 if (fp)
405 fclose (fp);
406 return rc;
411 /* Re-import certifciates. IN_FD is a list of linefeed delimited
412 fingerprints t re-import. The actual re-import is done by clearing
413 the ephemeral flag. */
414 static int
415 reimport_one (ctrl_t ctrl, struct stats_s *stats, int in_fd)
417 gpg_error_t err = 0;
418 estream_t fp = NULL;
419 char line[100]; /* Sufficient for a fingerprint. */
420 KEYDB_HANDLE kh;
421 KEYDB_SEARCH_DESC desc;
422 ksba_cert_t cert = NULL;
423 unsigned int flags;
425 kh = keydb_new (0);
426 if (!kh)
428 err = gpg_error (GPG_ERR_ENOMEM);;
429 log_error (_("failed to allocate keyDB handle\n"));
430 goto leave;
432 keydb_set_ephemeral (kh, 1);
434 fp = es_fdopen_nc (in_fd, "r");
435 if (!fp)
437 err = gpg_error_from_syserror ();
438 log_error ("es_fdopen(%d) failed: %s\n", in_fd, gpg_strerror (err));
439 goto leave;
442 while (es_fgets (line, DIM(line)-1, fp) )
444 if (*line && line[strlen(line)-1] != '\n')
446 err = gpg_error (GPG_ERR_LINE_TOO_LONG);
447 goto leave;
449 trim_spaces (line);
450 if (!*line)
451 continue;
453 stats->count++;
455 err = keydb_classify_name (line, &desc);
456 if (err)
458 print_import_problem (ctrl, NULL, 0);
459 stats->not_imported++;
460 continue;
463 keydb_search_reset (kh);
464 err = keydb_search (kh, &desc, 1);
465 if (err)
467 print_import_problem (ctrl, NULL, 0);
468 stats->not_imported++;
469 continue;
472 ksba_cert_release (cert);
473 cert = NULL;
474 err = keydb_get_cert (kh, &cert);
475 if (err)
477 log_error ("keydb_get_cert() failed: %s\n", gpg_strerror (err));
478 print_import_problem (ctrl, NULL, 1);
479 stats->not_imported++;
480 continue;
483 err = keydb_get_flags (kh, KEYBOX_FLAG_BLOB, 0, &flags);
484 if (err)
486 log_error (_("error getting stored flags: %s\n"), gpg_strerror (err));
487 print_imported_status (ctrl, cert, 0);
488 stats->not_imported++;
489 continue;
491 if ( !(flags & KEYBOX_FLAG_BLOB_EPHEMERAL) )
493 print_imported_status (ctrl, cert, 0);
494 stats->unchanged++;
495 continue;
498 err = keydb_set_cert_flags (cert, 1, KEYBOX_FLAG_BLOB, 0,
499 KEYBOX_FLAG_BLOB_EPHEMERAL, 0);
500 if (err)
502 log_error ("clearing ephemeral flag failed: %s\n",
503 gpg_strerror (err));
504 print_import_problem (ctrl, cert, 0);
505 stats->not_imported++;
506 continue;
509 print_imported_status (ctrl, cert, 1);
510 stats->imported++;
512 err = 0;
513 if (es_ferror (fp))
515 err = gpg_error_from_syserror ();
516 log_error ("error reading fd %d: %s\n", in_fd, gpg_strerror (err));
517 goto leave;
520 leave:
521 ksba_cert_release (cert);
522 keydb_release (kh);
523 es_fclose (fp);
524 return err;
530 gpgsm_import (ctrl_t ctrl, int in_fd, int reimport_mode)
532 int rc;
533 struct stats_s stats;
535 memset (&stats, 0, sizeof stats);
536 if (reimport_mode)
537 rc = reimport_one (ctrl, &stats, in_fd);
538 else
539 rc = import_one (ctrl, &stats, in_fd);
540 print_imported_summary (ctrl, &stats);
541 /* If we never printed an error message do it now so that a command
542 line invocation will return with an error (log_error keeps a
543 global errorcount) */
544 if (rc && !log_get_errorcount (0))
545 log_error (_("error importing certificate: %s\n"), gpg_strerror (rc));
546 return rc;
551 gpgsm_import_files (ctrl_t ctrl, int nfiles, char **files,
552 int (*of)(const char *fname))
554 int rc = 0;
555 struct stats_s stats;
557 memset (&stats, 0, sizeof stats);
559 if (!nfiles)
560 rc = import_one (ctrl, &stats, 0);
561 else
563 for (; nfiles && !rc ; nfiles--, files++)
565 int fd = of (*files);
566 rc = import_one (ctrl, &stats, fd);
567 close (fd);
568 if (rc == -1)
569 rc = 0;
572 print_imported_summary (ctrl, &stats);
573 /* If we never printed an error message do it now so that a command
574 line invocation will return with an error (log_error keeps a
575 global errorcount) */
576 if (rc && !log_get_errorcount (0))
577 log_error (_("error importing certificate: %s\n"), gpg_strerror (rc));
578 return rc;
582 /* Fork and exec the protecttool, connect the file descriptor of
583 INFILE to stdin, return a new stream in STATUSFILE, write the
584 output to OUTFILE and the pid of the process in PID. Returns 0 on
585 success or an error code. */
586 static gpg_error_t
587 popen_protect_tool (ctrl_t ctrl, const char *pgmname,
588 FILE *infile, FILE *outfile, FILE **statusfile, pid_t *pid)
590 const char *argv[22];
591 int i=0;
593 /* Make sure that the agent is running so that the protect tool is
594 able to ask for a passphrase. This has only an effect under W32
595 where the agent is started on demand; sending a NOP does not harm
596 on other platforms. This is not really necessary anymore because
597 the protect tool does this now by itself; it does not harm either. */
598 gpgsm_agent_send_nop (ctrl);
600 argv[i++] = "--homedir";
601 argv[i++] = opt.homedir;
602 argv[i++] = "--p12-import";
603 argv[i++] = "--store";
604 argv[i++] = "--no-fail-on-exist";
605 argv[i++] = "--enable-status-msg";
606 if (opt.fixed_passphrase)
608 argv[i++] = "--passphrase";
609 argv[i++] = opt.fixed_passphrase;
611 if (opt.agent_program)
613 argv[i++] = "--agent-program";
614 argv[i++] = opt.agent_program;
616 argv[i++] = "--",
617 argv[i] = NULL;
618 assert (i < sizeof argv);
620 return gnupg_spawn_process (pgmname, argv, infile, outfile,
621 setup_pinentry_env, (128 | 64),
622 statusfile, pid);
626 /* Assume that the reader is at a pkcs#12 message and try to import
627 certificates from that stupid format. We will also store secret
628 keys. All of the pkcs#12 parsing and key storing is handled by the
629 gpg-protect-tool, we merely have to take care of receiving the
630 certificates. On success RETFP returns a temporary file with
631 certificates. */
632 static gpg_error_t
633 parse_p12 (ctrl_t ctrl, ksba_reader_t reader,
634 FILE **retfp, struct stats_s *stats)
636 const char *pgmname;
637 gpg_error_t err = 0, child_err = 0;
638 int c, cont_line;
639 unsigned int pos;
640 FILE *tmpfp, *certfp = NULL, *fp = NULL;
641 char buffer[1024];
642 size_t nread;
643 pid_t pid = -1;
644 int bad_pass = 0;
646 if (!opt.protect_tool_program || !*opt.protect_tool_program)
647 pgmname = gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL);
648 else
649 pgmname = opt.protect_tool_program;
651 *retfp = NULL;
653 /* To avoid an extra feeder process or doing selects and because
654 gpg-protect-tool will anyway parse the entire pkcs#12 message in
655 memory, we simply use tempfiles here and pass them to
656 the gpg-protect-tool. */
657 tmpfp = gnupg_tmpfile ();
658 if (!tmpfp)
660 err = gpg_error_from_syserror ();
661 log_error (_("error creating temporary file: %s\n"), strerror (errno));
662 goto cleanup;
664 while (!(err = ksba_reader_read (reader, buffer, sizeof buffer, &nread)))
666 if (nread && fwrite (buffer, nread, 1, tmpfp) != 1)
668 err = gpg_error_from_syserror ();
669 log_error (_("error writing to temporary file: %s\n"),
670 strerror (errno));
671 goto cleanup;
674 if (gpg_err_code (err) == GPG_ERR_EOF)
675 err = 0;
676 if (err)
678 log_error (_("error reading input: %s\n"), gpg_strerror (err));
679 goto cleanup;
682 certfp = gnupg_tmpfile ();
683 if (!certfp)
685 err = gpg_error_from_syserror ();
686 log_error (_("error creating temporary file: %s\n"), strerror (errno));
687 goto cleanup;
690 err = popen_protect_tool (ctrl, pgmname, tmpfp, certfp, &fp, &pid);
691 if (err)
693 pid = -1;
694 goto cleanup;
696 fclose (tmpfp);
697 tmpfp = NULL;
699 /* Read stderr of the protect tool. */
700 pos = 0;
701 cont_line = 0;
702 while ((c=getc (fp)) != EOF)
704 /* fixme: We could here grep for status information of the
705 protect tool to figure out better error codes for
706 CHILD_ERR. */
707 buffer[pos++] = c;
708 if (pos >= sizeof buffer - 5 || c == '\n')
710 buffer[pos - (c == '\n')] = 0;
711 if (cont_line)
712 log_printf ("%s", buffer);
713 else
715 if (!strncmp (buffer, "gpg-protect-tool: [PROTECT-TOOL:] ",34))
717 char *p, *pend;
719 p = buffer + 34;
720 pend = strchr (p, ' ');
721 if (pend)
722 *pend = 0;
723 if ( !strcmp (p, "secretkey-stored"))
725 stats->count++;
726 stats->secret_read++;
727 stats->secret_imported++;
729 else if ( !strcmp (p, "secretkey-exists"))
731 stats->count++;
732 stats->secret_read++;
733 stats->secret_dups++;
735 else if ( !strcmp (p, "bad-passphrase"))
740 else
742 log_info ("%s", buffer);
743 if (!strncmp (buffer, "gpg-protect-tool: "
744 "possibly bad passphrase given",46))
745 bad_pass++;
748 pos = 0;
749 cont_line = (c != '\n');
753 if (pos)
755 buffer[pos] = 0;
756 if (cont_line)
757 log_printf ("%s\n", buffer);
758 else
759 log_info ("%s\n", buffer);
763 /* If we found no error in the output of the child, setup a suitable
764 error code, which will later be reset if the exit status of the
765 child is 0. */
766 if (!child_err)
767 child_err = gpg_error (GPG_ERR_DECRYPT_FAILED);
769 cleanup:
770 if (tmpfp)
771 fclose (tmpfp);
772 if (fp)
773 fclose (fp);
774 if (pid != -1)
776 if (!gnupg_wait_process (pgmname, pid, NULL))
777 child_err = 0;
779 if (!err)
780 err = child_err;
781 if (err)
783 if (certfp)
784 fclose (certfp);
786 else
787 *retfp = certfp;
789 if (bad_pass)
791 /* We only write a plain error code and not direct
792 BAD_PASSPHRASE because the pkcs12 parser might issue this
793 message multiple times, BAD_PASSPHRASE in general requires a
794 keyID and parts of the import might actually succeed so that
795 IMPORT_PROBLEM is also not appropriate. */
796 gpgsm_status_with_err_code (ctrl, STATUS_ERROR,
797 "import.parsep12", GPG_ERR_BAD_PASSPHRASE);
800 return err;