Imported Upstream version 2.2.37
[platform/upstream/gpg2.git] / sm / import.c
1 /* import.c - Import certificates
2  * Copyright (C) 2001, 2003, 2004, 2009, 2010 Free Software Foundation, Inc.
3  *
4  * This file is part of GnuPG.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
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>
28
29 #include "gpgsm.h"
30 #include <gcrypt.h>
31 #include <ksba.h>
32
33 #include "keydb.h"
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"
39 #include "minip12.h"
40
41 /* The arbitrary limit of one PKCS#12 object.  */
42 #define MAX_P12OBJ_SIZE 128 /*kb*/
43
44
45 struct stats_s {
46   unsigned long count;
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;
53  };
54
55
56 struct rsa_secret_key_s
57 {
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. */
64 };
65
66
67 static gpg_error_t parse_p12 (ctrl_t ctrl, ksba_reader_t reader,
68                               struct stats_s *stats);
69
70
71
72 static void
73 print_imported_status (ctrl_t ctrl, ksba_cert_t cert, int new_cert)
74 {
75   char *fpr;
76
77   fpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1);
78   if (new_cert)
79     gpgsm_status2 (ctrl, STATUS_IMPORTED, fpr, "[X.509]", NULL);
80
81   gpgsm_status2 (ctrl, STATUS_IMPORT_OK,
82                  new_cert? "1":"0",  fpr, NULL);
83
84   xfree (fpr);
85 }
86
87
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".
94 */
95 static void
96 print_import_problem (ctrl_t ctrl, ksba_cert_t cert, int reason)
97 {
98   char *fpr = NULL;
99   char buf[25];
100   int i;
101
102   sprintf (buf, "%d", reason);
103   if (cert)
104     {
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++)
108         ;
109       if (!fpr[i])
110         {
111           xfree (fpr);
112           fpr = NULL;
113         }
114     }
115   gpgsm_status2 (ctrl, STATUS_IMPORT_PROBLEM, buf, fpr, NULL);
116   xfree (fpr);
117 }
118
119
120 void
121 print_imported_summary (ctrl_t ctrl, struct stats_s *stats)
122 {
123   char buf[14*25];
124
125   if (!opt.quiet)
126     {
127       log_info (_("total number processed: %lu\n"), stats->count);
128       if (stats->imported)
129         {
130           log_info (_("              imported: %lu"), stats->imported );
131           log_printf ("\n");
132         }
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);
143     }
144
145   sprintf(buf, "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
146           stats->count,
147           0l /*stats->no_user_id*/,
148           stats->imported,
149           0l /*stats->imported_rsa*/,
150           stats->unchanged,
151           0l /*stats->n_uids*/,
152           0l /*stats->n_subk*/,
153           0l /*stats->n_sigs*/,
154           0l /*stats->n_revoc*/,
155           stats->secret_read,
156           stats->secret_imported,
157           stats->secret_dups,
158           0l /*stats->skipped_new_keys*/,
159           stats->not_imported
160           );
161   gpgsm_status (ctrl, STATUS_IMPORT_RES, buf);
162 }
163
164
165
166 static void
167 check_and_store (ctrl_t ctrl, struct stats_s *stats,
168                  ksba_cert_t cert, int depth)
169 {
170   int rc;
171
172   if (stats)
173     stats->count++;
174   if ( depth >= 50 )
175     {
176       log_error (_("certificate chain too long\n"));
177       if (stats)
178         stats->not_imported++;
179       print_import_problem (ctrl, cert, 3);
180       return;
181     }
182
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.
190
191      Optionally we do a full validation in addition to the basic test.
192   */
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)))
199     {
200       int existed;
201
202       if (!keydb_store_cert (ctrl, cert, 0, &existed))
203         {
204           ksba_cert_t next = NULL;
205
206           if (!existed)
207             {
208               print_imported_status (ctrl, cert, 1);
209               if (stats)
210                 stats->imported++;
211             }
212           else
213             {
214               print_imported_status (ctrl, cert, 0);
215               if (stats)
216                 stats->unchanged++;
217             }
218
219           if (opt.verbose > 1 && existed)
220             {
221               if (depth)
222                 log_info ("issuer certificate already in DB\n");
223               else
224                 log_info ("certificate already in DB\n");
225             }
226           else if (opt.verbose && !existed)
227             {
228               if (depth)
229                 log_info ("issuer certificate imported\n");
230               else
231                 log_info ("certificate imported\n");
232             }
233
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))
239             {
240               check_and_store (ctrl, NULL, next, depth+1);
241               ksba_cert_release (next);
242             }
243         }
244       else
245         {
246           log_error (_("error storing certificate\n"));
247           if (stats)
248             stats->not_imported++;
249           print_import_problem (ctrl, cert, 4);
250         }
251     }
252   else
253     {
254       log_error (_("basic certificate checks failed - not imported\n"));
255       if (stats)
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.  */
260       print_import_problem
261         (ctrl, 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);
265     }
266 }
267
268
269 \f
270
271 static int
272 import_one (ctrl_t ctrl, struct stats_s *stats, int in_fd)
273 {
274   int rc;
275   gnupg_ksba_io_t b64reader = NULL;
276   ksba_reader_t reader;
277   ksba_cert_t cert = NULL;
278   ksba_cms_t cms = NULL;
279   estream_t fp = NULL;
280   ksba_content_type_t ct;
281   int any = 0;
282
283   fp = es_fdopen_nc (in_fd, "rb");
284   if (!fp)
285     {
286       rc = gpg_error_from_syserror ();
287       log_error ("fdopen() failed: %s\n", strerror (errno));
288       goto leave;
289     }
290
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),
296      fp, &reader);
297   if (rc)
298     {
299       log_error ("can't create reader: %s\n", gpg_strerror (rc));
300       goto leave;
301     }
302
303
304   /* We need to loop here to handle multiple PEM objects in one
305      file. */
306   do
307     {
308       ksba_cms_release (cms); cms = NULL;
309       ksba_cert_release (cert); cert = NULL;
310
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;
315           int i;
316
317           rc = ksba_cms_new (&cms);
318           if (rc)
319             goto leave;
320
321           rc = ksba_cms_set_reader_writer (cms, reader, NULL);
322           if (rc)
323             {
324               log_error ("ksba_cms_set_reader_writer failed: %s\n",
325                          gpg_strerror (rc));
326               goto leave;
327             }
328
329           do
330             {
331               rc = ksba_cms_parse (cms, &stopreason);
332               if (rc)
333                 {
334                   log_error ("ksba_cms_parse failed: %s\n", gpg_strerror (rc));
335                   goto leave;
336                 }
337
338               if (stopreason == KSBA_SR_BEGIN_DATA)
339                 log_info ("not a certs-only message\n");
340             }
341           while (stopreason != KSBA_SR_READY);
342
343           for (i=0; (cert=ksba_cms_get_cert (cms, i)); i++)
344             {
345               check_and_store (ctrl, stats, cert, 0);
346               ksba_cert_release (cert);
347               cert = NULL;
348             }
349           if (!i)
350             log_error ("no certificate found\n");
351           else
352             any = 1;
353         }
354       else if (ct == KSBA_CT_PKCS12)
355         {
356           /* This seems to be a pkcs12 message. */
357           rc = parse_p12 (ctrl, reader, stats);
358           if (!rc)
359             any = 1;
360         }
361       else if (ct == KSBA_CT_NONE)
362         { /* Failed to identify this message - assume a certificate */
363
364           rc = ksba_cert_new (&cert);
365           if (rc)
366             goto leave;
367
368           rc = ksba_cert_read_der (cert, reader);
369           if (rc)
370             goto leave;
371
372           check_and_store (ctrl, stats, cert, 0);
373           any = 1;
374         }
375       else
376         {
377           log_error ("can't extract certificates from input\n");
378           rc = gpg_error (GPG_ERR_NO_DATA);
379         }
380
381       ksba_reader_clear (reader, NULL, NULL);
382     }
383   while (!gnupg_ksba_reader_eof_seen (b64reader));
384
385  leave:
386   if (any && gpg_err_code (rc) == GPG_ERR_EOF)
387     rc = 0;
388   ksba_cms_release (cms);
389   ksba_cert_release (cert);
390   gnupg_ksba_destroy_reader (b64reader);
391   es_fclose (fp);
392   return rc;
393 }
394
395
396 \f
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.  */
400 static int
401 reimport_one (ctrl_t ctrl, struct stats_s *stats, int in_fd)
402 {
403   gpg_error_t err = 0;
404   estream_t fp = NULL;
405   char line[100];  /* Sufficient for a fingerprint.  */
406   KEYDB_HANDLE kh;
407   KEYDB_SEARCH_DESC desc;
408   ksba_cert_t cert = NULL;
409   unsigned int flags;
410
411   kh = keydb_new ();
412   if (!kh)
413     {
414       err = gpg_error (GPG_ERR_ENOMEM);;
415       log_error (_("failed to allocate keyDB handle\n"));
416       goto leave;
417     }
418   keydb_set_ephemeral (kh, 1);
419
420   fp = es_fdopen_nc (in_fd, "r");
421   if (!fp)
422     {
423       err = gpg_error_from_syserror ();
424       log_error ("es_fdopen(%d) failed: %s\n", in_fd, gpg_strerror (err));
425       goto leave;
426     }
427
428   while (es_fgets (line, DIM(line)-1, fp) )
429     {
430       if (*line && line[strlen(line)-1] != '\n')
431         {
432           err = gpg_error (GPG_ERR_LINE_TOO_LONG);
433           goto leave;
434         }
435       trim_spaces (line);
436       if (!*line)
437         continue;
438
439       stats->count++;
440
441       err = classify_user_id (line, &desc, 0);
442       if (err)
443         {
444           print_import_problem (ctrl, NULL, 0);
445           stats->not_imported++;
446           continue;
447         }
448
449       keydb_search_reset (kh);
450       err = keydb_search (ctrl, kh, &desc, 1);
451       if (err)
452         {
453           print_import_problem (ctrl, NULL, 0);
454           stats->not_imported++;
455           continue;
456         }
457
458       ksba_cert_release (cert);
459       cert = NULL;
460       err = keydb_get_cert (kh, &cert);
461       if (err)
462         {
463           log_error ("keydb_get_cert() failed: %s\n", gpg_strerror (err));
464           print_import_problem (ctrl, NULL, 1);
465           stats->not_imported++;
466           continue;
467         }
468
469       err = keydb_get_flags (kh, KEYBOX_FLAG_BLOB, 0, &flags);
470       if (err)
471         {
472           log_error (_("error getting stored flags: %s\n"), gpg_strerror (err));
473           print_imported_status (ctrl, cert, 0);
474           stats->not_imported++;
475           continue;
476         }
477       if ( !(flags & KEYBOX_FLAG_BLOB_EPHEMERAL) )
478         {
479           print_imported_status (ctrl, cert, 0);
480           stats->unchanged++;
481           continue;
482         }
483
484       err = keydb_set_cert_flags (ctrl, cert, 1, KEYBOX_FLAG_BLOB, 0,
485                                   KEYBOX_FLAG_BLOB_EPHEMERAL, 0);
486       if (err)
487         {
488           log_error ("clearing ephemeral flag failed: %s\n",
489                      gpg_strerror (err));
490           print_import_problem (ctrl, cert, 0);
491           stats->not_imported++;
492           continue;
493         }
494
495       print_imported_status (ctrl, cert, 1);
496       stats->imported++;
497     }
498   err = 0;
499   if (es_ferror (fp))
500     {
501       err = gpg_error_from_syserror ();
502       log_error ("error reading fd %d: %s\n", in_fd, gpg_strerror (err));
503       goto leave;
504     }
505
506  leave:
507   ksba_cert_release (cert);
508   keydb_release (kh);
509   es_fclose (fp);
510   return err;
511 }
512
513
514 \f
515 int
516 gpgsm_import (ctrl_t ctrl, int in_fd, int reimport_mode)
517 {
518   int rc;
519   struct stats_s stats;
520
521   memset (&stats, 0, sizeof stats);
522   if (reimport_mode)
523     rc = reimport_one (ctrl, &stats, in_fd);
524   else
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));
532   return rc;
533 }
534
535
536 int
537 gpgsm_import_files (ctrl_t ctrl, int nfiles, char **files,
538                     int (*of)(const char *fname))
539 {
540   int rc = 0;
541   struct stats_s stats;
542
543   memset (&stats, 0, sizeof stats);
544
545   if (!nfiles)
546     rc = import_one (ctrl, &stats, 0);
547   else
548     {
549       for (; nfiles && !rc ; nfiles--, files++)
550         {
551           int fd = of (*files);
552           rc = import_one (ctrl, &stats, fd);
553           close (fd);
554           if (rc == -1)
555             rc = 0;
556         }
557     }
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));
564   return rc;
565 }
566
567
568 /* Check that the RSA secret key SKEY is valid.  Swap parameters to
569    the libgcrypt standard.  */
570 static gpg_error_t
571 rsa_key_check (struct rsa_secret_key_s *skey)
572 {
573   int err = 0;
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);
578
579   /* Check that n == p * q.  */
580   gcry_mpi_mul (t, skey->p, skey->q);
581   if (gcry_mpi_cmp( t, skey->n) )
582     {
583       log_error ("RSA oops: n != p * q\n");
584       err++;
585     }
586
587   /* Check that p is less than q.  */
588   if (gcry_mpi_cmp (skey->p, skey->q) > 0)
589     {
590       gcry_mpi_t tmp;
591
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);
597       /* Recompute u.  */
598       gcry_mpi_invm (skey->u, skey->p, skey->q);
599     }
600
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) )
605     {
606       log_error ("RSA oops: e divides p-1\n");
607       err++;
608     }
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))
612     {
613       log_info ("RSA oops: e divides q-1\n" );
614       err++;
615     }
616
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))
623     {
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))
629         {
630           log_error ("RSA oops: bad secret exponent\n");
631           err++;
632         }
633     }
634
635   /* Check for correctness of u.  */
636   gcry_mpi_invm (t, skey->p, skey->q);
637   if (gcry_mpi_cmp (t, skey->u))
638     {
639       log_info ("RSA oops: bad u parameter\n");
640       err++;
641     }
642
643   if (err)
644     log_info ("RSA secret key check failed\n");
645
646   gcry_mpi_release (t);
647   gcry_mpi_release (t1);
648   gcry_mpi_release (t2);
649   gcry_mpi_release (phi);
650
651   return err? gpg_error (GPG_ERR_BAD_SECKEY):0;
652 }
653
654
655 /* Object passed to store_cert_cb.  */
656 struct store_cert_parm_s
657 {
658   gpg_error_t err;        /* First error seen.  */
659   struct stats_s *stats;  /* The stats object.  */
660   ctrl_t ctrl;            /* The control object.  */
661 };
662
663 /* Helper to store the DER encoded certificate CERTDATA of length
664    CERTDATALEN.  */
665 static void
666 store_cert_cb (void *opaque,
667                const unsigned char *certdata, size_t certdatalen)
668 {
669   struct store_cert_parm_s *parm = opaque;
670   gpg_error_t err;
671   ksba_cert_t cert;
672
673   err = ksba_cert_new (&cert);
674   if (err)
675     {
676       if (!parm->err)
677         parm->err = err;
678       return;
679     }
680
681   err = ksba_cert_init_from_mem (cert, certdata, certdatalen);
682   if (err)
683     {
684       log_error ("failed to parse a certificate: %s\n", gpg_strerror (err));
685       if (!parm->err)
686         parm->err = err;
687     }
688   else
689     check_and_store (parm->ctrl, parm->stats, cert, 0);
690   ksba_cert_release (cert);
691 }
692
693
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.  */
697 static gpg_error_t
698 parse_p12 (ctrl_t ctrl, ksba_reader_t reader, struct stats_s *stats)
699 {
700   gpg_error_t err = 0;
701   char buffer[1024];
702   size_t ntotal, nread;
703   membuf_t p12mbuf;
704   char *p12buffer = NULL;
705   size_t p12buflen;
706   size_t p12bufoff;
707   gcry_mpi_t *kparms = NULL;
708   struct rsa_secret_key_s sk;
709   char *passphrase = NULL;
710   unsigned char *key = NULL;
711   size_t keylen;
712   void *kek = NULL;
713   size_t keklen;
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];
719   int bad_pass = 0;
720   int i;
721   struct store_cert_parm_s store_cert_parm;
722
723   memset (&store_cert_parm, 0, sizeof store_cert_parm);
724   store_cert_parm.ctrl = ctrl;
725   store_cert_parm.stats = stats;
726
727   init_membuf (&p12mbuf, 4096);
728   ntotal = 0;
729   while (!(err = ksba_reader_read (reader, buffer, sizeof buffer, &nread)))
730     {
731       if (ntotal >= MAX_P12OBJ_SIZE*1024)
732         {
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);
736           break;
737         }
738       put_membuf (&p12mbuf, buffer, nread);
739       ntotal += nread;
740     }
741   if (gpg_err_code (err) == GPG_ERR_EOF)
742     err = 0;
743   if (!err)
744     {
745       p12buffer = get_membuf (&p12mbuf, &p12buflen);
746       if (!p12buffer)
747         err = gpg_error_from_syserror ();
748     }
749   if (err)
750     {
751       log_error (_("error reading input: %s\n"), gpg_strerror (err));
752       goto leave;
753     }
754
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.
757      We fix that here.  */
758   if (p12buflen > 29 && !memcmp (p12buffer, "The passphrase is ", 18))
759     {
760       for (p12bufoff=18;
761            p12bufoff < p12buflen && p12buffer[p12bufoff] != '\n';
762            p12bufoff++)
763         ;
764       p12bufoff++;
765       if (p12bufoff < p12buflen && p12buffer[p12bufoff] == '\n')
766         p12bufoff++;
767     }
768   else
769     p12bufoff = 0;
770
771
772   err = gpgsm_agent_ask_passphrase
773     (ctrl,
774      i18n_utf8 (N_("Please enter the passphrase to unprotect the PKCS#12 object.")),
775      0, &passphrase);
776   if (err)
777     goto leave;
778
779   kparms = p12_parse (p12buffer + p12bufoff, p12buflen - p12bufoff,
780                       passphrase, store_cert_cb, &store_cert_parm,
781                       &bad_pass, NULL);
782
783   xfree (passphrase);
784   passphrase = NULL;
785
786   if (!kparms)
787     {
788       log_error ("error parsing or decrypting the PKCS#12 file\n");
789       err = gpg_error (GPG_ERR_INV_OBJ);
790       goto leave;
791     }
792
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]); */
801
802   sk.n = kparms[0];
803   sk.e = kparms[1];
804   sk.d = kparms[2];
805   sk.q = kparms[3];
806   sk.p = kparms[4];
807   sk.u = kparms[7];
808   err = rsa_key_check (&sk);
809   if (err)
810     goto leave;
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); */
817
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]);
824   gcry_free (kparms);
825   kparms = NULL;
826   if (err)
827     {
828       log_error ("failed to create S-expression from key: %s\n",
829                  gpg_strerror (err));
830       goto leave;
831     }
832
833   /* Compute the keygrip. */
834   if (!gcry_pk_get_keygrip (s_key, grip))
835     {
836       err = gpg_error (GPG_ERR_GENERAL);
837       log_error ("can't calculate keygrip\n");
838       goto leave;
839     }
840   if (DBG_X509)
841     log_printhex (grip, 20, "keygrip=");
842
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);
846   if (err)
847     {
848       log_error ("error creating canonical S-expression\n");
849       goto leave;
850     }
851   gcry_sexp_release (s_key);
852   s_key = NULL;
853
854   /* Get the current KEK.  */
855   err = gpgsm_agent_keywrap_key (ctrl, 0, &kek, &keklen);
856   if (err)
857     {
858       log_error ("error getting the KEK: %s\n", gpg_strerror (err));
859       goto leave;
860     }
861
862   /* Wrap the key.  */
863   err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
864                           GCRY_CIPHER_MODE_AESWRAP, 0);
865   if (err)
866     goto leave;
867   err = gcry_cipher_setkey (cipherhd, kek, keklen);
868   if (err)
869     goto leave;
870   xfree (kek);
871   kek = NULL;
872
873   wrappedkeylen = keylen + 8;
874   wrappedkey = xtrymalloc (wrappedkeylen);
875   if (!wrappedkey)
876     {
877       err = gpg_error_from_syserror ();
878       goto leave;
879     }
880
881   err = gcry_cipher_encrypt (cipherhd, wrappedkey, wrappedkeylen, key, keylen);
882   if (err)
883     goto leave;
884   xfree (key);
885   key = NULL;
886   gcry_cipher_close (cipherhd);
887   cipherhd = NULL;
888
889   /* Send the wrapped key to the agent.  */
890   err = gpgsm_agent_import_key (ctrl, wrappedkey, wrappedkeylen);
891   if (!err)
892     {
893       stats->count++;
894       stats->secret_read++;
895       stats->secret_imported++;
896     }
897   else if ( gpg_err_code (err) == GPG_ERR_EEXIST )
898     {
899       err = 0;
900       stats->count++;
901       stats->secret_read++;
902       stats->secret_dups++;
903     }
904
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;
911
912  leave:
913   if (kparms)
914     {
915       for (i=0; i < 8; i++)
916         gcry_mpi_release (kparms[i]);
917       gcry_free (kparms);
918       kparms = NULL;
919     }
920   xfree (key);
921   gcry_sexp_release (s_key);
922   xfree (passphrase);
923   gcry_cipher_close (cipherhd);
924   xfree (wrappedkey);
925   xfree (kek);
926   xfree (get_membuf (&p12mbuf, NULL));
927   xfree (p12buffer);
928
929   if (bad_pass)
930     {
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);
938     }
939
940   return err;
941 }