2005-04-15 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / sm / import.c
blob6d00e91ea5cbf3396f075f48d523df2f419e3575
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 2 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, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <time.h>
27 #include <assert.h>
28 #include <unistd.h>
30 #include "gpgsm.h"
31 #include <gcrypt.h>
32 #include <ksba.h>
34 #include "keydb.h"
35 #include "exechelp.h"
36 #include "i18n.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 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 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 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 ctrl, struct stats_s *stats, ksba_cert_t cert, int depth)
151 int rc;
153 if (stats)
154 stats->count++;
155 if ( depth >= 50 )
157 log_error (_("certificate chain too long\n"));
158 if (stats)
159 stats->not_imported++;
160 print_import_problem (ctrl, cert, 3);
161 return;
164 /* Some basic checks, but don't care about missing certificates;
165 this is so that we are able to import entire certificate chains
166 w/o requiring a special order (i.e. root-CA first). This used
167 to be different but because gpgsm_verify even imports
168 certificates without any checks, it doesn't matter much and the
169 code gets much cleaner. A housekeeping function to remove
170 certificates w/o an anchor would be nice, though.
172 Optionally we do a full validation in addition to the basic test.
174 rc = gpgsm_basic_cert_check (cert);
175 if (!rc && ctrl->with_validation)
176 rc = gpgsm_validate_chain (ctrl, cert, NULL, 0, NULL, 0);
177 if (!rc || (!ctrl->with_validation
178 && gpg_err_code (rc) == GPG_ERR_MISSING_CERT) )
180 int existed;
182 if (!keydb_store_cert (cert, 0, &existed))
184 ksba_cert_t next = NULL;
186 if (!existed)
188 print_imported_status (ctrl, cert, 1);
189 if (stats)
190 stats->imported++;
192 else
194 print_imported_status (ctrl, cert, 0);
195 if (stats)
196 stats->unchanged++;
199 if (opt.verbose > 1 && existed)
201 if (depth)
202 log_info ("issuer certificate already in DB\n");
203 else
204 log_info ("certificate already in DB\n");
206 else if (opt.verbose && !existed)
208 if (depth)
209 log_info ("issuer certificate imported\n");
210 else
211 log_info ("certificate imported\n");
214 /* Now lets walk up the chain and import all certificates up
215 the chain. This is required in case we already stored
216 parent certificates in the ephemeral keybox. Do not
217 update the statistics, though. */
218 if (!gpgsm_walk_cert_chain (cert, &next))
220 check_and_store (ctrl, NULL, next, depth+1);
221 ksba_cert_release (next);
224 else
226 log_error (_("error storing certificate\n"));
227 if (stats)
228 stats->not_imported++;
229 print_import_problem (ctrl, cert, 4);
232 else
234 log_error (_("basic certificate checks failed - not imported\n"));
235 if (stats)
236 stats->not_imported++;
237 print_import_problem (ctrl, cert,
238 gpg_err_code (rc) == GPG_ERR_MISSING_CERT? 2 :
239 gpg_err_code (rc) == GPG_ERR_BAD_CERT? 1 : 0);
246 static int
247 import_one (CTRL ctrl, struct stats_s *stats, int in_fd)
249 int rc;
250 Base64Context b64reader = NULL;
251 ksba_reader_t reader;
252 ksba_cert_t cert = NULL;
253 ksba_cms_t cms = NULL;
254 FILE *fp = NULL;
255 ksba_content_type_t ct;
256 int any = 0;
258 fp = fdopen ( dup (in_fd), "rb");
259 if (!fp)
261 rc = gpg_error (gpg_err_code_from_errno (errno));
262 log_error ("fdopen() failed: %s\n", strerror (errno));
263 goto leave;
266 rc = gpgsm_create_reader (&b64reader, ctrl, fp, 1, &reader);
267 if (rc)
269 log_error ("can't create reader: %s\n", gpg_strerror (rc));
270 goto leave;
274 /* We need to loop here to handle multiple PEM objects in one
275 file. */
278 ksba_cms_release (cms); cms = NULL;
279 ksba_cert_release (cert); cert = NULL;
281 ct = ksba_cms_identify (reader);
282 if (ct == KSBA_CT_SIGNED_DATA)
283 { /* This is probably a signed-only message - import the certs */
284 ksba_stop_reason_t stopreason;
285 int i;
287 rc = ksba_cms_new (&cms);
288 if (rc)
289 goto leave;
291 rc = ksba_cms_set_reader_writer (cms, reader, NULL);
292 if (rc)
294 log_error ("ksba_cms_set_reader_writer failed: %s\n",
295 gpg_strerror (rc));
296 goto leave;
301 rc = ksba_cms_parse (cms, &stopreason);
302 if (rc)
304 log_error ("ksba_cms_parse failed: %s\n", gpg_strerror (rc));
305 goto leave;
308 if (stopreason == KSBA_SR_BEGIN_DATA)
309 log_info ("not a certs-only message\n");
311 while (stopreason != KSBA_SR_READY);
313 for (i=0; (cert=ksba_cms_get_cert (cms, i)); i++)
315 check_and_store (ctrl, stats, cert, 0);
316 ksba_cert_release (cert);
317 cert = NULL;
319 if (!i)
320 log_error ("no certificate found\n");
321 else
322 any = 1;
324 else if (ct == KSBA_CT_PKCS12)
325 { /* This seems to be a pkcs12 message. We use an external
326 tool to parse the message and to store the private keys.
327 We need to use a another reader here to parse the
328 certificate we included in the p12 file; then we continue
329 to look for other pkcs12 files (works only if they are in
330 PEM format. */
331 FILE *certfp;
332 Base64Context b64p12rdr;
333 ksba_reader_t p12rdr;
335 rc = parse_p12 (ctrl, reader, &certfp, stats);
336 if (!rc)
338 any = 1;
340 rewind (certfp);
341 rc = gpgsm_create_reader (&b64p12rdr, ctrl, certfp, 1, &p12rdr);
342 if (rc)
344 log_error ("can't create reader: %s\n", gpg_strerror (rc));
345 fclose (certfp);
346 goto leave;
351 ksba_cert_release (cert); cert = NULL;
352 rc = ksba_cert_new (&cert);
353 if (!rc)
355 rc = ksba_cert_read_der (cert, p12rdr);
356 if (!rc)
357 check_and_store (ctrl, stats, cert, 0);
359 ksba_reader_clear (p12rdr, NULL, NULL);
361 while (!rc && !gpgsm_reader_eof_seen (b64p12rdr));
363 if (gpg_err_code (rc) == GPG_ERR_EOF)
364 rc = 0;
365 gpgsm_destroy_reader (b64p12rdr);
366 fclose (certfp);
367 if (rc)
368 goto leave;
371 else if (ct == KSBA_CT_NONE)
372 { /* Failed to identify this message - assume a certificate */
374 rc = ksba_cert_new (&cert);
375 if (rc)
376 goto leave;
378 rc = ksba_cert_read_der (cert, reader);
379 if (rc)
380 goto leave;
382 check_and_store (ctrl, stats, cert, 0);
383 any = 1;
385 else
387 log_error ("can't extract certificates from input\n");
388 rc = gpg_error (GPG_ERR_NO_DATA);
391 ksba_reader_clear (reader, NULL, NULL);
393 while (!gpgsm_reader_eof_seen (b64reader));
395 leave:
396 if (any && gpg_err_code (rc) == GPG_ERR_EOF)
397 rc = 0;
398 ksba_cms_release (cms);
399 ksba_cert_release (cert);
400 gpgsm_destroy_reader (b64reader);
401 if (fp)
402 fclose (fp);
403 return rc;
408 gpgsm_import (CTRL ctrl, int in_fd)
410 int rc;
411 struct stats_s stats;
413 memset (&stats, 0, sizeof stats);
414 rc = import_one (ctrl, &stats, in_fd);
415 print_imported_summary (ctrl, &stats);
416 /* If we never printed an error message do it now so that a command
417 line invocation will return with an error (log_error keeps a
418 global errorcount) */
419 if (rc && !log_get_errorcount (0))
420 log_error (_("error importing certificate: %s\n"), gpg_strerror (rc));
421 return rc;
426 gpgsm_import_files (CTRL ctrl, int nfiles, char **files,
427 int (*of)(const char *fname))
429 int rc = 0;
430 struct stats_s stats;
432 memset (&stats, 0, sizeof stats);
434 if (!nfiles)
435 rc = import_one (ctrl, &stats, 0);
436 else
438 for (; nfiles && !rc ; nfiles--, files++)
440 int fd = of (*files);
441 rc = import_one (ctrl, &stats, fd);
442 close (fd);
443 if (rc == -1)
444 rc = 0;
447 print_imported_summary (ctrl, &stats);
448 /* If we never printed an error message do it now so that a command
449 line invocation will return with an error (log_error keeps a
450 global errorcount) */
451 if (rc && !log_get_errorcount (0))
452 log_error (_("error importing certificate: %s\n"), gpg_strerror (rc));
453 return rc;
457 /* Fork and exec the protecttool, connect the file descriptor of
458 INFILE to stdin, return a new stream in STATUSFILE, write the
459 output to OUTFILE and the pid of the process in PID. Returns 0 on
460 success or an error code. */
461 static gpg_error_t
462 popen_protect_tool (const char *pgmname,
463 FILE *infile, FILE *outfile, FILE **statusfile, pid_t *pid)
465 const char *argv[20];
466 int i=0;
468 argv[i++] = "--homedir";
469 argv[i++] = opt.homedir;
470 argv[i++] = "--p12-import";
471 argv[i++] = "--store";
472 argv[i++] = "--no-fail-on-exist";
473 argv[i++] = "--enable-status-msg";
474 if (opt.fixed_passphrase)
476 argv[i++] = "--passphrase";
477 argv[i++] = opt.fixed_passphrase;
479 argv[i++] = "--",
480 argv[i] = NULL;
481 assert (i < sizeof argv);
483 return gnupg_spawn_process (pgmname, argv, infile, outfile,
484 setup_pinentry_env,
485 statusfile, pid);
489 /* Assume that the reader is at a pkcs#12 message and try to import
490 certificates from that stupid format. We will also store secret
491 keys. All of the pkcs#12 parsing and key storing is handled by the
492 gpg-protect-tool, we merely have to take care of receiving the
493 certificates. On success RETFP returns a temporary file with
494 certificates. */
495 static gpg_error_t
496 parse_p12 (ctrl_t ctrl, ksba_reader_t reader,
497 FILE **retfp, struct stats_s *stats)
499 const char *pgmname;
500 gpg_error_t err = 0, child_err = 0;
501 int c, cont_line;
502 unsigned int pos;
503 FILE *tmpfp, *certfp = NULL, *fp = NULL;
504 char buffer[1024];
505 size_t nread;
506 pid_t pid = -1;
507 int bad_pass = 0;
509 if (!opt.protect_tool_program || !*opt.protect_tool_program)
510 pgmname = GNUPG_DEFAULT_PROTECT_TOOL;
511 else
512 pgmname = opt.protect_tool_program;
514 *retfp = NULL;
516 /* To avoid an extra feeder process or doing selects and because
517 gpg-protect-tool will anyway parse the entire pkcs#12 message in
518 memory, we simply use tempfiles here and pass them to
519 the gpg-protect-tool. */
520 tmpfp = tmpfile ();
521 if (!tmpfp)
523 err = gpg_error_from_errno (errno);
524 log_error (_("error creating temporary file: %s\n"), strerror (errno));
525 goto cleanup;
527 while (!(err = ksba_reader_read (reader, buffer, sizeof buffer, &nread)))
529 if (nread && fwrite (buffer, nread, 1, tmpfp) != 1)
531 err = gpg_error_from_errno (errno);
532 log_error (_("error writing to temporary file: %s\n"),
533 strerror (errno));
534 goto cleanup;
537 if (gpg_err_code (err) == GPG_ERR_EOF)
538 err = 0;
539 if (err)
541 log_error (_("error reading input: %s\n"), gpg_strerror (err));
542 goto cleanup;
545 certfp = tmpfile ();
546 if (!certfp)
548 err = gpg_error_from_errno (errno);
549 log_error (_("error creating temporary file: %s\n"), strerror (errno));
550 goto cleanup;
553 err = popen_protect_tool (pgmname, tmpfp, certfp, &fp, &pid);
554 if (err)
556 pid = -1;
557 goto cleanup;
559 fclose (tmpfp);
560 tmpfp = NULL;
562 /* Read stderr of the protect tool. */
563 pos = 0;
564 cont_line = 0;
565 while ((c=getc (fp)) != EOF)
567 /* fixme: We could here grep for status information of the
568 protect tool to figure out better error codes for
569 CHILD_ERR. */
570 buffer[pos++] = c;
571 if (pos >= sizeof buffer - 5 || c == '\n')
573 buffer[pos - (c == '\n')] = 0;
574 if (cont_line)
575 log_printf ("%s", buffer);
576 else
578 if (!strncmp (buffer, "gpg-protect-tool: [PROTECT-TOOL:] ",34))
580 char *p, *pend;
582 p = buffer + 34;
583 pend = strchr (p, ' ');
584 if (pend)
585 *pend = 0;
586 if ( !strcmp (p, "secretkey-stored"))
588 stats->count++;
589 stats->secret_read++;
590 stats->secret_imported++;
592 else if ( !strcmp (p, "secretkey-exists"))
594 stats->count++;
595 stats->secret_read++;
596 stats->secret_dups++;
598 else if ( !strcmp (p, "bad-passphrase"))
601 else
603 log_info ("%s", buffer);
604 if (!strncmp (buffer, "gpg-protect-tool: "
605 "possibly bad passphrase given",46))
606 bad_pass++;
609 pos = 0;
610 cont_line = (c != '\n');
614 if (pos)
616 buffer[pos] = 0;
617 if (cont_line)
618 log_printf ("%s\n", buffer);
619 else
620 log_info ("%s\n", buffer);
624 /* If we found no error in the output of the cild, setup a suitable
625 error code, which will later be reset if the exit status of the
626 child is 0. */
627 if (!child_err)
628 child_err = gpg_error (GPG_ERR_DECRYPT_FAILED);
630 cleanup:
631 if (tmpfp)
632 fclose (tmpfp);
633 if (fp)
634 fclose (fp);
635 if (pid != -1)
637 if (!gnupg_wait_process (pgmname, pid))
638 child_err = 0;
640 if (!err)
641 err = child_err;
642 if (err)
644 if (certfp)
645 fclose (certfp);
647 else
648 *retfp = certfp;
650 if (bad_pass)
652 /* We only write a plain error code and not direct
653 BAD_PASSPHRASE because the pkcs12 parser might issue this
654 message multiple times, BAd_PASSPHRASE in general requires a
655 keyID and parts of the import might actually succeed so that
656 IMPORT_PROBLEM is also not appropriate. */
657 gpgsm_status_with_err_code (ctrl, STATUS_ERROR,
658 "import.parsep12", GPG_ERR_BAD_PASSPHRASE);
661 return err;