config: fix HP-UX PA-RISC detection.
[openssl.git] / apps / pkcs12.c
1 /*
2  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3  * project.
4  */
5 /* ====================================================================
6  * Copyright (c) 1999-2006 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58
59 #include <openssl/opensslconf.h>
60 #if !defined(OPENSSL_NO_DES)
61
62 # include <stdio.h>
63 # include <stdlib.h>
64 # include <string.h>
65 # include "apps.h"
66 # include <openssl/crypto.h>
67 # include <openssl/err.h>
68 # include <openssl/pem.h>
69 # include <openssl/pkcs12.h>
70
71 # define NOKEYS          0x1
72 # define NOCERTS         0x2
73 # define INFO            0x4
74 # define CLCERTS         0x8
75 # define CACERTS         0x10
76
77 static int get_cert_chain(X509 *cert, X509_STORE *store,
78                           STACK_OF(X509) **chain);
79 int dump_certs_keys_p12(BIO *out, PKCS12 *p12, char *pass, int passlen,
80                         int options, char *pempass, const EVP_CIPHER *enc);
81 int dump_certs_pkeys_bags(BIO *out, STACK_OF(PKCS12_SAFEBAG) *bags,
82                           char *pass, int passlen, int options, char *pempass,
83                           const EVP_CIPHER *enc);
84 int dump_certs_pkeys_bag(BIO *out, PKCS12_SAFEBAG *bags, char *pass,
85                          int passlen, int options, char *pempass,
86                          const EVP_CIPHER *enc);
87 int print_attribs(BIO *out, STACK_OF(X509_ATTRIBUTE) *attrlst,
88                   const char *name);
89 void hex_prin(BIO *out, unsigned char *buf, int len);
90 static int alg_print(X509_ALGOR *alg);
91 int cert_load(BIO *in, STACK_OF(X509) *sk);
92 static int set_pbe(int *ppbe, const char *str);
93
94 typedef enum OPTION_choice {
95     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
96     OPT_CIPHER, OPT_NOKEYS, OPT_KEYEX, OPT_KEYSIG, OPT_NOCERTS, OPT_CLCERTS,
97     OPT_CACERTS, OPT_NOOUT, OPT_INFO, OPT_CHAIN, OPT_TWOPASS, OPT_NOMACVER,
98     OPT_DESCERT, OPT_EXPORT, OPT_NOITER, OPT_MACITER, OPT_NOMACITER,
99     OPT_NOMAC, OPT_LMK, OPT_NODES, OPT_MACALG, OPT_CERTPBE, OPT_KEYPBE,
100     OPT_RAND, OPT_INKEY, OPT_CERTFILE, OPT_NAME, OPT_CSP, OPT_CANAME,
101     OPT_IN, OPT_OUT, OPT_PASSIN, OPT_PASSOUT, OPT_PASSWORD, OPT_CAPATH,
102     OPT_CAFILE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_ENGINE
103 } OPTION_CHOICE;
104
105 OPTIONS pkcs12_options[] = {
106     {"help", OPT_HELP, '-', "Display this summary"},
107     {"nokeys", OPT_NOKEYS, '-', "Don't output private keys"},
108     {"keyex", OPT_KEYEX, '-', "Set MS key exchange type"},
109     {"keysig", OPT_KEYSIG, '-', "Set MS key signature type"},
110     {"nocerts", OPT_NOCERTS, '-', "Don't output certificates"},
111     {"clcerts", OPT_CLCERTS, '-', "Only output client certificates"},
112     {"cacerts", OPT_CACERTS, '-', "Only output CA certificates"},
113     {"noout", OPT_NOOUT, '-', "Don't output anything, just verify"},
114     {"info", OPT_INFO, '-', "Print info about PKCS#12 structure"},
115     {"chain", OPT_CHAIN, '-', "Add certificate chain"},
116     {"twopass", OPT_TWOPASS, '-', "Separate MAC, encryption passwords"},
117     {"nomacver", OPT_NOMACVER, '-', "Don't verify MAC"},
118 # ifndef OPENSSL_NO_RC2
119     {"descert", OPT_DESCERT, '-',
120      "Encrypt output with 3DES (default RC2-40)"},
121     {"certpbe", OPT_CERTPBE, 's',
122      "Certificate PBE algorithm (default RC2-40)"},
123 # else
124     {"descert", OPT_DESCERT, '-', "Encrypt output with 3DES (the default)"},
125     {"certpbe", OPT_CERTPBE, 's', "Certificate PBE algorithm (default 3DES)"},
126 # endif
127     {"export", OPT_EXPORT, '-', "Output PKCS12 file"},
128     {"noiter", OPT_NOITER, '-', "Don't use encryption iteration"},
129     {"maciter", OPT_MACITER, '-', "Use MAC iteration"},
130     {"nomaciter", OPT_NOMACITER, '-', "Don't use MAC iteration"},
131     {"nomac", OPT_NOMAC, '-', "Don't generate MAC"},
132     {"LMK", OPT_LMK, '-',
133      "Add local machine keyset attribute to private key"},
134     {"nodes", OPT_NODES, '-', "Don't encrypt private keys"},
135     {"macalg", OPT_MACALG, 's',
136      "Digest algorithm used in MAC (default SHA1)"},
137     {"keypbe", OPT_KEYPBE, 's', "Private key PBE algorithm (default 3DES)"},
138     {"rand", OPT_RAND, 's',
139      "Load the file(s) into the random number generator"},
140     {"inkey", OPT_INKEY, '<', "Private key if not infile"},
141     {"certfile", OPT_CERTFILE, '<', "Load certs from file"},
142     {"name", OPT_NAME, 's', "Use name as friendly name"},
143     {"CSP", OPT_CSP, 's', "Microsoft CSP name"},
144     {"caname", OPT_CANAME, 's',
145      "Use name as CA friendly name (can be repeated)"},
146     {"in", OPT_IN, '<', "Input filename"},
147     {"out", OPT_OUT, '>', "Output filename"},
148     {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
149     {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
150     {"password", OPT_PASSWORD, 's', "Set import/export password source"},
151     {"CApath", OPT_CAPATH, '/', "PEM-format directory of CA's"},
152     {"CAfile", OPT_CAFILE, '<', "PEM-format file of CA's"},
153     {"no-CAfile", OPT_NOCAFILE, '-',
154      "Do not load the default certificates file"},
155     {"no-CApath", OPT_NOCAPATH, '-',
156      "Do not load certificates from the default certificates directory"},
157     {"", OPT_CIPHER, '-', "Any supported cipher"},
158 # ifndef OPENSSL_NO_ENGINE
159     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
160 # endif
161     {NULL}
162 };
163
164 int pkcs12_main(int argc, char **argv)
165 {
166     char *infile = NULL, *outfile = NULL, *keyname = NULL, *certfile = NULL;
167     char *name = NULL, *csp_name = NULL;
168     char pass[2048], macpass[2048];
169     int export_cert = 0, options = 0, chain = 0, twopass = 0, keytype = 0;
170     int iter = PKCS12_DEFAULT_ITER, maciter = PKCS12_DEFAULT_ITER;
171 # ifndef OPENSSL_NO_RC2
172     int cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
173 # else
174     int cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
175 # endif
176     int key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
177     int ret = 1, macver = 1, noprompt = 0, add_lmk = 0, private = 0;
178     char *passinarg = NULL, *passoutarg = NULL, *passarg = NULL;
179     char *passin = NULL, *passout = NULL, *inrand = NULL, *macalg = NULL;
180     char *cpass = NULL, *mpass = NULL, *CApath = NULL, *CAfile = NULL;
181     char *prog;
182     int noCApath = 0, noCAfile = 0;
183     ENGINE *e = NULL;
184     BIO *in = NULL, *out = NULL;
185     PKCS12 *p12 = NULL;
186     STACK_OF(OPENSSL_STRING) *canames = NULL;
187     const EVP_CIPHER *enc = EVP_des_ede3_cbc();
188     OPTION_CHOICE o;
189
190     prog = opt_init(argc, argv, pkcs12_options);
191     while ((o = opt_next()) != OPT_EOF) {
192         switch (o) {
193         case OPT_EOF:
194         case OPT_ERR:
195  opthelp:
196             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
197             goto end;
198         case OPT_HELP:
199             opt_help(pkcs12_options);
200             ret = 0;
201             goto end;
202         case OPT_NOKEYS:
203             options |= NOKEYS;
204             break;
205         case OPT_KEYEX:
206             keytype = KEY_EX;
207             break;
208         case OPT_KEYSIG:
209             keytype = KEY_SIG;
210             break;
211         case OPT_NOCERTS:
212             options |= NOCERTS;
213             break;
214         case OPT_CLCERTS:
215             options |= CLCERTS;
216             break;
217         case OPT_CACERTS:
218             options |= CACERTS;
219             break;
220         case OPT_NOOUT:
221             options |= (NOKEYS | NOCERTS);
222             break;
223         case OPT_INFO:
224             options |= INFO;
225             break;
226         case OPT_CHAIN:
227             chain = 1;
228             break;
229         case OPT_TWOPASS:
230             twopass = 1;
231             break;
232         case OPT_NOMACVER:
233             macver = 0;
234             break;
235         case OPT_DESCERT:
236             cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
237             break;
238         case OPT_EXPORT:
239             export_cert = 1;
240             break;
241         case OPT_CIPHER:
242             if (!opt_cipher(opt_unknown(), &enc))
243                 goto opthelp;
244             break;
245         case OPT_NOITER:
246             iter = 1;
247             break;
248         case OPT_MACITER:
249             maciter = PKCS12_DEFAULT_ITER;
250             break;
251         case OPT_NOMACITER:
252             maciter = 1;
253             break;
254         case OPT_NOMAC:
255             maciter = -1;
256             break;
257         case OPT_MACALG:
258             macalg = opt_arg();
259             break;
260         case OPT_NODES:
261             enc = NULL;
262             break;
263         case OPT_CERTPBE:
264             if (!set_pbe(&cert_pbe, opt_arg()))
265                 goto opthelp;
266             break;
267         case OPT_KEYPBE:
268             if (!set_pbe(&key_pbe, opt_arg()))
269                 goto opthelp;
270             break;
271         case OPT_RAND:
272             inrand = opt_arg();
273             break;
274         case OPT_INKEY:
275             keyname = opt_arg();
276             break;
277         case OPT_CERTFILE:
278             certfile = opt_arg();
279             break;
280         case OPT_NAME:
281             name = opt_arg();
282             break;
283         case OPT_LMK:
284             add_lmk = 1;
285             break;
286         case OPT_CSP:
287             csp_name = opt_arg();
288             break;
289         case OPT_CANAME:
290             if (canames == NULL
291                 && (canames = sk_OPENSSL_STRING_new_null()) == NULL)
292                 goto end;
293             sk_OPENSSL_STRING_push(canames, opt_arg());
294             break;
295         case OPT_IN:
296             infile = opt_arg();
297             break;
298         case OPT_OUT:
299             outfile = opt_arg();
300             break;
301         case OPT_PASSIN:
302             passinarg = opt_arg();
303             break;
304         case OPT_PASSOUT:
305             passoutarg = opt_arg();
306             break;
307         case OPT_PASSWORD:
308             passarg = opt_arg();
309             break;
310         case OPT_CAPATH:
311             CApath = opt_arg();
312             break;
313         case OPT_CAFILE:
314             CAfile = opt_arg();
315             break;
316         case OPT_NOCAPATH:
317             noCApath = 1;
318             break;
319         case OPT_NOCAFILE:
320             noCAfile = 1;
321             break;
322         case OPT_ENGINE:
323             e = setup_engine(opt_arg(), 0);
324             break;
325         }
326     }
327     argc = opt_num_rest();
328     if (argc != 0)
329         goto opthelp;
330
331     private = 1;
332
333     if (passarg) {
334         if (export_cert)
335             passoutarg = passarg;
336         else
337             passinarg = passarg;
338     }
339
340     if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
341         BIO_printf(bio_err, "Error getting passwords\n");
342         goto end;
343     }
344
345     if (!cpass) {
346         if (export_cert)
347             cpass = passout;
348         else
349             cpass = passin;
350     }
351
352     if (cpass) {
353         mpass = cpass;
354         noprompt = 1;
355     } else {
356         cpass = pass;
357         mpass = macpass;
358     }
359
360     if (export_cert || inrand) {
361         app_RAND_load_file(NULL, (inrand != NULL));
362         if (inrand != NULL)
363             BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
364                        app_RAND_load_files(inrand));
365     }
366
367     if (twopass) {
368         if (EVP_read_pw_string
369             (macpass, sizeof macpass, "Enter MAC Password:", export_cert)) {
370             BIO_printf(bio_err, "Can't read Password\n");
371             goto end;
372         }
373     }
374
375     if (export_cert) {
376         EVP_PKEY *key = NULL;
377         X509 *ucert = NULL, *x = NULL;
378         STACK_OF(X509) *certs = NULL;
379         const EVP_MD *macmd = NULL;
380         unsigned char *catmp = NULL;
381         int i;
382
383         if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) {
384             BIO_printf(bio_err, "Nothing to do!\n");
385             goto export_end;
386         }
387
388         if (options & NOCERTS)
389             chain = 0;
390
391         if (!(options & NOKEYS)) {
392             key = load_key(keyname ? keyname : infile,
393                            FORMAT_PEM, 1, passin, e, "private key");
394             if (!key)
395                 goto export_end;
396         }
397
398         /* Load in all certs in input file */
399         if (!(options & NOCERTS)) {
400             if (!load_certs(infile, &certs, FORMAT_PEM, NULL,
401                             "certificates"))
402                 goto export_end;
403
404             if (key) {
405                 /* Look for matching private key */
406                 for (i = 0; i < sk_X509_num(certs); i++) {
407                     x = sk_X509_value(certs, i);
408                     if (X509_check_private_key(x, key)) {
409                         ucert = x;
410                         /* Zero keyid and alias */
411                         X509_keyid_set1(ucert, NULL, 0);
412                         X509_alias_set1(ucert, NULL, 0);
413                         /* Remove from list */
414                         (void)sk_X509_delete(certs, i);
415                         break;
416                     }
417                 }
418                 if (!ucert) {
419                     BIO_printf(bio_err,
420                                "No certificate matches private key\n");
421                     goto export_end;
422                 }
423             }
424
425         }
426
427         /* Add any more certificates asked for */
428         if (certfile) {
429             if (!load_certs(certfile, &certs, FORMAT_PEM, NULL,
430                             "certificates from certfile"))
431                 goto export_end;
432         }
433
434         /* If chaining get chain from user cert */
435         if (chain) {
436             int vret;
437             STACK_OF(X509) *chain2;
438             X509_STORE *store;
439             if ((store = setup_verify(CAfile, CApath, noCAfile, noCApath))
440                     == NULL)
441                 goto export_end;
442
443             vret = get_cert_chain(ucert, store, &chain2);
444             X509_STORE_free(store);
445
446             if (vret == X509_V_OK) {
447                 /* Exclude verified certificate */
448                 for (i = 1; i < sk_X509_num(chain2); i++)
449                     sk_X509_push(certs, sk_X509_value(chain2, i));
450                 /* Free first certificate */
451                 X509_free(sk_X509_value(chain2, 0));
452                 sk_X509_free(chain2);
453             } else {
454                 if (vret != X509_V_ERR_UNSPECIFIED)
455                     BIO_printf(bio_err, "Error %s getting chain.\n",
456                                X509_verify_cert_error_string(vret));
457                 else
458                     ERR_print_errors(bio_err);
459                 goto export_end;
460             }
461         }
462
463         /* Add any CA names */
464
465         for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) {
466             catmp = (unsigned char *)sk_OPENSSL_STRING_value(canames, i);
467             X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
468         }
469
470         if (csp_name && key)
471             EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
472                                       MBSTRING_ASC, (unsigned char *)csp_name,
473                                       -1);
474
475         if (add_lmk && key)
476             EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1);
477
478         if (!noprompt &&
479             EVP_read_pw_string(pass, sizeof pass, "Enter Export Password:",
480                                1)) {
481             BIO_printf(bio_err, "Can't read Password\n");
482             goto export_end;
483         }
484         if (!twopass)
485             OPENSSL_strlcpy(macpass, pass, sizeof macpass);
486
487         p12 = PKCS12_create(cpass, name, key, ucert, certs,
488                             key_pbe, cert_pbe, iter, -1, keytype);
489
490         if (!p12) {
491             ERR_print_errors(bio_err);
492             goto export_end;
493         }
494
495         if (macalg) {
496             if (!opt_md(macalg, &macmd))
497                 goto opthelp;
498         }
499
500         if (maciter != -1)
501             PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd);
502
503         assert(private);
504
505         out = bio_open_owner(outfile, FORMAT_PKCS12, private);
506         if (out == NULL)
507             goto end;
508
509         i2d_PKCS12_bio(out, p12);
510
511         ret = 0;
512
513  export_end:
514
515         EVP_PKEY_free(key);
516         sk_X509_pop_free(certs, X509_free);
517         X509_free(ucert);
518
519         goto end;
520
521     }
522
523     in = bio_open_default(infile, 'r', FORMAT_PKCS12);
524     if (in == NULL)
525         goto end;
526     out = bio_open_owner(outfile, FORMAT_PEM, private);
527     if (out == NULL)
528         goto end;
529
530     if ((p12 = d2i_PKCS12_bio(in, NULL)) == NULL) {
531         ERR_print_errors(bio_err);
532         goto end;
533     }
534
535     if (!noprompt
536         && EVP_read_pw_string(pass, sizeof pass, "Enter Import Password:",
537                               0)) {
538         BIO_printf(bio_err, "Can't read Password\n");
539         goto end;
540     }
541
542     if (!twopass)
543         OPENSSL_strlcpy(macpass, pass, sizeof macpass);
544
545     if ((options & INFO) && PKCS12_mac_present(p12)) {
546         ASN1_INTEGER *tmaciter;
547
548         PKCS12_get0_mac(NULL, NULL, NULL, &tmaciter, p12);
549         BIO_printf(bio_err, "MAC Iteration %ld\n",
550                    tmaciter  != NULL ? ASN1_INTEGER_get(tmaciter) : 1L);
551     }
552     if (macver) {
553         /* If we enter empty password try no password first */
554         if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
555             /* If mac and crypto pass the same set it to NULL too */
556             if (!twopass)
557                 cpass = NULL;
558         } else if (!PKCS12_verify_mac(p12, mpass, -1)) {
559             BIO_printf(bio_err, "Mac verify error: invalid password?\n");
560             ERR_print_errors(bio_err);
561             goto end;
562         }
563     }
564
565     assert(private);
566     if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout, enc)) {
567         BIO_printf(bio_err, "Error outputting keys and certificates\n");
568         ERR_print_errors(bio_err);
569         goto end;
570     }
571     ret = 0;
572  end:
573     PKCS12_free(p12);
574     if (export_cert || inrand)
575         app_RAND_write_file(NULL);
576     BIO_free(in);
577     BIO_free_all(out);
578     sk_OPENSSL_STRING_free(canames);
579     OPENSSL_free(passin);
580     OPENSSL_free(passout);
581     return (ret);
582 }
583
584 int dump_certs_keys_p12(BIO *out, PKCS12 *p12, char *pass,
585                         int passlen, int options, char *pempass,
586                         const EVP_CIPHER *enc)
587 {
588     STACK_OF(PKCS7) *asafes = NULL;
589     STACK_OF(PKCS12_SAFEBAG) *bags;
590     int i, bagnid;
591     int ret = 0;
592     PKCS7 *p7;
593
594     if ((asafes = PKCS12_unpack_authsafes(p12)) == NULL)
595         return 0;
596     for (i = 0; i < sk_PKCS7_num(asafes); i++) {
597         p7 = sk_PKCS7_value(asafes, i);
598         bagnid = OBJ_obj2nid(p7->type);
599         if (bagnid == NID_pkcs7_data) {
600             bags = PKCS12_unpack_p7data(p7);
601             if (options & INFO)
602                 BIO_printf(bio_err, "PKCS7 Data\n");
603         } else if (bagnid == NID_pkcs7_encrypted) {
604             if (options & INFO) {
605                 BIO_printf(bio_err, "PKCS7 Encrypted data: ");
606                 alg_print(p7->d.encrypted->enc_data->algorithm);
607             }
608             bags = PKCS12_unpack_p7encdata(p7, pass, passlen);
609         } else
610             continue;
611         if (!bags)
612             goto err;
613         if (!dump_certs_pkeys_bags(out, bags, pass, passlen,
614                                    options, pempass, enc)) {
615             sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
616             goto err;
617         }
618         sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
619         bags = NULL;
620     }
621     ret = 1;
622
623  err:
624     sk_PKCS7_pop_free(asafes, PKCS7_free);
625     return ret;
626 }
627
628 int dump_certs_pkeys_bags(BIO *out, STACK_OF(PKCS12_SAFEBAG) *bags,
629                           char *pass, int passlen, int options, char *pempass,
630                           const EVP_CIPHER *enc)
631 {
632     int i;
633     for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) {
634         if (!dump_certs_pkeys_bag(out,
635                                   sk_PKCS12_SAFEBAG_value(bags, i),
636                                   pass, passlen, options, pempass, enc))
637             return 0;
638     }
639     return 1;
640 }
641
642 int dump_certs_pkeys_bag(BIO *out, PKCS12_SAFEBAG *bag, char *pass,
643                          int passlen, int options, char *pempass,
644                          const EVP_CIPHER *enc)
645 {
646     EVP_PKEY *pkey;
647     PKCS8_PRIV_KEY_INFO *p8;
648     X509 *x509;
649     STACK_OF(X509_ATTRIBUTE) *attrs;
650
651     attrs = PKCS12_SAFEBAG_get0_attrs(bag);
652
653     switch (PKCS12_SAFEBAG_get_nid(bag)) {
654     case NID_keyBag:
655         if (options & INFO)
656             BIO_printf(bio_err, "Key bag\n");
657         if (options & NOKEYS)
658             return 1;
659         print_attribs(out, attrs, "Bag Attributes");
660         p8 = PKCS12_SAFEBAG_get0_p8inf(bag);
661         if ((pkey = EVP_PKCS82PKEY(p8)) == NULL)
662             return 0;
663         print_attribs(out, PKCS8_pkey_get0_attrs(p8), "Key Attributes");
664         PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
665         EVP_PKEY_free(pkey);
666         break;
667
668     case NID_pkcs8ShroudedKeyBag:
669         if (options & INFO) {
670             X509_SIG *tp8;
671             X509_ALGOR *tp8alg;
672
673             BIO_printf(bio_err, "Shrouded Keybag: ");
674             tp8 = PKCS12_SAFEBAG_get0_pkcs8(bag);
675             X509_SIG_get0(&tp8alg, NULL, tp8);
676             alg_print(tp8alg);
677         }
678         if (options & NOKEYS)
679             return 1;
680         print_attribs(out, attrs, "Bag Attributes");
681         if ((p8 = PKCS12_decrypt_skey(bag, pass, passlen)) == NULL)
682             return 0;
683         if ((pkey = EVP_PKCS82PKEY(p8)) == NULL) {
684             PKCS8_PRIV_KEY_INFO_free(p8);
685             return 0;
686         }
687         print_attribs(out, PKCS8_pkey_get0_attrs(p8), "Key Attributes");
688         PKCS8_PRIV_KEY_INFO_free(p8);
689         PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
690         EVP_PKEY_free(pkey);
691         break;
692
693     case NID_certBag:
694         if (options & INFO)
695             BIO_printf(bio_err, "Certificate bag\n");
696         if (options & NOCERTS)
697             return 1;
698         if (PKCS12_SAFEBAG_get0_attr(bag, NID_localKeyID)) {
699             if (options & CACERTS)
700                 return 1;
701         } else if (options & CLCERTS)
702             return 1;
703         print_attribs(out, attrs, "Bag Attributes");
704         if (PKCS12_SAFEBAG_get_bag_nid(bag) != NID_x509Certificate)
705             return 1;
706         if ((x509 = PKCS12_SAFEBAG_get1_cert(bag)) == NULL)
707             return 0;
708         dump_cert_text(out, x509);
709         PEM_write_bio_X509(out, x509);
710         X509_free(x509);
711         break;
712
713     case NID_safeContentsBag:
714         if (options & INFO)
715             BIO_printf(bio_err, "Safe Contents bag\n");
716         print_attribs(out, attrs, "Bag Attributes");
717         return dump_certs_pkeys_bags(out, PKCS12_SAFEBAG_get0_safes(bag),
718                                      pass, passlen, options, pempass, enc);
719
720     default:
721         BIO_printf(bio_err, "Warning unsupported bag type: ");
722         i2a_ASN1_OBJECT(bio_err, PKCS12_SAFEBAG_get0_type(bag));
723         BIO_printf(bio_err, "\n");
724         return 1;
725     }
726     return 1;
727 }
728
729 /* Given a single certificate return a verified chain or NULL if error */
730
731 static int get_cert_chain(X509 *cert, X509_STORE *store,
732                           STACK_OF(X509) **chain)
733 {
734     X509_STORE_CTX store_ctx;
735     STACK_OF(X509) *chn = NULL;
736     int i = 0;
737
738     if (!X509_STORE_CTX_init(&store_ctx, store, cert, NULL)) {
739         *chain = NULL;
740         return X509_V_ERR_UNSPECIFIED;
741     }
742
743     if (X509_verify_cert(&store_ctx) > 0)
744         chn = X509_STORE_CTX_get1_chain(&store_ctx);
745     else if ((i = X509_STORE_CTX_get_error(&store_ctx)) == 0)
746         i = X509_V_ERR_UNSPECIFIED;
747
748     X509_STORE_CTX_cleanup(&store_ctx);
749     *chain = chn;
750     return i;
751 }
752
753 static int alg_print(X509_ALGOR *alg)
754 {
755     PBEPARAM *pbe;
756     const unsigned char *p = alg->parameter->value.sequence->data;
757
758     pbe = d2i_PBEPARAM(NULL, &p, alg->parameter->value.sequence->length);
759     if (!pbe)
760         return 1;
761     BIO_printf(bio_err, "%s, Iteration %ld\n",
762                OBJ_nid2ln(OBJ_obj2nid(alg->algorithm)),
763                ASN1_INTEGER_get(pbe->iter));
764     PBEPARAM_free(pbe);
765     return 1;
766 }
767
768 /* Load all certificates from a given file */
769
770 int cert_load(BIO *in, STACK_OF(X509) *sk)
771 {
772     int ret;
773     X509 *cert;
774     ret = 0;
775     while ((cert = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
776         ret = 1;
777         sk_X509_push(sk, cert);
778     }
779     if (ret)
780         ERR_clear_error();
781     return ret;
782 }
783
784 /* Generalised attribute print: handle PKCS#8 and bag attributes */
785
786 int print_attribs(BIO *out, STACK_OF(X509_ATTRIBUTE) *attrlst,
787                   const char *name)
788 {
789     X509_ATTRIBUTE *attr;
790     ASN1_TYPE *av;
791     char *value;
792     int i, attr_nid;
793     if (!attrlst) {
794         BIO_printf(out, "%s: <No Attributes>\n", name);
795         return 1;
796     }
797     if (!sk_X509_ATTRIBUTE_num(attrlst)) {
798         BIO_printf(out, "%s: <Empty Attributes>\n", name);
799         return 1;
800     }
801     BIO_printf(out, "%s\n", name);
802     for (i = 0; i < sk_X509_ATTRIBUTE_num(attrlst); i++) {
803         ASN1_OBJECT *attr_obj;
804         attr = sk_X509_ATTRIBUTE_value(attrlst, i);
805         attr_obj = X509_ATTRIBUTE_get0_object(attr);
806         attr_nid = OBJ_obj2nid(attr_obj);
807         BIO_printf(out, "    ");
808         if (attr_nid == NID_undef) {
809             i2a_ASN1_OBJECT(out, attr_obj);
810             BIO_printf(out, ": ");
811         } else
812             BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid));
813
814         if (X509_ATTRIBUTE_count(attr)) {
815             av = X509_ATTRIBUTE_get0_type(attr, 0);
816             switch (av->type) {
817             case V_ASN1_BMPSTRING:
818                 value = OPENSSL_uni2asc(av->value.bmpstring->data,
819                                         av->value.bmpstring->length);
820                 BIO_printf(out, "%s\n", value);
821                 OPENSSL_free(value);
822                 break;
823
824             case V_ASN1_OCTET_STRING:
825                 hex_prin(out, av->value.octet_string->data,
826                          av->value.octet_string->length);
827                 BIO_printf(out, "\n");
828                 break;
829
830             case V_ASN1_BIT_STRING:
831                 hex_prin(out, av->value.bit_string->data,
832                          av->value.bit_string->length);
833                 BIO_printf(out, "\n");
834                 break;
835
836             default:
837                 BIO_printf(out, "<Unsupported tag %d>\n", av->type);
838                 break;
839             }
840         } else
841             BIO_printf(out, "<No Values>\n");
842     }
843     return 1;
844 }
845
846 void hex_prin(BIO *out, unsigned char *buf, int len)
847 {
848     int i;
849     for (i = 0; i < len; i++)
850         BIO_printf(out, "%02X ", buf[i]);
851 }
852
853 static int set_pbe(int *ppbe, const char *str)
854 {
855     if (!str)
856         return 0;
857     if (strcmp(str, "NONE") == 0) {
858         *ppbe = -1;
859         return 1;
860     }
861     *ppbe = OBJ_txt2nid(str);
862     if (*ppbe == NID_undef) {
863         BIO_printf(bio_err, "Unknown PBE algorithm %s\n", str);
864         return 0;
865     }
866     return 1;
867 }
868
869 #endif