1 /* import.c - Import certificates
2 * Copyright (C) 2001, 2003, 2004, 2009, 2010 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 <https://www.gnu.org/licenses/>.
37 #include "../kbx/keybox.h" /* for KEYBOX_FLAG_* */
38 #include "../common/membuf.h"
41 /* The arbitrary limit of one PKCS#12 object. */
42 #define MAX_P12OBJ_SIZE 128 /*kb*/
47 unsigned long imported;
48 unsigned long unchanged;
49 unsigned long not_imported;
50 unsigned long secret_read;
51 unsigned long secret_imported;
52 unsigned long secret_dups;
56 struct rsa_secret_key_s
58 gcry_mpi_t n; /* public modulus */
59 gcry_mpi_t e; /* public exponent */
60 gcry_mpi_t d; /* exponent */
61 gcry_mpi_t p; /* prime p. */
62 gcry_mpi_t q; /* prime q. */
63 gcry_mpi_t u; /* inverse of p mod q. */
67 static gpg_error_t parse_p12 (ctrl_t ctrl, ksba_reader_t reader,
68 struct stats_s *stats);
73 print_imported_status (ctrl_t ctrl, ksba_cert_t cert, int new_cert)
77 fpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1);
79 gpgsm_status2 (ctrl, STATUS_IMPORTED, fpr, "[X.509]", NULL);
81 gpgsm_status2 (ctrl, STATUS_IMPORT_OK,
82 new_cert? "1":"0", fpr, NULL);
88 /* Print an IMPORT_PROBLEM status. REASON is one of:
89 0 := "No specific reason given".
90 1 := "Invalid Certificate".
91 2 := "Issuer Certificate missing".
92 3 := "Certificate Chain too long".
93 4 := "Error storing certificate".
96 print_import_problem (ctrl_t ctrl, ksba_cert_t cert, int reason)
102 sprintf (buf, "%d", reason);
105 fpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1);
106 /* detetect an error (all high) value */
107 for (i=0; fpr[i] == 'F'; i++)
115 gpgsm_status2 (ctrl, STATUS_IMPORT_PROBLEM, buf, fpr, NULL);
121 print_imported_summary (ctrl_t ctrl, struct stats_s *stats)
127 log_info (_("total number processed: %lu\n"), stats->count);
130 log_info (_(" imported: %lu"), stats->imported );
133 if (stats->unchanged)
134 log_info (_(" unchanged: %lu\n"), stats->unchanged);
135 if (stats->secret_read)
136 log_info (_(" secret keys read: %lu\n"), stats->secret_read );
137 if (stats->secret_imported)
138 log_info (_(" secret keys imported: %lu\n"), stats->secret_imported );
139 if (stats->secret_dups)
140 log_info (_(" secret keys unchanged: %lu\n"), stats->secret_dups );
141 if (stats->not_imported)
142 log_info (_(" not imported: %lu\n"), stats->not_imported);
145 sprintf(buf, "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
147 0l /*stats->no_user_id*/,
149 0l /*stats->imported_rsa*/,
151 0l /*stats->n_uids*/,
152 0l /*stats->n_subk*/,
153 0l /*stats->n_sigs*/,
154 0l /*stats->n_revoc*/,
156 stats->secret_imported,
158 0l /*stats->skipped_new_keys*/,
161 gpgsm_status (ctrl, STATUS_IMPORT_RES, buf);
167 check_and_store (ctrl_t ctrl, struct stats_s *stats,
168 ksba_cert_t cert, int depth)
176 log_error (_("certificate chain too long\n"));
178 stats->not_imported++;
179 print_import_problem (ctrl, cert, 3);
183 /* Some basic checks, but don't care about missing certificates;
184 this is so that we are able to import entire certificate chains
185 w/o requiring a special order (i.e. root-CA first). This used
186 to be different but because gpgsm_verify even imports
187 certificates without any checks, it doesn't matter much and the
188 code gets much cleaner. A housekeeping function to remove
189 certificates w/o an anchor would be nice, though.
191 Optionally we do a full validation in addition to the basic test.
193 rc = gpgsm_basic_cert_check (ctrl, cert);
194 if (!rc && ctrl->with_validation)
195 rc = gpgsm_validate_chain (ctrl, cert, "", NULL, 0, NULL, 0, NULL);
196 if (!rc || (!ctrl->with_validation
197 && (gpg_err_code (rc) == GPG_ERR_MISSING_CERT
198 || gpg_err_code (rc) == GPG_ERR_MISSING_ISSUER_CERT)))
202 if (!keydb_store_cert (ctrl, cert, 0, &existed))
204 ksba_cert_t next = NULL;
208 print_imported_status (ctrl, cert, 1);
214 print_imported_status (ctrl, cert, 0);
219 if (opt.verbose > 1 && existed)
222 log_info ("issuer certificate already in DB\n");
224 log_info ("certificate already in DB\n");
226 else if (opt.verbose && !existed)
229 log_info ("issuer certificate imported\n");
231 log_info ("certificate imported\n");
234 /* Now lets walk up the chain and import all certificates up
235 the chain. This is required in case we already stored
236 parent certificates in the ephemeral keybox. Do not
237 update the statistics, though. */
238 if (!gpgsm_walk_cert_chain (ctrl, cert, &next))
240 check_and_store (ctrl, NULL, next, depth+1);
241 ksba_cert_release (next);
246 log_error (_("error storing certificate\n"));
248 stats->not_imported++;
249 print_import_problem (ctrl, cert, 4);
254 log_error (_("basic certificate checks failed - not imported\n"));
256 stats->not_imported++;
257 /* We keep the test for GPG_ERR_MISSING_CERT only in case
258 GPG_ERR_MISSING_CERT has been used instead of the newer
259 GPG_ERR_MISSING_ISSUER_CERT. */
262 gpg_err_code (rc) == GPG_ERR_MISSING_ISSUER_CERT? 2 :
263 gpg_err_code (rc) == GPG_ERR_MISSING_CERT? 2 :
264 gpg_err_code (rc) == GPG_ERR_BAD_CERT? 1 : 0);
272 import_one (ctrl_t ctrl, struct stats_s *stats, int in_fd)
275 Base64Context b64reader = NULL;
276 ksba_reader_t reader;
277 ksba_cert_t cert = NULL;
278 ksba_cms_t cms = NULL;
280 ksba_content_type_t ct;
283 fp = es_fdopen_nc (in_fd, "rb");
286 rc = gpg_error_from_syserror ();
287 log_error ("fdopen() failed: %s\n", strerror (errno));
291 rc = gpgsm_create_reader (&b64reader, ctrl, fp, 1, &reader);
294 log_error ("can't create reader: %s\n", gpg_strerror (rc));
299 /* We need to loop here to handle multiple PEM objects in one
303 ksba_cms_release (cms); cms = NULL;
304 ksba_cert_release (cert); cert = NULL;
306 ct = ksba_cms_identify (reader);
307 if (ct == KSBA_CT_SIGNED_DATA)
308 { /* This is probably a signed-only message - import the certs */
309 ksba_stop_reason_t stopreason;
312 rc = ksba_cms_new (&cms);
316 rc = ksba_cms_set_reader_writer (cms, reader, NULL);
319 log_error ("ksba_cms_set_reader_writer failed: %s\n",
326 rc = ksba_cms_parse (cms, &stopreason);
329 log_error ("ksba_cms_parse failed: %s\n", gpg_strerror (rc));
333 if (stopreason == KSBA_SR_BEGIN_DATA)
334 log_info ("not a certs-only message\n");
336 while (stopreason != KSBA_SR_READY);
338 for (i=0; (cert=ksba_cms_get_cert (cms, i)); i++)
340 check_and_store (ctrl, stats, cert, 0);
341 ksba_cert_release (cert);
345 log_error ("no certificate found\n");
349 else if (ct == KSBA_CT_PKCS12)
351 /* This seems to be a pkcs12 message. */
352 rc = parse_p12 (ctrl, reader, stats);
356 else if (ct == KSBA_CT_NONE)
357 { /* Failed to identify this message - assume a certificate */
359 rc = ksba_cert_new (&cert);
363 rc = ksba_cert_read_der (cert, reader);
367 check_and_store (ctrl, stats, cert, 0);
372 log_error ("can't extract certificates from input\n");
373 rc = gpg_error (GPG_ERR_NO_DATA);
376 ksba_reader_clear (reader, NULL, NULL);
378 while (!gpgsm_reader_eof_seen (b64reader));
381 if (any && gpg_err_code (rc) == GPG_ERR_EOF)
383 ksba_cms_release (cms);
384 ksba_cert_release (cert);
385 gpgsm_destroy_reader (b64reader);
392 /* Re-import certifciates. IN_FD is a list of linefeed delimited
393 fingerprints t re-import. The actual re-import is done by clearing
394 the ephemeral flag. */
396 reimport_one (ctrl_t ctrl, struct stats_s *stats, int in_fd)
400 char line[100]; /* Sufficient for a fingerprint. */
402 KEYDB_SEARCH_DESC desc;
403 ksba_cert_t cert = NULL;
409 err = gpg_error (GPG_ERR_ENOMEM);;
410 log_error (_("failed to allocate keyDB handle\n"));
413 keydb_set_ephemeral (kh, 1);
415 fp = es_fdopen_nc (in_fd, "r");
418 err = gpg_error_from_syserror ();
419 log_error ("es_fdopen(%d) failed: %s\n", in_fd, gpg_strerror (err));
423 while (es_fgets (line, DIM(line)-1, fp) )
425 if (*line && line[strlen(line)-1] != '\n')
427 err = gpg_error (GPG_ERR_LINE_TOO_LONG);
436 err = classify_user_id (line, &desc, 0);
439 print_import_problem (ctrl, NULL, 0);
440 stats->not_imported++;
444 keydb_search_reset (kh);
445 err = keydb_search (ctrl, kh, &desc, 1);
448 print_import_problem (ctrl, NULL, 0);
449 stats->not_imported++;
453 ksba_cert_release (cert);
455 err = keydb_get_cert (kh, &cert);
458 log_error ("keydb_get_cert() failed: %s\n", gpg_strerror (err));
459 print_import_problem (ctrl, NULL, 1);
460 stats->not_imported++;
464 err = keydb_get_flags (kh, KEYBOX_FLAG_BLOB, 0, &flags);
467 log_error (_("error getting stored flags: %s\n"), gpg_strerror (err));
468 print_imported_status (ctrl, cert, 0);
469 stats->not_imported++;
472 if ( !(flags & KEYBOX_FLAG_BLOB_EPHEMERAL) )
474 print_imported_status (ctrl, cert, 0);
479 err = keydb_set_cert_flags (ctrl, cert, 1, KEYBOX_FLAG_BLOB, 0,
480 KEYBOX_FLAG_BLOB_EPHEMERAL, 0);
483 log_error ("clearing ephemeral flag failed: %s\n",
485 print_import_problem (ctrl, cert, 0);
486 stats->not_imported++;
490 print_imported_status (ctrl, cert, 1);
496 err = gpg_error_from_syserror ();
497 log_error ("error reading fd %d: %s\n", in_fd, gpg_strerror (err));
502 ksba_cert_release (cert);
511 gpgsm_import (ctrl_t ctrl, int in_fd, int reimport_mode)
514 struct stats_s stats;
516 memset (&stats, 0, sizeof stats);
518 rc = reimport_one (ctrl, &stats, in_fd);
520 rc = import_one (ctrl, &stats, in_fd);
521 print_imported_summary (ctrl, &stats);
522 /* If we never printed an error message do it now so that a command
523 line invocation will return with an error (log_error keeps a
524 global errorcount) */
525 if (rc && !log_get_errorcount (0))
526 log_error (_("error importing certificate: %s\n"), gpg_strerror (rc));
532 gpgsm_import_files (ctrl_t ctrl, int nfiles, char **files,
533 int (*of)(const char *fname))
536 struct stats_s stats;
538 memset (&stats, 0, sizeof stats);
541 rc = import_one (ctrl, &stats, 0);
544 for (; nfiles && !rc ; nfiles--, files++)
546 int fd = of (*files);
547 rc = import_one (ctrl, &stats, fd);
553 print_imported_summary (ctrl, &stats);
554 /* If we never printed an error message do it now so that a command
555 line invocation will return with an error (log_error keeps a
556 global errorcount) */
557 if (rc && !log_get_errorcount (0))
558 log_error (_("error importing certificate: %s\n"), gpg_strerror (rc));
563 /* Check that the RSA secret key SKEY is valid. Swap parameters to
564 the libgcrypt standard. */
566 rsa_key_check (struct rsa_secret_key_s *skey)
569 gcry_mpi_t t = gcry_mpi_snew (0);
570 gcry_mpi_t t1 = gcry_mpi_snew (0);
571 gcry_mpi_t t2 = gcry_mpi_snew (0);
572 gcry_mpi_t phi = gcry_mpi_snew (0);
574 /* Check that n == p * q. */
575 gcry_mpi_mul (t, skey->p, skey->q);
576 if (gcry_mpi_cmp( t, skey->n) )
578 log_error ("RSA oops: n != p * q\n");
582 /* Check that p is less than q. */
583 if (gcry_mpi_cmp (skey->p, skey->q) > 0)
587 log_info ("swapping secret primes\n");
588 tmp = gcry_mpi_copy (skey->p);
589 gcry_mpi_set (skey->p, skey->q);
590 gcry_mpi_set (skey->q, tmp);
591 gcry_mpi_release (tmp);
593 gcry_mpi_invm (skey->u, skey->p, skey->q);
596 /* Check that e divides neither p-1 nor q-1. */
597 gcry_mpi_sub_ui (t, skey->p, 1 );
598 gcry_mpi_div (NULL, t, t, skey->e, 0);
599 if (!gcry_mpi_cmp_ui( t, 0) )
601 log_error ("RSA oops: e divides p-1\n");
604 gcry_mpi_sub_ui (t, skey->q, 1);
605 gcry_mpi_div (NULL, t, t, skey->e, 0);
606 if (!gcry_mpi_cmp_ui( t, 0))
608 log_info ("RSA oops: e divides q-1\n" );
612 /* Check that d is correct. */
613 gcry_mpi_sub_ui (t1, skey->p, 1);
614 gcry_mpi_sub_ui (t2, skey->q, 1);
615 gcry_mpi_mul (phi, t1, t2);
616 gcry_mpi_invm (t, skey->e, phi);
617 if (gcry_mpi_cmp (t, skey->d))
619 /* No: try universal exponent. */
620 gcry_mpi_gcd (t, t1, t2);
621 gcry_mpi_div (t, NULL, phi, t, 0);
622 gcry_mpi_invm (t, skey->e, t);
623 if (gcry_mpi_cmp (t, skey->d))
625 log_error ("RSA oops: bad secret exponent\n");
630 /* Check for correctness of u. */
631 gcry_mpi_invm (t, skey->p, skey->q);
632 if (gcry_mpi_cmp (t, skey->u))
634 log_info ("RSA oops: bad u parameter\n");
639 log_info ("RSA secret key check failed\n");
641 gcry_mpi_release (t);
642 gcry_mpi_release (t1);
643 gcry_mpi_release (t2);
644 gcry_mpi_release (phi);
646 return err? gpg_error (GPG_ERR_BAD_SECKEY):0;
650 /* Object passed to store_cert_cb. */
651 struct store_cert_parm_s
653 gpg_error_t err; /* First error seen. */
654 struct stats_s *stats; /* The stats object. */
655 ctrl_t ctrl; /* The control object. */
658 /* Helper to store the DER encoded certificate CERTDATA of length
661 store_cert_cb (void *opaque,
662 const unsigned char *certdata, size_t certdatalen)
664 struct store_cert_parm_s *parm = opaque;
668 err = ksba_cert_new (&cert);
676 err = ksba_cert_init_from_mem (cert, certdata, certdatalen);
679 log_error ("failed to parse a certificate: %s\n", gpg_strerror (err));
684 check_and_store (parm->ctrl, parm->stats, cert, 0);
685 ksba_cert_release (cert);
689 /* Assume that the reader is at a pkcs#12 message and try to import
690 certificates from that stupid format. We will transfer secret
691 keys to the agent. */
693 parse_p12 (ctrl_t ctrl, ksba_reader_t reader, struct stats_s *stats)
697 size_t ntotal, nread;
699 char *p12buffer = NULL;
702 gcry_mpi_t *kparms = NULL;
703 struct rsa_secret_key_s sk;
704 char *passphrase = NULL;
705 unsigned char *key = NULL;
709 unsigned char *wrappedkey = NULL;
710 size_t wrappedkeylen;
711 gcry_cipher_hd_t cipherhd = NULL;
712 gcry_sexp_t s_key = NULL;
713 unsigned char grip[20];
716 struct store_cert_parm_s store_cert_parm;
718 memset (&store_cert_parm, 0, sizeof store_cert_parm);
719 store_cert_parm.ctrl = ctrl;
720 store_cert_parm.stats = stats;
722 init_membuf (&p12mbuf, 4096);
724 while (!(err = ksba_reader_read (reader, buffer, sizeof buffer, &nread)))
726 if (ntotal >= MAX_P12OBJ_SIZE*1024)
728 /* Arbitrary limit to avoid DoS attacks. */
729 err = gpg_error (GPG_ERR_TOO_LARGE);
730 log_error ("pkcs#12 object is larger than %dk\n", MAX_P12OBJ_SIZE);
733 put_membuf (&p12mbuf, buffer, nread);
736 if (gpg_err_code (err) == GPG_ERR_EOF)
740 p12buffer = get_membuf (&p12mbuf, &p12buflen);
742 err = gpg_error_from_syserror ();
746 log_error (_("error reading input: %s\n"), gpg_strerror (err));
750 /* GnuPG 2.0.4 accidentally created binary P12 files with the string
751 "The passphrase is %s encoded.\n\n" prepended to the ASN.1 data.
753 if (p12buflen > 29 && !memcmp (p12buffer, "The passphrase is ", 18))
756 p12bufoff < p12buflen && p12buffer[p12bufoff] != '\n';
760 if (p12bufoff < p12buflen && p12buffer[p12bufoff] == '\n')
767 err = gpgsm_agent_ask_passphrase
769 i18n_utf8 ("Please enter the passphrase to unprotect the PKCS#12 object."),
774 kparms = p12_parse (p12buffer + p12bufoff, p12buflen - p12bufoff,
775 passphrase, store_cert_cb, &store_cert_parm, &bad_pass);
782 log_error ("error parsing or decrypting the PKCS#12 file\n");
783 err = gpg_error (GPG_ERR_INV_OBJ);
787 /* print_mpi (" n", kparms[0]); */
788 /* print_mpi (" e", kparms[1]); */
789 /* print_mpi (" d", kparms[2]); */
790 /* print_mpi (" p", kparms[3]); */
791 /* print_mpi (" q", kparms[4]); */
792 /* print_mpi ("dmp1", kparms[5]); */
793 /* print_mpi ("dmq1", kparms[6]); */
794 /* print_mpi (" u", kparms[7]); */
802 err = rsa_key_check (&sk);
805 /* print_mpi (" n", sk.n); */
806 /* print_mpi (" e", sk.e); */
807 /* print_mpi (" d", sk.d); */
808 /* print_mpi (" p", sk.p); */
809 /* print_mpi (" q", sk.q); */
810 /* print_mpi (" u", sk.u); */
812 /* Create an S-expresion from the parameters. */
813 err = gcry_sexp_build (&s_key, NULL,
814 "(private-key(rsa(n%m)(e%m)(d%m)(p%m)(q%m)(u%m)))",
815 sk.n, sk.e, sk.d, sk.p, sk.q, sk.u, NULL);
816 for (i=0; i < 8; i++)
817 gcry_mpi_release (kparms[i]);
822 log_error ("failed to create S-expression from key: %s\n",
827 /* Compute the keygrip. */
828 if (!gcry_pk_get_keygrip (s_key, grip))
830 err = gpg_error (GPG_ERR_GENERAL);
831 log_error ("can't calculate keygrip\n");
834 log_printhex ("keygrip=", grip, 20);
836 /* Convert to canonical encoding using a function which pads it to a
837 multiple of 64 bits. We need this padding for AESWRAP. */
838 err = make_canon_sexp_pad (s_key, 1, &key, &keylen);
841 log_error ("error creating canonical S-expression\n");
844 gcry_sexp_release (s_key);
847 /* Get the current KEK. */
848 err = gpgsm_agent_keywrap_key (ctrl, 0, &kek, &keklen);
851 log_error ("error getting the KEK: %s\n", gpg_strerror (err));
856 err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
857 GCRY_CIPHER_MODE_AESWRAP, 0);
860 err = gcry_cipher_setkey (cipherhd, kek, keklen);
866 wrappedkeylen = keylen + 8;
867 wrappedkey = xtrymalloc (wrappedkeylen);
870 err = gpg_error_from_syserror ();
874 err = gcry_cipher_encrypt (cipherhd, wrappedkey, wrappedkeylen, key, keylen);
879 gcry_cipher_close (cipherhd);
882 /* Send the wrapped key to the agent. */
883 err = gpgsm_agent_import_key (ctrl, wrappedkey, wrappedkeylen);
887 stats->secret_read++;
888 stats->secret_imported++;
890 else if ( gpg_err_code (err) == GPG_ERR_EEXIST )
894 stats->secret_read++;
895 stats->secret_dups++;
898 /* If we did not get an error from storing the secret key we return
899 a possible error from parsing the certificates. We do this after
900 storing the secret keys so that a bad certificate does not
901 inhibit our chance to store the secret key. */
902 if (!err && store_cert_parm.err)
903 err = store_cert_parm.err;
908 for (i=0; i < 8; i++)
909 gcry_mpi_release (kparms[i]);
914 gcry_sexp_release (s_key);
916 gcry_cipher_close (cipherhd);
919 xfree (get_membuf (&p12mbuf, NULL));
924 /* We only write a plain error code and not direct
925 BAD_PASSPHRASE because the pkcs12 parser might issue this
926 message multiple times, BAD_PASSPHRASE in general requires a
927 keyID and parts of the import might actually succeed so that
928 IMPORT_PROBLEM is also not appropriate. */
929 gpgsm_status_with_err_code (ctrl, STATUS_ERROR,
930 "import.parsep12", GPG_ERR_BAD_PASSPHRASE);