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/>.
34 #include "../common/exechelp.h"
35 #include "../common/i18n.h"
36 #include "../common/sysutils.h"
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 gnupg_ksba_io_t 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 = gnupg_ksba_create_reader
292 (&b64reader, ((ctrl->is_pem? GNUPG_KSBA_IO_PEM : 0)
293 | (ctrl->is_base64? GNUPG_KSBA_IO_BASE64 : 0)
294 | (ctrl->autodetect_encoding? GNUPG_KSBA_IO_AUTODETECT : 0)
295 | GNUPG_KSBA_IO_MULTIPEM),
299 log_error ("can't create reader: %s\n", gpg_strerror (rc));
304 /* We need to loop here to handle multiple PEM objects in one
308 ksba_cms_release (cms); cms = NULL;
309 ksba_cert_release (cert); cert = NULL;
311 ct = ksba_cms_identify (reader);
312 if (ct == KSBA_CT_SIGNED_DATA)
313 { /* This is probably a signed-only message - import the certs */
314 ksba_stop_reason_t stopreason;
317 rc = ksba_cms_new (&cms);
321 rc = ksba_cms_set_reader_writer (cms, reader, NULL);
324 log_error ("ksba_cms_set_reader_writer failed: %s\n",
331 rc = ksba_cms_parse (cms, &stopreason);
334 log_error ("ksba_cms_parse failed: %s\n", gpg_strerror (rc));
338 if (stopreason == KSBA_SR_BEGIN_DATA)
339 log_info ("not a certs-only message\n");
341 while (stopreason != KSBA_SR_READY);
343 for (i=0; (cert=ksba_cms_get_cert (cms, i)); i++)
345 check_and_store (ctrl, stats, cert, 0);
346 ksba_cert_release (cert);
350 log_error ("no certificate found\n");
354 else if (ct == KSBA_CT_PKCS12)
356 /* This seems to be a pkcs12 message. */
357 rc = parse_p12 (ctrl, reader, stats);
361 else if (ct == KSBA_CT_NONE)
362 { /* Failed to identify this message - assume a certificate */
364 rc = ksba_cert_new (&cert);
368 rc = ksba_cert_read_der (cert, reader);
372 check_and_store (ctrl, stats, cert, 0);
377 log_error ("can't extract certificates from input\n");
378 rc = gpg_error (GPG_ERR_NO_DATA);
381 ksba_reader_clear (reader, NULL, NULL);
383 while (!gnupg_ksba_reader_eof_seen (b64reader));
386 if (any && gpg_err_code (rc) == GPG_ERR_EOF)
388 ksba_cms_release (cms);
389 ksba_cert_release (cert);
390 gnupg_ksba_destroy_reader (b64reader);
397 /* Re-import certifciates. IN_FD is a list of linefeed delimited
398 fingerprints t re-import. The actual re-import is done by clearing
399 the ephemeral flag. */
401 reimport_one (ctrl_t ctrl, struct stats_s *stats, int in_fd)
405 char line[100]; /* Sufficient for a fingerprint. */
407 KEYDB_SEARCH_DESC desc;
408 ksba_cert_t cert = NULL;
414 err = gpg_error (GPG_ERR_ENOMEM);;
415 log_error (_("failed to allocate keyDB handle\n"));
418 keydb_set_ephemeral (kh, 1);
420 fp = es_fdopen_nc (in_fd, "r");
423 err = gpg_error_from_syserror ();
424 log_error ("es_fdopen(%d) failed: %s\n", in_fd, gpg_strerror (err));
428 while (es_fgets (line, DIM(line)-1, fp) )
430 if (*line && line[strlen(line)-1] != '\n')
432 err = gpg_error (GPG_ERR_LINE_TOO_LONG);
441 err = classify_user_id (line, &desc, 0);
444 print_import_problem (ctrl, NULL, 0);
445 stats->not_imported++;
449 keydb_search_reset (kh);
450 err = keydb_search (ctrl, kh, &desc, 1);
453 print_import_problem (ctrl, NULL, 0);
454 stats->not_imported++;
458 ksba_cert_release (cert);
460 err = keydb_get_cert (kh, &cert);
463 log_error ("keydb_get_cert() failed: %s\n", gpg_strerror (err));
464 print_import_problem (ctrl, NULL, 1);
465 stats->not_imported++;
469 err = keydb_get_flags (kh, KEYBOX_FLAG_BLOB, 0, &flags);
472 log_error (_("error getting stored flags: %s\n"), gpg_strerror (err));
473 print_imported_status (ctrl, cert, 0);
474 stats->not_imported++;
477 if ( !(flags & KEYBOX_FLAG_BLOB_EPHEMERAL) )
479 print_imported_status (ctrl, cert, 0);
484 err = keydb_set_cert_flags (ctrl, cert, 1, KEYBOX_FLAG_BLOB, 0,
485 KEYBOX_FLAG_BLOB_EPHEMERAL, 0);
488 log_error ("clearing ephemeral flag failed: %s\n",
490 print_import_problem (ctrl, cert, 0);
491 stats->not_imported++;
495 print_imported_status (ctrl, cert, 1);
501 err = gpg_error_from_syserror ();
502 log_error ("error reading fd %d: %s\n", in_fd, gpg_strerror (err));
507 ksba_cert_release (cert);
516 gpgsm_import (ctrl_t ctrl, int in_fd, int reimport_mode)
519 struct stats_s stats;
521 memset (&stats, 0, sizeof stats);
523 rc = reimport_one (ctrl, &stats, in_fd);
525 rc = import_one (ctrl, &stats, in_fd);
526 print_imported_summary (ctrl, &stats);
527 /* If we never printed an error message do it now so that a command
528 line invocation will return with an error (log_error keeps a
529 global errorcount) */
530 if (rc && !log_get_errorcount (0))
531 log_error (_("error importing certificate: %s\n"), gpg_strerror (rc));
537 gpgsm_import_files (ctrl_t ctrl, int nfiles, char **files,
538 int (*of)(const char *fname))
541 struct stats_s stats;
543 memset (&stats, 0, sizeof stats);
546 rc = import_one (ctrl, &stats, 0);
549 for (; nfiles && !rc ; nfiles--, files++)
551 int fd = of (*files);
552 rc = import_one (ctrl, &stats, fd);
558 print_imported_summary (ctrl, &stats);
559 /* If we never printed an error message do it now so that a command
560 line invocation will return with an error (log_error keeps a
561 global errorcount) */
562 if (rc && !log_get_errorcount (0))
563 log_error (_("error importing certificate: %s\n"), gpg_strerror (rc));
568 /* Check that the RSA secret key SKEY is valid. Swap parameters to
569 the libgcrypt standard. */
571 rsa_key_check (struct rsa_secret_key_s *skey)
574 gcry_mpi_t t = gcry_mpi_snew (0);
575 gcry_mpi_t t1 = gcry_mpi_snew (0);
576 gcry_mpi_t t2 = gcry_mpi_snew (0);
577 gcry_mpi_t phi = gcry_mpi_snew (0);
579 /* Check that n == p * q. */
580 gcry_mpi_mul (t, skey->p, skey->q);
581 if (gcry_mpi_cmp( t, skey->n) )
583 log_error ("RSA oops: n != p * q\n");
587 /* Check that p is less than q. */
588 if (gcry_mpi_cmp (skey->p, skey->q) > 0)
592 log_info ("swapping secret primes\n");
593 tmp = gcry_mpi_copy (skey->p);
594 gcry_mpi_set (skey->p, skey->q);
595 gcry_mpi_set (skey->q, tmp);
596 gcry_mpi_release (tmp);
598 gcry_mpi_invm (skey->u, skey->p, skey->q);
601 /* Check that e divides neither p-1 nor q-1. */
602 gcry_mpi_sub_ui (t, skey->p, 1 );
603 gcry_mpi_div (NULL, t, t, skey->e, 0);
604 if (!gcry_mpi_cmp_ui( t, 0) )
606 log_error ("RSA oops: e divides p-1\n");
609 gcry_mpi_sub_ui (t, skey->q, 1);
610 gcry_mpi_div (NULL, t, t, skey->e, 0);
611 if (!gcry_mpi_cmp_ui( t, 0))
613 log_info ("RSA oops: e divides q-1\n" );
617 /* Check that d is correct. */
618 gcry_mpi_sub_ui (t1, skey->p, 1);
619 gcry_mpi_sub_ui (t2, skey->q, 1);
620 gcry_mpi_mul (phi, t1, t2);
621 gcry_mpi_invm (t, skey->e, phi);
622 if (gcry_mpi_cmp (t, skey->d))
624 /* No: try universal exponent. */
625 gcry_mpi_gcd (t, t1, t2);
626 gcry_mpi_div (t, NULL, phi, t, 0);
627 gcry_mpi_invm (t, skey->e, t);
628 if (gcry_mpi_cmp (t, skey->d))
630 log_error ("RSA oops: bad secret exponent\n");
635 /* Check for correctness of u. */
636 gcry_mpi_invm (t, skey->p, skey->q);
637 if (gcry_mpi_cmp (t, skey->u))
639 log_info ("RSA oops: bad u parameter\n");
644 log_info ("RSA secret key check failed\n");
646 gcry_mpi_release (t);
647 gcry_mpi_release (t1);
648 gcry_mpi_release (t2);
649 gcry_mpi_release (phi);
651 return err? gpg_error (GPG_ERR_BAD_SECKEY):0;
655 /* Object passed to store_cert_cb. */
656 struct store_cert_parm_s
658 gpg_error_t err; /* First error seen. */
659 struct stats_s *stats; /* The stats object. */
660 ctrl_t ctrl; /* The control object. */
663 /* Helper to store the DER encoded certificate CERTDATA of length
666 store_cert_cb (void *opaque,
667 const unsigned char *certdata, size_t certdatalen)
669 struct store_cert_parm_s *parm = opaque;
673 err = ksba_cert_new (&cert);
681 err = ksba_cert_init_from_mem (cert, certdata, certdatalen);
684 log_error ("failed to parse a certificate: %s\n", gpg_strerror (err));
689 check_and_store (parm->ctrl, parm->stats, cert, 0);
690 ksba_cert_release (cert);
694 /* Assume that the reader is at a pkcs#12 message and try to import
695 certificates from that stupid format. We will transfer secret
696 keys to the agent. */
698 parse_p12 (ctrl_t ctrl, ksba_reader_t reader, struct stats_s *stats)
702 size_t ntotal, nread;
704 char *p12buffer = NULL;
707 gcry_mpi_t *kparms = NULL;
708 struct rsa_secret_key_s sk;
709 char *passphrase = NULL;
710 unsigned char *key = NULL;
714 unsigned char *wrappedkey = NULL;
715 size_t wrappedkeylen;
716 gcry_cipher_hd_t cipherhd = NULL;
717 gcry_sexp_t s_key = NULL;
718 unsigned char grip[20];
721 struct store_cert_parm_s store_cert_parm;
723 memset (&store_cert_parm, 0, sizeof store_cert_parm);
724 store_cert_parm.ctrl = ctrl;
725 store_cert_parm.stats = stats;
727 init_membuf (&p12mbuf, 4096);
729 while (!(err = ksba_reader_read (reader, buffer, sizeof buffer, &nread)))
731 if (ntotal >= MAX_P12OBJ_SIZE*1024)
733 /* Arbitrary limit to avoid DoS attacks. */
734 err = gpg_error (GPG_ERR_TOO_LARGE);
735 log_error ("pkcs#12 object is larger than %dk\n", MAX_P12OBJ_SIZE);
738 put_membuf (&p12mbuf, buffer, nread);
741 if (gpg_err_code (err) == GPG_ERR_EOF)
745 p12buffer = get_membuf (&p12mbuf, &p12buflen);
747 err = gpg_error_from_syserror ();
751 log_error (_("error reading input: %s\n"), gpg_strerror (err));
755 /* GnuPG 2.0.4 accidentally created binary P12 files with the string
756 "The passphrase is %s encoded.\n\n" prepended to the ASN.1 data.
758 if (p12buflen > 29 && !memcmp (p12buffer, "The passphrase is ", 18))
761 p12bufoff < p12buflen && p12buffer[p12bufoff] != '\n';
765 if (p12bufoff < p12buflen && p12buffer[p12bufoff] == '\n')
772 err = gpgsm_agent_ask_passphrase
774 i18n_utf8 (N_("Please enter the passphrase to unprotect the PKCS#12 object.")),
779 kparms = p12_parse (p12buffer + p12bufoff, p12buflen - p12bufoff,
780 passphrase, store_cert_cb, &store_cert_parm,
788 log_error ("error parsing or decrypting the PKCS#12 file\n");
789 err = gpg_error (GPG_ERR_INV_OBJ);
793 /* print_mpi (" n", kparms[0]); */
794 /* print_mpi (" e", kparms[1]); */
795 /* print_mpi (" d", kparms[2]); */
796 /* print_mpi (" p", kparms[3]); */
797 /* print_mpi (" q", kparms[4]); */
798 /* print_mpi ("dmp1", kparms[5]); */
799 /* print_mpi ("dmq1", kparms[6]); */
800 /* print_mpi (" u", kparms[7]); */
808 err = rsa_key_check (&sk);
811 /* print_mpi (" n", sk.n); */
812 /* print_mpi (" e", sk.e); */
813 /* print_mpi (" d", sk.d); */
814 /* print_mpi (" p", sk.p); */
815 /* print_mpi (" q", sk.q); */
816 /* print_mpi (" u", sk.u); */
818 /* Create an S-expression from the parameters. */
819 err = gcry_sexp_build (&s_key, NULL,
820 "(private-key(rsa(n%m)(e%m)(d%m)(p%m)(q%m)(u%m)))",
821 sk.n, sk.e, sk.d, sk.p, sk.q, sk.u, NULL);
822 for (i=0; i < 8; i++)
823 gcry_mpi_release (kparms[i]);
828 log_error ("failed to create S-expression from key: %s\n",
833 /* Compute the keygrip. */
834 if (!gcry_pk_get_keygrip (s_key, grip))
836 err = gpg_error (GPG_ERR_GENERAL);
837 log_error ("can't calculate keygrip\n");
841 log_printhex (grip, 20, "keygrip=");
843 /* Convert to canonical encoding using a function which pads it to a
844 multiple of 64 bits. We need this padding for AESWRAP. */
845 err = make_canon_sexp_pad (s_key, 1, &key, &keylen);
848 log_error ("error creating canonical S-expression\n");
851 gcry_sexp_release (s_key);
854 /* Get the current KEK. */
855 err = gpgsm_agent_keywrap_key (ctrl, 0, &kek, &keklen);
858 log_error ("error getting the KEK: %s\n", gpg_strerror (err));
863 err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
864 GCRY_CIPHER_MODE_AESWRAP, 0);
867 err = gcry_cipher_setkey (cipherhd, kek, keklen);
873 wrappedkeylen = keylen + 8;
874 wrappedkey = xtrymalloc (wrappedkeylen);
877 err = gpg_error_from_syserror ();
881 err = gcry_cipher_encrypt (cipherhd, wrappedkey, wrappedkeylen, key, keylen);
886 gcry_cipher_close (cipherhd);
889 /* Send the wrapped key to the agent. */
890 err = gpgsm_agent_import_key (ctrl, wrappedkey, wrappedkeylen);
894 stats->secret_read++;
895 stats->secret_imported++;
897 else if ( gpg_err_code (err) == GPG_ERR_EEXIST )
901 stats->secret_read++;
902 stats->secret_dups++;
905 /* If we did not get an error from storing the secret key we return
906 a possible error from parsing the certificates. We do this after
907 storing the secret keys so that a bad certificate does not
908 inhibit our chance to store the secret key. */
909 if (!err && store_cert_parm.err)
910 err = store_cert_parm.err;
915 for (i=0; i < 8; i++)
916 gcry_mpi_release (kparms[i]);
921 gcry_sexp_release (s_key);
923 gcry_cipher_close (cipherhd);
926 xfree (get_membuf (&p12mbuf, NULL));
931 /* We only write a plain error code and not direct
932 BAD_PASSPHRASE because the pkcs12 parser might issue this
933 message multiple times, BAD_PASSPHRASE in general requires a
934 keyID and parts of the import might actually succeed so that
935 IMPORT_PROBLEM is also not appropriate. */
936 gpgsm_status_with_err_code (ctrl, STATUS_ERROR,
937 "import.parsep12", GPG_ERR_BAD_PASSPHRASE);