Reworked passing of envars to Pinentry.
[gnupg.git] / sm / import.c
blob5e8b429716685a7a0b847e9750120ca37d4d41b9
1 /* import.c - Import certificates
2 * Copyright (C) 2001, 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>
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"
38 struct stats_s {
39 unsigned long count;
40 unsigned long imported;
41 unsigned long unchanged;
42 unsigned long not_imported;
43 unsigned long secret_read;
44 unsigned long secret_imported;
45 unsigned long secret_dups;
49 static gpg_error_t parse_p12 (ctrl_t ctrl, ksba_reader_t reader, FILE **retfp,
50 struct stats_s *stats);
54 static void
55 print_imported_status (ctrl_t ctrl, ksba_cert_t cert, int new_cert)
57 char *fpr;
59 fpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1);
60 if (new_cert)
61 gpgsm_status2 (ctrl, STATUS_IMPORTED, fpr, "[X.509]", NULL);
63 gpgsm_status2 (ctrl, STATUS_IMPORT_OK,
64 new_cert? "1":"0", fpr, NULL);
66 xfree (fpr);
70 /* Print an IMPORT_PROBLEM status. REASON is one of:
71 0 := "No specific reason given".
72 1 := "Invalid Certificate".
73 2 := "Issuer Certificate missing".
74 3 := "Certificate Chain too long".
75 4 := "Error storing certificate".
77 static void
78 print_import_problem (ctrl_t ctrl, ksba_cert_t cert, int reason)
80 char *fpr = NULL;
81 char buf[25];
82 int i;
84 sprintf (buf, "%d", reason);
85 if (cert)
87 fpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1);
88 /* detetect an error (all high) value */
89 for (i=0; fpr[i] == 'F'; i++)
91 if (!fpr[i])
93 xfree (fpr);
94 fpr = NULL;
97 gpgsm_status2 (ctrl, STATUS_IMPORT_PROBLEM, buf, fpr, NULL);
98 xfree (fpr);
102 void
103 print_imported_summary (ctrl_t ctrl, struct stats_s *stats)
105 char buf[14*25];
107 if (!opt.quiet)
109 log_info (_("total number processed: %lu\n"), stats->count);
110 if (stats->imported)
112 log_info (_(" imported: %lu"), stats->imported );
113 log_printf ("\n");
115 if (stats->unchanged)
116 log_info (_(" unchanged: %lu\n"), stats->unchanged);
117 if (stats->secret_read)
118 log_info (_(" secret keys read: %lu\n"), stats->secret_read );
119 if (stats->secret_imported)
120 log_info (_(" secret keys imported: %lu\n"), stats->secret_imported );
121 if (stats->secret_dups)
122 log_info (_(" secret keys unchanged: %lu\n"), stats->secret_dups );
123 if (stats->not_imported)
124 log_info (_(" not imported: %lu\n"), stats->not_imported);
127 sprintf(buf, "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
128 stats->count,
129 0l /*stats->no_user_id*/,
130 stats->imported,
131 0l /*stats->imported_rsa*/,
132 stats->unchanged,
133 0l /*stats->n_uids*/,
134 0l /*stats->n_subk*/,
135 0l /*stats->n_sigs*/,
136 0l /*stats->n_revoc*/,
137 stats->secret_read,
138 stats->secret_imported,
139 stats->secret_dups,
140 0l /*stats->skipped_new_keys*/,
141 stats->not_imported
143 gpgsm_status (ctrl, STATUS_IMPORT_RES, buf);
148 static void
149 check_and_store (ctrl_t ctrl, struct stats_s *stats,
150 ksba_cert_t cert, int depth)
152 int rc;
154 if (stats)
155 stats->count++;
156 if ( depth >= 50 )
158 log_error (_("certificate chain too long\n"));
159 if (stats)
160 stats->not_imported++;
161 print_import_problem (ctrl, cert, 3);
162 return;
165 /* Some basic checks, but don't care about missing certificates;
166 this is so that we are able to import entire certificate chains
167 w/o requiring a special order (i.e. root-CA first). This used
168 to be different but because gpgsm_verify even imports
169 certificates without any checks, it doesn't matter much and the
170 code gets much cleaner. A housekeeping function to remove
171 certificates w/o an anchor would be nice, though.
173 Optionally we do a full validation in addition to the basic test.
175 rc = gpgsm_basic_cert_check (ctrl, cert);
176 if (!rc && ctrl->with_validation)
177 rc = gpgsm_validate_chain (ctrl, cert, "", NULL, 0, NULL, 0, NULL);
178 if (!rc || (!ctrl->with_validation
179 && gpg_err_code (rc) == GPG_ERR_MISSING_CERT) )
181 int existed;
183 if (!keydb_store_cert (cert, 0, &existed))
185 ksba_cert_t next = NULL;
187 if (!existed)
189 print_imported_status (ctrl, cert, 1);
190 if (stats)
191 stats->imported++;
193 else
195 print_imported_status (ctrl, cert, 0);
196 if (stats)
197 stats->unchanged++;
200 if (opt.verbose > 1 && existed)
202 if (depth)
203 log_info ("issuer certificate already in DB\n");
204 else
205 log_info ("certificate already in DB\n");
207 else if (opt.verbose && !existed)
209 if (depth)
210 log_info ("issuer certificate imported\n");
211 else
212 log_info ("certificate imported\n");
215 /* Now lets walk up the chain and import all certificates up
216 the chain. This is required in case we already stored
217 parent certificates in the ephemeral keybox. Do not
218 update the statistics, though. */
219 if (!gpgsm_walk_cert_chain (ctrl, cert, &next))
221 check_and_store (ctrl, NULL, next, depth+1);
222 ksba_cert_release (next);
225 else
227 log_error (_("error storing certificate\n"));
228 if (stats)
229 stats->not_imported++;
230 print_import_problem (ctrl, cert, 4);
233 else
235 log_error (_("basic certificate checks failed - not imported\n"));
236 if (stats)
237 stats->not_imported++;
238 print_import_problem (ctrl, cert,
239 gpg_err_code (rc) == GPG_ERR_MISSING_CERT? 2 :
240 gpg_err_code (rc) == GPG_ERR_BAD_CERT? 1 : 0);
247 static int
248 import_one (ctrl_t ctrl, struct stats_s *stats, int in_fd)
250 int rc;
251 Base64Context b64reader = NULL;
252 ksba_reader_t reader;
253 ksba_cert_t cert = NULL;
254 ksba_cms_t cms = NULL;
255 FILE *fp = NULL;
256 ksba_content_type_t ct;
257 int any = 0;
259 fp = fdopen ( dup (in_fd), "rb");
260 if (!fp)
262 rc = gpg_error (gpg_err_code_from_errno (errno));
263 log_error ("fdopen() failed: %s\n", strerror (errno));
264 goto leave;
267 rc = gpgsm_create_reader (&b64reader, ctrl, fp, 1, &reader);
268 if (rc)
270 log_error ("can't create reader: %s\n", gpg_strerror (rc));
271 goto leave;
275 /* We need to loop here to handle multiple PEM objects in one
276 file. */
279 ksba_cms_release (cms); cms = NULL;
280 ksba_cert_release (cert); cert = NULL;
282 ct = ksba_cms_identify (reader);
283 if (ct == KSBA_CT_SIGNED_DATA)
284 { /* This is probably a signed-only message - import the certs */
285 ksba_stop_reason_t stopreason;
286 int i;
288 rc = ksba_cms_new (&cms);
289 if (rc)
290 goto leave;
292 rc = ksba_cms_set_reader_writer (cms, reader, NULL);
293 if (rc)
295 log_error ("ksba_cms_set_reader_writer failed: %s\n",
296 gpg_strerror (rc));
297 goto leave;
302 rc = ksba_cms_parse (cms, &stopreason);
303 if (rc)
305 log_error ("ksba_cms_parse failed: %s\n", gpg_strerror (rc));
306 goto leave;
309 if (stopreason == KSBA_SR_BEGIN_DATA)
310 log_info ("not a certs-only message\n");
312 while (stopreason != KSBA_SR_READY);
314 for (i=0; (cert=ksba_cms_get_cert (cms, i)); i++)
316 check_and_store (ctrl, stats, cert, 0);
317 ksba_cert_release (cert);
318 cert = NULL;
320 if (!i)
321 log_error ("no certificate found\n");
322 else
323 any = 1;
325 else if (ct == KSBA_CT_PKCS12)
326 { /* This seems to be a pkcs12 message. We use an external
327 tool to parse the message and to store the private keys.
328 We need to use a another reader here to parse the
329 certificate we included in the p12 file; then we continue
330 to look for other pkcs12 files (works only if they are in
331 PEM format. */
332 FILE *certfp;
333 Base64Context b64p12rdr;
334 ksba_reader_t p12rdr;
336 rc = parse_p12 (ctrl, reader, &certfp, stats);
337 if (!rc)
339 any = 1;
341 rewind (certfp);
342 rc = gpgsm_create_reader (&b64p12rdr, ctrl, certfp, 1, &p12rdr);
343 if (rc)
345 log_error ("can't create reader: %s\n", gpg_strerror (rc));
346 fclose (certfp);
347 goto leave;
352 ksba_cert_release (cert); cert = NULL;
353 rc = ksba_cert_new (&cert);
354 if (!rc)
356 rc = ksba_cert_read_der (cert, p12rdr);
357 if (!rc)
358 check_and_store (ctrl, stats, cert, 0);
360 ksba_reader_clear (p12rdr, NULL, NULL);
362 while (!rc && !gpgsm_reader_eof_seen (b64p12rdr));
364 if (gpg_err_code (rc) == GPG_ERR_EOF)
365 rc = 0;
366 gpgsm_destroy_reader (b64p12rdr);
367 fclose (certfp);
368 if (rc)
369 goto leave;
372 else if (ct == KSBA_CT_NONE)
373 { /* Failed to identify this message - assume a certificate */
375 rc = ksba_cert_new (&cert);
376 if (rc)
377 goto leave;
379 rc = ksba_cert_read_der (cert, reader);
380 if (rc)
381 goto leave;
383 check_and_store (ctrl, stats, cert, 0);
384 any = 1;
386 else
388 log_error ("can't extract certificates from input\n");
389 rc = gpg_error (GPG_ERR_NO_DATA);
392 ksba_reader_clear (reader, NULL, NULL);
394 while (!gpgsm_reader_eof_seen (b64reader));
396 leave:
397 if (any && gpg_err_code (rc) == GPG_ERR_EOF)
398 rc = 0;
399 ksba_cms_release (cms);
400 ksba_cert_release (cert);
401 gpgsm_destroy_reader (b64reader);
402 if (fp)
403 fclose (fp);
404 return rc;
409 gpgsm_import (ctrl_t ctrl, int in_fd)
411 int rc;
412 struct stats_s stats;
414 memset (&stats, 0, sizeof stats);
415 rc = import_one (ctrl, &stats, in_fd);
416 print_imported_summary (ctrl, &stats);
417 /* If we never printed an error message do it now so that a command
418 line invocation will return with an error (log_error keeps a
419 global errorcount) */
420 if (rc && !log_get_errorcount (0))
421 log_error (_("error importing certificate: %s\n"), gpg_strerror (rc));
422 return rc;
427 gpgsm_import_files (ctrl_t ctrl, int nfiles, char **files,
428 int (*of)(const char *fname))
430 int rc = 0;
431 struct stats_s stats;
433 memset (&stats, 0, sizeof stats);
435 if (!nfiles)
436 rc = import_one (ctrl, &stats, 0);
437 else
439 for (; nfiles && !rc ; nfiles--, files++)
441 int fd = of (*files);
442 rc = import_one (ctrl, &stats, fd);
443 close (fd);
444 if (rc == -1)
445 rc = 0;
448 print_imported_summary (ctrl, &stats);
449 /* If we never printed an error message do it now so that a command
450 line invocation will return with an error (log_error keeps a
451 global errorcount) */
452 if (rc && !log_get_errorcount (0))
453 log_error (_("error importing certificate: %s\n"), gpg_strerror (rc));
454 return rc;
458 /* Fork and exec the protecttool, connect the file descriptor of
459 INFILE to stdin, return a new stream in STATUSFILE, write the
460 output to OUTFILE and the pid of the process in PID. Returns 0 on
461 success or an error code. */
462 static gpg_error_t
463 popen_protect_tool (ctrl_t ctrl, const char *pgmname,
464 FILE *infile, FILE *outfile, FILE **statusfile, pid_t *pid)
466 const char *argv[22];
467 int i=0;
469 /* Make sure that the agent is running so that the protect tool is
470 able to ask for a passphrase. This has only an effect under W32
471 where the agent is started on demand; sending a NOP does not harm
472 on other platforms. This is not really necessary anymore because
473 the protect tool does this now by itself; it does not harm either. */
474 gpgsm_agent_send_nop (ctrl);
476 argv[i++] = "--homedir";
477 argv[i++] = opt.homedir;
478 argv[i++] = "--p12-import";
479 argv[i++] = "--store";
480 argv[i++] = "--no-fail-on-exist";
481 argv[i++] = "--enable-status-msg";
482 if (opt.fixed_passphrase)
484 argv[i++] = "--passphrase";
485 argv[i++] = opt.fixed_passphrase;
487 if (opt.agent_program)
489 argv[i++] = "--agent-program";
490 argv[i++] = opt.agent_program;
492 argv[i++] = "--",
493 argv[i] = NULL;
494 assert (i < sizeof argv);
496 return gnupg_spawn_process (pgmname, argv, infile, outfile,
497 setup_pinentry_env, (128 | 64),
498 statusfile, pid);
502 /* Assume that the reader is at a pkcs#12 message and try to import
503 certificates from that stupid format. We will also store secret
504 keys. All of the pkcs#12 parsing and key storing is handled by the
505 gpg-protect-tool, we merely have to take care of receiving the
506 certificates. On success RETFP returns a temporary file with
507 certificates. */
508 static gpg_error_t
509 parse_p12 (ctrl_t ctrl, ksba_reader_t reader,
510 FILE **retfp, struct stats_s *stats)
512 const char *pgmname;
513 gpg_error_t err = 0, child_err = 0;
514 int c, cont_line;
515 unsigned int pos;
516 FILE *tmpfp, *certfp = NULL, *fp = NULL;
517 char buffer[1024];
518 size_t nread;
519 pid_t pid = -1;
520 int bad_pass = 0;
522 if (!opt.protect_tool_program || !*opt.protect_tool_program)
523 pgmname = gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL);
524 else
525 pgmname = opt.protect_tool_program;
527 *retfp = NULL;
529 /* To avoid an extra feeder process or doing selects and because
530 gpg-protect-tool will anyway parse the entire pkcs#12 message in
531 memory, we simply use tempfiles here and pass them to
532 the gpg-protect-tool. */
533 tmpfp = gnupg_tmpfile ();
534 if (!tmpfp)
536 err = gpg_error_from_syserror ();
537 log_error (_("error creating temporary file: %s\n"), strerror (errno));
538 goto cleanup;
540 while (!(err = ksba_reader_read (reader, buffer, sizeof buffer, &nread)))
542 if (nread && fwrite (buffer, nread, 1, tmpfp) != 1)
544 err = gpg_error_from_syserror ();
545 log_error (_("error writing to temporary file: %s\n"),
546 strerror (errno));
547 goto cleanup;
550 if (gpg_err_code (err) == GPG_ERR_EOF)
551 err = 0;
552 if (err)
554 log_error (_("error reading input: %s\n"), gpg_strerror (err));
555 goto cleanup;
558 certfp = gnupg_tmpfile ();
559 if (!certfp)
561 err = gpg_error_from_syserror ();
562 log_error (_("error creating temporary file: %s\n"), strerror (errno));
563 goto cleanup;
566 err = popen_protect_tool (ctrl, pgmname, tmpfp, certfp, &fp, &pid);
567 if (err)
569 pid = -1;
570 goto cleanup;
572 fclose (tmpfp);
573 tmpfp = NULL;
575 /* Read stderr of the protect tool. */
576 pos = 0;
577 cont_line = 0;
578 while ((c=getc (fp)) != EOF)
580 /* fixme: We could here grep for status information of the
581 protect tool to figure out better error codes for
582 CHILD_ERR. */
583 buffer[pos++] = c;
584 if (pos >= sizeof buffer - 5 || c == '\n')
586 buffer[pos - (c == '\n')] = 0;
587 if (cont_line)
588 log_printf ("%s", buffer);
589 else
591 if (!strncmp (buffer, "gpg-protect-tool: [PROTECT-TOOL:] ",34))
593 char *p, *pend;
595 p = buffer + 34;
596 pend = strchr (p, ' ');
597 if (pend)
598 *pend = 0;
599 if ( !strcmp (p, "secretkey-stored"))
601 stats->count++;
602 stats->secret_read++;
603 stats->secret_imported++;
605 else if ( !strcmp (p, "secretkey-exists"))
607 stats->count++;
608 stats->secret_read++;
609 stats->secret_dups++;
611 else if ( !strcmp (p, "bad-passphrase"))
616 else
618 log_info ("%s", buffer);
619 if (!strncmp (buffer, "gpg-protect-tool: "
620 "possibly bad passphrase given",46))
621 bad_pass++;
624 pos = 0;
625 cont_line = (c != '\n');
629 if (pos)
631 buffer[pos] = 0;
632 if (cont_line)
633 log_printf ("%s\n", buffer);
634 else
635 log_info ("%s\n", buffer);
639 /* If we found no error in the output of the child, setup a suitable
640 error code, which will later be reset if the exit status of the
641 child is 0. */
642 if (!child_err)
643 child_err = gpg_error (GPG_ERR_DECRYPT_FAILED);
645 cleanup:
646 if (tmpfp)
647 fclose (tmpfp);
648 if (fp)
649 fclose (fp);
650 if (pid != -1)
652 if (!gnupg_wait_process (pgmname, pid, NULL))
653 child_err = 0;
655 if (!err)
656 err = child_err;
657 if (err)
659 if (certfp)
660 fclose (certfp);
662 else
663 *retfp = certfp;
665 if (bad_pass)
667 /* We only write a plain error code and not direct
668 BAD_PASSPHRASE because the pkcs12 parser might issue this
669 message multiple times, BAD_PASSPHRASE in general requires a
670 keyID and parts of the import might actually succeed so that
671 IMPORT_PROBLEM is also not appropriate. */
672 gpgsm_status_with_err_code (ctrl, STATUS_ERROR,
673 "import.parsep12", GPG_ERR_BAD_PASSPHRASE);
676 return err;