Add -CAstore and similar to all openssl commands that have -CApath
[openssl.git] / apps / cms.c
1 /*
2  * Copyright 2008-2019 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /* CMS utility function */
11
12 #include <stdio.h>
13 #include <string.h>
14 #include "apps.h"
15 #include "progs.h"
16
17 #ifndef OPENSSL_NO_CMS
18
19 # include <openssl/crypto.h>
20 # include <openssl/pem.h>
21 # include <openssl/err.h>
22 # include <openssl/x509_vfy.h>
23 # include <openssl/x509v3.h>
24 # include <openssl/cms.h>
25
26 static int save_certs(char *signerfile, STACK_OF(X509) *signers);
27 static int cms_cb(int ok, X509_STORE_CTX *ctx);
28 static void receipt_request_print(CMS_ContentInfo *cms);
29 static CMS_ReceiptRequest *make_receipt_request(STACK_OF(OPENSSL_STRING)
30                                                 *rr_to, int rr_allorfirst, STACK_OF(OPENSSL_STRING)
31                                                 *rr_from);
32 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
33                               STACK_OF(OPENSSL_STRING) *param);
34
35 # define SMIME_OP        0x10
36 # define SMIME_IP        0x20
37 # define SMIME_SIGNERS   0x40
38 # define SMIME_ENCRYPT           (1 | SMIME_OP)
39 # define SMIME_DECRYPT           (2 | SMIME_IP)
40 # define SMIME_SIGN              (3 | SMIME_OP | SMIME_SIGNERS)
41 # define SMIME_VERIFY            (4 | SMIME_IP)
42 # define SMIME_CMSOUT            (5 | SMIME_IP | SMIME_OP)
43 # define SMIME_RESIGN            (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
44 # define SMIME_DATAOUT           (7 | SMIME_IP)
45 # define SMIME_DATA_CREATE       (8 | SMIME_OP)
46 # define SMIME_DIGEST_VERIFY     (9 | SMIME_IP)
47 # define SMIME_DIGEST_CREATE     (10 | SMIME_OP)
48 # define SMIME_UNCOMPRESS        (11 | SMIME_IP)
49 # define SMIME_COMPRESS          (12 | SMIME_OP)
50 # define SMIME_ENCRYPTED_DECRYPT (13 | SMIME_IP)
51 # define SMIME_ENCRYPTED_ENCRYPT (14 | SMIME_OP)
52 # define SMIME_SIGN_RECEIPT      (15 | SMIME_IP | SMIME_OP)
53 # define SMIME_VERIFY_RECEIPT    (16 | SMIME_IP)
54
55 static int verify_err = 0;
56
57 typedef struct cms_key_param_st cms_key_param;
58
59 struct cms_key_param_st {
60     int idx;
61     STACK_OF(OPENSSL_STRING) *param;
62     cms_key_param *next;
63 };
64
65 typedef enum OPTION_choice {
66     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
67     OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_ENCRYPT,
68     OPT_DECRYPT, OPT_SIGN, OPT_CADES, OPT_SIGN_RECEIPT, OPT_RESIGN,
69     OPT_VERIFY, OPT_VERIFY_RETCODE, OPT_VERIFY_RECEIPT,
70     OPT_CMSOUT, OPT_DATA_OUT, OPT_DATA_CREATE, OPT_DIGEST_VERIFY,
71     OPT_DIGEST_CREATE, OPT_COMPRESS, OPT_UNCOMPRESS,
72     OPT_ED_DECRYPT, OPT_ED_ENCRYPT, OPT_DEBUG_DECRYPT, OPT_TEXT,
73     OPT_ASCIICRLF, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCERTS,
74     OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP, OPT_BINARY, OPT_KEYID,
75     OPT_NOSIGS, OPT_NO_CONTENT_VERIFY, OPT_NO_ATTR_VERIFY, OPT_INDEF,
76     OPT_NOINDEF, OPT_CRLFEOL, OPT_NOOUT, OPT_RR_PRINT,
77     OPT_RR_ALL, OPT_RR_FIRST, OPT_RCTFORM, OPT_CERTFILE, OPT_CAFILE,
78     OPT_CAPATH, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE,
79     OPT_CONTENT, OPT_PRINT,
80     OPT_SECRETKEY, OPT_SECRETKEYID, OPT_PWRI_PASSWORD, OPT_ECONTENT_TYPE,
81     OPT_PASSIN, OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP,
82     OPT_CERTSOUT, OPT_MD, OPT_INKEY, OPT_KEYFORM, OPT_KEYOPT, OPT_RR_FROM,
83     OPT_RR_TO, OPT_AES128_WRAP, OPT_AES192_WRAP, OPT_AES256_WRAP,
84     OPT_3DES_WRAP, OPT_ENGINE,
85     OPT_R_ENUM,
86     OPT_V_ENUM,
87     OPT_CIPHER
88 } OPTION_CHOICE;
89
90 const OPTIONS cms_options[] = {
91     {OPT_HELP_STR, 1, '-', "Usage: %s [options] cert.pem...\n"},
92     {OPT_HELP_STR, 1, '-',
93         "  cert.pem... recipient certs for encryption\n"},
94     {OPT_HELP_STR, 1, '-', "Valid options are:\n"},
95     {"help", OPT_HELP, '-', "Display this summary"},
96     {"inform", OPT_INFORM, 'c', "Input format SMIME (default), PEM or DER"},
97     {"outform", OPT_OUTFORM, 'c',
98      "Output format SMIME (default), PEM or DER"},
99     {"in", OPT_IN, '<', "Input file"},
100     {"out", OPT_OUT, '>', "Output file"},
101     {"encrypt", OPT_ENCRYPT, '-', "Encrypt message"},
102     {"decrypt", OPT_DECRYPT, '-', "Decrypt encrypted message"},
103     {"sign", OPT_SIGN, '-', "Sign message"},
104     {"sign_receipt", OPT_SIGN_RECEIPT, '-', "Generate a signed receipt for the message"},
105     {"resign", OPT_RESIGN, '-', "Resign a signed message"},
106     {"cades", OPT_CADES, '-', "Include signer certificate digest"},
107     {"verify", OPT_VERIFY, '-', "Verify signed message"},
108     {"verify_retcode", OPT_VERIFY_RETCODE, '-',
109         "Exit non-zero on verification failure"},
110     {"verify_receipt", OPT_VERIFY_RECEIPT, '<',
111         "Verify receipts; exit if receipt signatures do not verify"},
112     {"cmsout", OPT_CMSOUT, '-', "Output CMS structure"},
113     {"data_out", OPT_DATA_OUT, '-', "Copy CMS \"Data\" object to output"},
114     {"data_create", OPT_DATA_CREATE, '-', "Create a CMS \"Data\" object"},
115     {"digest_verify", OPT_DIGEST_VERIFY, '-',
116         "Verify a CMS \"DigestedData\" object and output it"},
117     {"digest_create", OPT_DIGEST_CREATE, '-',
118         "Create a CMS \"DigestedData\" object"},
119     {"compress", OPT_COMPRESS, '-', "Create a CMS \"CompressedData\" object"},
120     {"uncompress", OPT_UNCOMPRESS, '-', "Uncompress a CMS \"CompressedData\" object"},
121     {"EncryptedData_decrypt", OPT_ED_DECRYPT, '-',
122         "Decrypt CMS \"EncryptedData\" object using symmetric key"},
123     {"EncryptedData_encrypt", OPT_ED_ENCRYPT, '-',
124         "Create CMS \"EncryptedData\" object using symmetric key"},
125     {"debug_decrypt", OPT_DEBUG_DECRYPT, '-',
126         "Disable MMA protection and return an error if no recipient found"
127         " (see documentation)"},
128     {"text", OPT_TEXT, '-', "Include or delete text MIME headers"},
129     {"asciicrlf", OPT_ASCIICRLF, '-',
130         "Perform CRLF canonicalisation when signing"},
131     {"nointern", OPT_NOINTERN, '-',
132      "Don't search certificates in message for signer"},
133     {"noverify", OPT_NOVERIFY, '-', "Don't verify signers certificate"},
134     {"nocerts", OPT_NOCERTS, '-',
135      "Don't include signers certificate when signing"},
136     {"noattr", OPT_NOATTR, '-', "Don't include any signed attributes"},
137     {"nodetach", OPT_NODETACH, '-', "Use opaque signing"},
138     {"nosmimecap", OPT_NOSMIMECAP, '-', "Omit the SMIMECapabilities attribute"},
139     {"binary", OPT_BINARY, '-', "Don't translate message to text"},
140     {"keyid", OPT_KEYID, '-', "Use subject key identifier"},
141     {"nosigs", OPT_NOSIGS, '-', "Don't verify message signature"},
142     {"no_content_verify", OPT_NO_CONTENT_VERIFY, '-',
143         "Do not verify signed content signatures"},
144     {"no_attr_verify", OPT_NO_ATTR_VERIFY, '-',
145         "Do not verify signed attribute signatures"},
146     {"stream", OPT_INDEF, '-', "Enable CMS streaming"},
147     {"indef", OPT_INDEF, '-', "Same as -stream"},
148     {"noindef", OPT_NOINDEF, '-', "Disable CMS streaming"},
149     {"crlfeol", OPT_CRLFEOL, '-', "Use CRLF as EOL termination instead of CR only" },
150     {"noout", OPT_NOOUT, '-', "For the -cmsout operation do not output the parsed CMS structure"},
151     {"receipt_request_print", OPT_RR_PRINT, '-', "Print CMS Receipt Request" },
152     {"receipt_request_all", OPT_RR_ALL, '-',
153         "When signing, create a receipt request for all recipients"},
154     {"receipt_request_first", OPT_RR_FIRST, '-',
155         "When signing, create a receipt request for first recipient"},
156     {"rctform", OPT_RCTFORM, 'F', "Receipt file format"},
157     {"certfile", OPT_CERTFILE, '<', "Other certificates file"},
158     {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
159     {"CApath", OPT_CAPATH, '/', "trusted certificates directory"},
160     {"CAstore", OPT_CASTORE, ':', "trusted certificates store URI"},
161     {"no-CAfile", OPT_NOCAFILE, '-',
162      "Do not load the default certificates file"},
163     {"no-CApath", OPT_NOCAPATH, '-',
164      "Do not load certificates from the default certificates directory"},
165     {"no-CAstore", OPT_NOCASTORE, '-',
166      "Do not load certificates from the default certificates store"},
167     {"content", OPT_CONTENT, '<',
168      "Supply or override content for detached signature"},
169     {"print", OPT_PRINT, '-',
170      "For the -cmsout operation print out all fields of the CMS structure"},
171     {"secretkey", OPT_SECRETKEY, 's',
172         "Use specified hex-encoded key to decrypt/encrypt recipients or content"},
173     {"secretkeyid", OPT_SECRETKEYID, 's',
174         "Identity of the -secretkey for CMS \"KEKRecipientInfo\" object"},
175     {"pwri_password", OPT_PWRI_PASSWORD, 's',
176         "Specific password for recipient"},
177     {"econtent_type", OPT_ECONTENT_TYPE, 's', "OID for external content"},
178     {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
179     {"to", OPT_TO, 's', "To address"},
180     {"from", OPT_FROM, 's', "From address"},
181     {"subject", OPT_SUBJECT, 's', "Subject"},
182     {"signer", OPT_SIGNER, 's', "Signer certificate file"},
183     {"recip", OPT_RECIP, '<', "Recipient cert file for decryption"},
184     {"certsout", OPT_CERTSOUT, '>', "Certificate output file"},
185     {"md", OPT_MD, 's', "Digest algorithm to use when signing or resigning"},
186     {"inkey", OPT_INKEY, 's',
187      "Input private key (if not signer or recipient)"},
188     {"keyform", OPT_KEYFORM, 'f', "Input private key format (PEM or ENGINE)"},
189     {"keyopt", OPT_KEYOPT, 's', "Set public key parameters as n:v pairs"},
190     {"receipt_request_from", OPT_RR_FROM, 's',
191         "Create signed receipt request with specified email address"},
192     {"receipt_request_to", OPT_RR_TO, 's',
193         "Create signed receipt targeted to specified address"},
194     {"", OPT_CIPHER, '-', "Any supported cipher"},
195     OPT_R_OPTIONS,
196     OPT_V_OPTIONS,
197     {"aes128-wrap", OPT_AES128_WRAP, '-', "Use AES128 to wrap key"},
198     {"aes192-wrap", OPT_AES192_WRAP, '-', "Use AES192 to wrap key"},
199     {"aes256-wrap", OPT_AES256_WRAP, '-', "Use AES256 to wrap key"},
200 # ifndef OPENSSL_NO_DES
201     {"des3-wrap", OPT_3DES_WRAP, '-', "Use 3DES-EDE to wrap key"},
202 # endif
203 # ifndef OPENSSL_NO_ENGINE
204     {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
205 # endif
206     {NULL}
207 };
208
209 int cms_main(int argc, char **argv)
210 {
211     ASN1_OBJECT *econtent_type = NULL;
212     BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL;
213     CMS_ContentInfo *cms = NULL, *rcms = NULL;
214     CMS_ReceiptRequest *rr = NULL;
215     ENGINE *e = NULL;
216     EVP_PKEY *key = NULL;
217     const EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL;
218     const EVP_MD *sign_md = NULL;
219     STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL;
220     STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
221     STACK_OF(X509) *encerts = NULL, *other = NULL;
222     X509 *cert = NULL, *recip = NULL, *signer = NULL;
223     X509_STORE *store = NULL;
224     X509_VERIFY_PARAM *vpm = NULL;
225     char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
226     const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
227     char *certsoutfile = NULL;
228     int noCAfile = 0, noCApath = 0, noCAstore = 0;
229     char *infile = NULL, *outfile = NULL, *rctfile = NULL;
230     char *passinarg = NULL, *passin = NULL, *signerfile = NULL, *recipfile = NULL;
231     char *to = NULL, *from = NULL, *subject = NULL, *prog;
232     cms_key_param *key_first = NULL, *key_param = NULL;
233     int flags = CMS_DETACHED, noout = 0, print = 0, keyidx = -1, vpmtouched = 0;
234     int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
235     int operation = 0, ret = 1, rr_print = 0, rr_allorfirst = -1;
236     int verify_retcode = 0, rctformat = FORMAT_SMIME, keyform = FORMAT_PEM;
237     size_t secret_keylen = 0, secret_keyidlen = 0;
238     unsigned char *pwri_pass = NULL, *pwri_tmp = NULL;
239     unsigned char *secret_key = NULL, *secret_keyid = NULL;
240     long ltmp;
241     const char *mime_eol = "\n";
242     OPTION_CHOICE o;
243
244     if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
245         return 1;
246
247     prog = opt_init(argc, argv, cms_options);
248     while ((o = opt_next()) != OPT_EOF) {
249         switch (o) {
250         case OPT_EOF:
251         case OPT_ERR:
252  opthelp:
253             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
254             goto end;
255         case OPT_HELP:
256             opt_help(cms_options);
257             ret = 0;
258             goto end;
259         case OPT_INFORM:
260             if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat))
261                 goto opthelp;
262             break;
263         case OPT_OUTFORM:
264             if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat))
265                 goto opthelp;
266             break;
267         case OPT_OUT:
268             outfile = opt_arg();
269             break;
270         case OPT_ENCRYPT:
271             operation = SMIME_ENCRYPT;
272             break;
273         case OPT_DECRYPT:
274             operation = SMIME_DECRYPT;
275             break;
276         case OPT_SIGN:
277             operation = SMIME_SIGN;
278             break;
279         case OPT_SIGN_RECEIPT:
280             operation = SMIME_SIGN_RECEIPT;
281             break;
282         case OPT_RESIGN:
283             operation = SMIME_RESIGN;
284             break;
285         case OPT_VERIFY:
286             operation = SMIME_VERIFY;
287             break;
288         case OPT_VERIFY_RETCODE:
289             verify_retcode = 1;
290             break;
291         case OPT_VERIFY_RECEIPT:
292             operation = SMIME_VERIFY_RECEIPT;
293             rctfile = opt_arg();
294             break;
295         case OPT_CMSOUT:
296             operation = SMIME_CMSOUT;
297             break;
298         case OPT_DATA_OUT:
299             operation = SMIME_DATAOUT;
300             break;
301         case OPT_DATA_CREATE:
302             operation = SMIME_DATA_CREATE;
303             break;
304         case OPT_DIGEST_VERIFY:
305             operation = SMIME_DIGEST_VERIFY;
306             break;
307         case OPT_DIGEST_CREATE:
308             operation = SMIME_DIGEST_CREATE;
309             break;
310         case OPT_COMPRESS:
311             operation = SMIME_COMPRESS;
312             break;
313         case OPT_UNCOMPRESS:
314             operation = SMIME_UNCOMPRESS;
315             break;
316         case OPT_ED_DECRYPT:
317             operation = SMIME_ENCRYPTED_DECRYPT;
318             break;
319         case OPT_ED_ENCRYPT:
320             operation = SMIME_ENCRYPTED_ENCRYPT;
321             break;
322         case OPT_DEBUG_DECRYPT:
323             flags |= CMS_DEBUG_DECRYPT;
324             break;
325         case OPT_TEXT:
326             flags |= CMS_TEXT;
327             break;
328         case OPT_ASCIICRLF:
329             flags |= CMS_ASCIICRLF;
330             break;
331         case OPT_NOINTERN:
332             flags |= CMS_NOINTERN;
333             break;
334         case OPT_NOVERIFY:
335             flags |= CMS_NO_SIGNER_CERT_VERIFY;
336             break;
337         case OPT_NOCERTS:
338             flags |= CMS_NOCERTS;
339             break;
340         case OPT_NOATTR:
341             flags |= CMS_NOATTR;
342             break;
343         case OPT_NODETACH:
344             flags &= ~CMS_DETACHED;
345             break;
346         case OPT_NOSMIMECAP:
347             flags |= CMS_NOSMIMECAP;
348             break;
349         case OPT_BINARY:
350             flags |= CMS_BINARY;
351             break;
352         case OPT_CADES:
353             flags |= CMS_CADES;
354             break;
355         case OPT_KEYID:
356             flags |= CMS_USE_KEYID;
357             break;
358         case OPT_NOSIGS:
359             flags |= CMS_NOSIGS;
360             break;
361         case OPT_NO_CONTENT_VERIFY:
362             flags |= CMS_NO_CONTENT_VERIFY;
363             break;
364         case OPT_NO_ATTR_VERIFY:
365             flags |= CMS_NO_ATTR_VERIFY;
366             break;
367         case OPT_INDEF:
368             flags |= CMS_STREAM;
369             break;
370         case OPT_NOINDEF:
371             flags &= ~CMS_STREAM;
372             break;
373         case OPT_CRLFEOL:
374             mime_eol = "\r\n";
375             flags |= CMS_CRLFEOL;
376             break;
377         case OPT_NOOUT:
378             noout = 1;
379             break;
380         case OPT_RR_PRINT:
381             rr_print = 1;
382             break;
383         case OPT_RR_ALL:
384             rr_allorfirst = 0;
385             break;
386         case OPT_RR_FIRST:
387             rr_allorfirst = 1;
388             break;
389         case OPT_RCTFORM:
390             if (rctformat == FORMAT_SMIME)
391                 rcms = SMIME_read_CMS(rctin, NULL);
392             else if (rctformat == FORMAT_PEM)
393                 rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL);
394             else if (rctformat == FORMAT_ASN1)
395                 if (!opt_format(opt_arg(),
396                                 OPT_FMT_PEMDER | OPT_FMT_SMIME, &rctformat))
397                     goto opthelp;
398             break;
399         case OPT_CERTFILE:
400             certfile = opt_arg();
401             break;
402         case OPT_CAFILE:
403             CAfile = opt_arg();
404             break;
405         case OPT_CAPATH:
406             CApath = opt_arg();
407             break;
408         case OPT_CASTORE:
409             CAstore = opt_arg();
410             break;
411         case OPT_NOCAFILE:
412             noCAfile = 1;
413             break;
414         case OPT_NOCAPATH:
415             noCApath = 1;
416             break;
417         case OPT_NOCASTORE:
418             noCAstore = 1;
419             break;
420         case OPT_IN:
421             infile = opt_arg();
422             break;
423         case OPT_CONTENT:
424             contfile = opt_arg();
425             break;
426         case OPT_RR_FROM:
427             if (rr_from == NULL
428                 && (rr_from = sk_OPENSSL_STRING_new_null()) == NULL)
429                 goto end;
430             sk_OPENSSL_STRING_push(rr_from, opt_arg());
431             break;
432         case OPT_RR_TO:
433             if (rr_to == NULL
434                 && (rr_to = sk_OPENSSL_STRING_new_null()) == NULL)
435                 goto end;
436             sk_OPENSSL_STRING_push(rr_to, opt_arg());
437             break;
438         case OPT_PRINT:
439             noout = print = 1;
440             break;
441         case OPT_SECRETKEY:
442             if (secret_key != NULL) {
443                 BIO_printf(bio_err, "Invalid key (supplied twice) %s\n",
444                            opt_arg());
445                 goto opthelp;
446             }
447             secret_key = OPENSSL_hexstr2buf(opt_arg(), &ltmp);
448             if (secret_key == NULL) {
449                 BIO_printf(bio_err, "Invalid key %s\n", opt_arg());
450                 goto end;
451             }
452             secret_keylen = (size_t)ltmp;
453             break;
454         case OPT_SECRETKEYID:
455             if (secret_keyid != NULL) {
456                 BIO_printf(bio_err, "Invalid id (supplied twice) %s\n",
457                            opt_arg());
458                 goto opthelp;
459             }
460             secret_keyid = OPENSSL_hexstr2buf(opt_arg(), &ltmp);
461             if (secret_keyid == NULL) {
462                 BIO_printf(bio_err, "Invalid id %s\n", opt_arg());
463                 goto opthelp;
464             }
465             secret_keyidlen = (size_t)ltmp;
466             break;
467         case OPT_PWRI_PASSWORD:
468             pwri_pass = (unsigned char *)opt_arg();
469             break;
470         case OPT_ECONTENT_TYPE:
471             if (econtent_type != NULL) {
472                 BIO_printf(bio_err, "Invalid OID (supplied twice) %s\n",
473                            opt_arg());
474                 goto opthelp;
475             }
476             econtent_type = OBJ_txt2obj(opt_arg(), 0);
477             if (econtent_type == NULL) {
478                 BIO_printf(bio_err, "Invalid OID %s\n", opt_arg());
479                 goto opthelp;
480             }
481             break;
482         case OPT_ENGINE:
483             e = setup_engine(opt_arg(), 0);
484             break;
485         case OPT_PASSIN:
486             passinarg = opt_arg();
487             break;
488         case OPT_TO:
489             to = opt_arg();
490             break;
491         case OPT_FROM:
492             from = opt_arg();
493             break;
494         case OPT_SUBJECT:
495             subject = opt_arg();
496             break;
497         case OPT_CERTSOUT:
498             certsoutfile = opt_arg();
499             break;
500         case OPT_MD:
501             if (!opt_md(opt_arg(), &sign_md))
502                 goto end;
503             break;
504         case OPT_SIGNER:
505             /* If previous -signer argument add signer to list */
506             if (signerfile != NULL) {
507                 if (sksigners == NULL
508                     && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
509                     goto end;
510                 sk_OPENSSL_STRING_push(sksigners, signerfile);
511                 if (keyfile == NULL)
512                     keyfile = signerfile;
513                 if (skkeys == NULL
514                     && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
515                     goto end;
516                 sk_OPENSSL_STRING_push(skkeys, keyfile);
517                 keyfile = NULL;
518             }
519             signerfile = opt_arg();
520             break;
521         case OPT_INKEY:
522             /* If previous -inkey argument add signer to list */
523             if (keyfile != NULL) {
524                 if (signerfile == NULL) {
525                     BIO_puts(bio_err, "Illegal -inkey without -signer\n");
526                     goto end;
527                 }
528                 if (sksigners == NULL
529                     && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
530                     goto end;
531                 sk_OPENSSL_STRING_push(sksigners, signerfile);
532                 signerfile = NULL;
533                 if (skkeys == NULL
534                     && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
535                     goto end;
536                 sk_OPENSSL_STRING_push(skkeys, keyfile);
537             }
538             keyfile = opt_arg();
539             break;
540         case OPT_KEYFORM:
541             if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
542                 goto opthelp;
543             break;
544         case OPT_RECIP:
545             if (operation == SMIME_ENCRYPT) {
546                 if (encerts == NULL && (encerts = sk_X509_new_null()) == NULL)
547                     goto end;
548                 cert = load_cert(opt_arg(), FORMAT_PEM,
549                                  "recipient certificate file");
550                 if (cert == NULL)
551                     goto end;
552                 sk_X509_push(encerts, cert);
553                 cert = NULL;
554             } else {
555                 recipfile = opt_arg();
556             }
557             break;
558         case OPT_CIPHER:
559             if (!opt_cipher(opt_unknown(), &cipher))
560                 goto end;
561             break;
562         case OPT_KEYOPT:
563             keyidx = -1;
564             if (operation == SMIME_ENCRYPT) {
565                 if (encerts != NULL)
566                     keyidx += sk_X509_num(encerts);
567             } else {
568                 if (keyfile != NULL || signerfile != NULL)
569                     keyidx++;
570                 if (skkeys != NULL)
571                     keyidx += sk_OPENSSL_STRING_num(skkeys);
572             }
573             if (keyidx < 0) {
574                 BIO_printf(bio_err, "No key specified\n");
575                 goto opthelp;
576             }
577             if (key_param == NULL || key_param->idx != keyidx) {
578                 cms_key_param *nparam;
579                 nparam = app_malloc(sizeof(*nparam), "key param buffer");
580                 nparam->idx = keyidx;
581                 if ((nparam->param = sk_OPENSSL_STRING_new_null()) == NULL)
582                     goto end;
583                 nparam->next = NULL;
584                 if (key_first == NULL)
585                     key_first = nparam;
586                 else
587                     key_param->next = nparam;
588                 key_param = nparam;
589             }
590             sk_OPENSSL_STRING_push(key_param->param, opt_arg());
591             break;
592         case OPT_V_CASES:
593             if (!opt_verify(o, vpm))
594                 goto end;
595             vpmtouched++;
596             break;
597         case OPT_R_CASES:
598             if (!opt_rand(o))
599                 goto end;
600             break;
601         case OPT_3DES_WRAP:
602 # ifndef OPENSSL_NO_DES
603             wrap_cipher = EVP_des_ede3_wrap();
604 # endif
605             break;
606         case OPT_AES128_WRAP:
607             wrap_cipher = EVP_aes_128_wrap();
608             break;
609         case OPT_AES192_WRAP:
610             wrap_cipher = EVP_aes_192_wrap();
611             break;
612         case OPT_AES256_WRAP:
613             wrap_cipher = EVP_aes_256_wrap();
614             break;
615         }
616     }
617     argc = opt_num_rest();
618     argv = opt_rest();
619
620     if ((rr_allorfirst != -1 || rr_from != NULL) && rr_to == NULL) {
621         BIO_puts(bio_err, "No Signed Receipts Recipients\n");
622         goto opthelp;
623     }
624
625     if (!(operation & SMIME_SIGNERS) && (rr_to != NULL || rr_from != NULL)) {
626         BIO_puts(bio_err, "Signed receipts only allowed with -sign\n");
627         goto opthelp;
628     }
629     if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) {
630         BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
631         goto opthelp;
632     }
633
634     if (flags & CMS_CADES) {
635         if (flags & CMS_NOATTR) {
636             BIO_puts(bio_err, "Incompatible options: "
637                      "CAdES required signed attributes\n");
638             goto opthelp;
639         }
640     }
641
642     if (operation & SMIME_SIGNERS) {
643         if (keyfile != NULL && signerfile == NULL) {
644             BIO_puts(bio_err, "Illegal -inkey without -signer\n");
645             goto opthelp;
646         }
647         /* Check to see if any final signer needs to be appended */
648         if (signerfile != NULL) {
649             if (sksigners == NULL
650                 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
651                 goto end;
652             sk_OPENSSL_STRING_push(sksigners, signerfile);
653             if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
654                 goto end;
655             if (keyfile == NULL)
656                 keyfile = signerfile;
657             sk_OPENSSL_STRING_push(skkeys, keyfile);
658         }
659         if (sksigners == NULL) {
660             BIO_printf(bio_err, "No signer certificate specified\n");
661             goto opthelp;
662         }
663         signerfile = NULL;
664         keyfile = NULL;
665     } else if (operation == SMIME_DECRYPT) {
666         if (recipfile == NULL && keyfile == NULL
667             && secret_key == NULL && pwri_pass == NULL) {
668             BIO_printf(bio_err,
669                        "No recipient certificate or key specified\n");
670             goto opthelp;
671         }
672     } else if (operation == SMIME_ENCRYPT) {
673         if (*argv == NULL && secret_key == NULL
674             && pwri_pass == NULL && encerts == NULL) {
675             BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
676             goto opthelp;
677         }
678     } else if (!operation) {
679         BIO_printf(bio_err, "No operation option (-encrypt|-decrypt|-sign|-verify|...) specified.\n");
680         goto opthelp;
681     }
682
683     if (!app_passwd(passinarg, NULL, &passin, NULL)) {
684         BIO_printf(bio_err, "Error getting password\n");
685         goto end;
686     }
687
688     ret = 2;
689
690     if (!(operation & SMIME_SIGNERS))
691         flags &= ~CMS_DETACHED;
692
693     if (!(operation & SMIME_OP))
694         if (flags & CMS_BINARY)
695             outformat = FORMAT_BINARY;
696
697     if (!(operation & SMIME_IP))
698         if (flags & CMS_BINARY)
699             informat = FORMAT_BINARY;
700
701     if (operation == SMIME_ENCRYPT) {
702         if (!cipher) {
703 # ifndef OPENSSL_NO_DES
704             cipher = EVP_des_ede3_cbc();
705 # else
706             BIO_printf(bio_err, "No cipher selected\n");
707             goto end;
708 # endif
709         }
710
711         if (secret_key && !secret_keyid) {
712             BIO_printf(bio_err, "No secret key id\n");
713             goto end;
714         }
715
716         if (*argv && encerts == NULL)
717             if ((encerts = sk_X509_new_null()) == NULL)
718                 goto end;
719         while (*argv) {
720             if ((cert = load_cert(*argv, FORMAT_PEM,
721                                   "recipient certificate file")) == NULL)
722                 goto end;
723             sk_X509_push(encerts, cert);
724             cert = NULL;
725             argv++;
726         }
727     }
728
729     if (certfile != NULL) {
730         if (!load_certs(certfile, &other, FORMAT_PEM, NULL,
731                         "certificate file")) {
732             ERR_print_errors(bio_err);
733             goto end;
734         }
735     }
736
737     if (recipfile != NULL && (operation == SMIME_DECRYPT)) {
738         if ((recip = load_cert(recipfile, FORMAT_PEM,
739                                "recipient certificate file")) == NULL) {
740             ERR_print_errors(bio_err);
741             goto end;
742         }
743     }
744
745     if (operation == SMIME_SIGN_RECEIPT) {
746         if ((signer = load_cert(signerfile, FORMAT_PEM,
747                                 "receipt signer certificate file")) == NULL) {
748             ERR_print_errors(bio_err);
749             goto end;
750         }
751     }
752
753     if (operation == SMIME_DECRYPT) {
754         if (keyfile == NULL)
755             keyfile = recipfile;
756     } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) {
757         if (keyfile == NULL)
758             keyfile = signerfile;
759     } else {
760         keyfile = NULL;
761     }
762
763     if (keyfile != NULL) {
764         key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
765         if (key == NULL)
766             goto end;
767     }
768
769     in = bio_open_default(infile, 'r', informat);
770     if (in == NULL)
771         goto end;
772
773     if (operation & SMIME_IP) {
774         if (informat == FORMAT_SMIME) {
775             cms = SMIME_read_CMS(in, &indata);
776         } else if (informat == FORMAT_PEM) {
777             cms = PEM_read_bio_CMS(in, NULL, NULL, NULL);
778         } else if (informat == FORMAT_ASN1) {
779             cms = d2i_CMS_bio(in, NULL);
780         } else {
781             BIO_printf(bio_err, "Bad input format for CMS file\n");
782             goto end;
783         }
784
785         if (cms == NULL) {
786             BIO_printf(bio_err, "Error reading S/MIME message\n");
787             goto end;
788         }
789         if (contfile != NULL) {
790             BIO_free(indata);
791             if ((indata = BIO_new_file(contfile, "rb")) == NULL) {
792                 BIO_printf(bio_err, "Can't read content file %s\n", contfile);
793                 goto end;
794             }
795         }
796         if (certsoutfile != NULL) {
797             STACK_OF(X509) *allcerts;
798             allcerts = CMS_get1_certs(cms);
799             if (!save_certs(certsoutfile, allcerts)) {
800                 BIO_printf(bio_err,
801                            "Error writing certs to %s\n", certsoutfile);
802                 ret = 5;
803                 goto end;
804             }
805             sk_X509_pop_free(allcerts, X509_free);
806         }
807     }
808
809     if (rctfile != NULL) {
810         char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r";
811         if ((rctin = BIO_new_file(rctfile, rctmode)) == NULL) {
812             BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile);
813             goto end;
814         }
815
816         if (rctformat == FORMAT_SMIME) {
817             rcms = SMIME_read_CMS(rctin, NULL);
818         } else if (rctformat == FORMAT_PEM) {
819             rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL);
820         } else if (rctformat == FORMAT_ASN1) {
821             rcms = d2i_CMS_bio(rctin, NULL);
822         } else {
823             BIO_printf(bio_err, "Bad input format for receipt\n");
824             goto end;
825         }
826
827         if (rcms == NULL) {
828             BIO_printf(bio_err, "Error reading receipt\n");
829             goto end;
830         }
831     }
832
833     out = bio_open_default(outfile, 'w', outformat);
834     if (out == NULL)
835         goto end;
836
837     if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) {
838         if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
839                                   CAstore, noCAstore)) == NULL)
840             goto end;
841         X509_STORE_set_verify_cb(store, cms_cb);
842         if (vpmtouched)
843             X509_STORE_set1_param(store, vpm);
844     }
845
846     ret = 3;
847
848     if (operation == SMIME_DATA_CREATE) {
849         cms = CMS_data_create(in, flags);
850     } else if (operation == SMIME_DIGEST_CREATE) {
851         cms = CMS_digest_create(in, sign_md, flags);
852     } else if (operation == SMIME_COMPRESS) {
853         cms = CMS_compress(in, -1, flags);
854     } else if (operation == SMIME_ENCRYPT) {
855         int i;
856         flags |= CMS_PARTIAL;
857         cms = CMS_encrypt(NULL, in, cipher, flags);
858         if (cms == NULL)
859             goto end;
860         for (i = 0; i < sk_X509_num(encerts); i++) {
861             CMS_RecipientInfo *ri;
862             cms_key_param *kparam;
863             int tflags = flags;
864             X509 *x = sk_X509_value(encerts, i);
865             for (kparam = key_first; kparam; kparam = kparam->next) {
866                 if (kparam->idx == i) {
867                     tflags |= CMS_KEY_PARAM;
868                     break;
869                 }
870             }
871             ri = CMS_add1_recipient_cert(cms, x, tflags);
872             if (ri == NULL)
873                 goto end;
874             if (kparam != NULL) {
875                 EVP_PKEY_CTX *pctx;
876                 pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
877                 if (!cms_set_pkey_param(pctx, kparam->param))
878                     goto end;
879             }
880             if (CMS_RecipientInfo_type(ri) == CMS_RECIPINFO_AGREE
881                 && wrap_cipher) {
882                 EVP_CIPHER_CTX *wctx;
883                 wctx = CMS_RecipientInfo_kari_get0_ctx(ri);
884                 EVP_EncryptInit_ex(wctx, wrap_cipher, NULL, NULL, NULL);
885             }
886         }
887
888         if (secret_key != NULL) {
889             if (!CMS_add0_recipient_key(cms, NID_undef,
890                                         secret_key, secret_keylen,
891                                         secret_keyid, secret_keyidlen,
892                                         NULL, NULL, NULL))
893                 goto end;
894             /* NULL these because call absorbs them */
895             secret_key = NULL;
896             secret_keyid = NULL;
897         }
898         if (pwri_pass != NULL) {
899             pwri_tmp = (unsigned char *)OPENSSL_strdup((char *)pwri_pass);
900             if (pwri_tmp == NULL)
901                 goto end;
902             if (CMS_add0_recipient_password(cms,
903                                             -1, NID_undef, NID_undef,
904                                             pwri_tmp, -1, NULL) == NULL)
905                 goto end;
906             pwri_tmp = NULL;
907         }
908         if (!(flags & CMS_STREAM)) {
909             if (!CMS_final(cms, in, NULL, flags))
910                 goto end;
911         }
912     } else if (operation == SMIME_ENCRYPTED_ENCRYPT) {
913         cms = CMS_EncryptedData_encrypt(in, cipher,
914                                         secret_key, secret_keylen, flags);
915
916     } else if (operation == SMIME_SIGN_RECEIPT) {
917         CMS_ContentInfo *srcms = NULL;
918         STACK_OF(CMS_SignerInfo) *sis;
919         CMS_SignerInfo *si;
920         sis = CMS_get0_SignerInfos(cms);
921         if (sis == NULL)
922             goto end;
923         si = sk_CMS_SignerInfo_value(sis, 0);
924         srcms = CMS_sign_receipt(si, signer, key, other, flags);
925         if (srcms == NULL)
926             goto end;
927         CMS_ContentInfo_free(cms);
928         cms = srcms;
929     } else if (operation & SMIME_SIGNERS) {
930         int i;
931         /*
932          * If detached data content we enable streaming if S/MIME output
933          * format.
934          */
935         if (operation == SMIME_SIGN) {
936
937             if (flags & CMS_DETACHED) {
938                 if (outformat == FORMAT_SMIME)
939                     flags |= CMS_STREAM;
940             }
941             flags |= CMS_PARTIAL;
942             cms = CMS_sign(NULL, NULL, other, in, flags);
943             if (cms == NULL)
944                 goto end;
945             if (econtent_type != NULL)
946                 CMS_set1_eContentType(cms, econtent_type);
947
948             if (rr_to != NULL) {
949                 rr = make_receipt_request(rr_to, rr_allorfirst, rr_from);
950                 if (rr == NULL) {
951                     BIO_puts(bio_err,
952                              "Signed Receipt Request Creation Error\n");
953                     goto end;
954                 }
955             }
956         } else {
957             flags |= CMS_REUSE_DIGEST;
958         }
959         for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
960             CMS_SignerInfo *si;
961             cms_key_param *kparam;
962             int tflags = flags;
963             signerfile = sk_OPENSSL_STRING_value(sksigners, i);
964             keyfile = sk_OPENSSL_STRING_value(skkeys, i);
965
966             signer = load_cert(signerfile, FORMAT_PEM, "signer certificate");
967             if (signer == NULL) {
968                 ret = 2;
969                 goto end;
970             }
971             key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
972             if (key == NULL) {
973                 ret = 2;
974                 goto end;
975             }
976             for (kparam = key_first; kparam; kparam = kparam->next) {
977                 if (kparam->idx == i) {
978                     tflags |= CMS_KEY_PARAM;
979                     break;
980                 }
981             }
982             si = CMS_add1_signer(cms, signer, key, sign_md, tflags);
983             if (si == NULL)
984                 goto end;
985             if (kparam != NULL) {
986                 EVP_PKEY_CTX *pctx;
987                 pctx = CMS_SignerInfo_get0_pkey_ctx(si);
988                 if (!cms_set_pkey_param(pctx, kparam->param))
989                     goto end;
990             }
991             if (rr != NULL && !CMS_add1_ReceiptRequest(si, rr))
992                 goto end;
993             X509_free(signer);
994             signer = NULL;
995             EVP_PKEY_free(key);
996             key = NULL;
997         }
998         /* If not streaming or resigning finalize structure */
999         if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM)) {
1000             if (!CMS_final(cms, in, NULL, flags))
1001                 goto end;
1002         }
1003     }
1004
1005     if (cms == NULL) {
1006         BIO_printf(bio_err, "Error creating CMS structure\n");
1007         goto end;
1008     }
1009
1010     ret = 4;
1011     if (operation == SMIME_DECRYPT) {
1012         if (flags & CMS_DEBUG_DECRYPT)
1013             CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags);
1014
1015         if (secret_key != NULL) {
1016             if (!CMS_decrypt_set1_key(cms,
1017                                       secret_key, secret_keylen,
1018                                       secret_keyid, secret_keyidlen)) {
1019                 BIO_puts(bio_err, "Error decrypting CMS using secret key\n");
1020                 goto end;
1021             }
1022         }
1023
1024         if (key != NULL) {
1025             if (!CMS_decrypt_set1_pkey(cms, key, recip)) {
1026                 BIO_puts(bio_err, "Error decrypting CMS using private key\n");
1027                 goto end;
1028             }
1029         }
1030
1031         if (pwri_pass != NULL) {
1032             if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) {
1033                 BIO_puts(bio_err, "Error decrypting CMS using password\n");
1034                 goto end;
1035             }
1036         }
1037
1038         if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) {
1039             BIO_printf(bio_err, "Error decrypting CMS structure\n");
1040             goto end;
1041         }
1042     } else if (operation == SMIME_DATAOUT) {
1043         if (!CMS_data(cms, out, flags))
1044             goto end;
1045     } else if (operation == SMIME_UNCOMPRESS) {
1046         if (!CMS_uncompress(cms, indata, out, flags))
1047             goto end;
1048     } else if (operation == SMIME_DIGEST_VERIFY) {
1049         if (CMS_digest_verify(cms, indata, out, flags) > 0) {
1050             BIO_printf(bio_err, "Verification successful\n");
1051         } else {
1052             BIO_printf(bio_err, "Verification failure\n");
1053             goto end;
1054         }
1055     } else if (operation == SMIME_ENCRYPTED_DECRYPT) {
1056         if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen,
1057                                        indata, out, flags))
1058             goto end;
1059     } else if (operation == SMIME_VERIFY) {
1060         if (CMS_verify(cms, other, store, indata, out, flags) > 0) {
1061             BIO_printf(bio_err, "Verification successful\n");
1062         } else {
1063             BIO_printf(bio_err, "Verification failure\n");
1064             if (verify_retcode)
1065                 ret = verify_err + 32;
1066             goto end;
1067         }
1068         if (signerfile != NULL) {
1069             STACK_OF(X509) *signers;
1070             signers = CMS_get0_signers(cms);
1071             if (!save_certs(signerfile, signers)) {
1072                 BIO_printf(bio_err,
1073                            "Error writing signers to %s\n", signerfile);
1074                 ret = 5;
1075                 goto end;
1076             }
1077             sk_X509_free(signers);
1078         }
1079         if (rr_print)
1080             receipt_request_print(cms);
1081
1082     } else if (operation == SMIME_VERIFY_RECEIPT) {
1083         if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0) {
1084             BIO_printf(bio_err, "Verification successful\n");
1085         } else {
1086             BIO_printf(bio_err, "Verification failure\n");
1087             goto end;
1088         }
1089     } else {
1090         if (noout) {
1091             if (print)
1092                 CMS_ContentInfo_print_ctx(out, cms, 0, NULL);
1093         } else if (outformat == FORMAT_SMIME) {
1094             if (to)
1095                 BIO_printf(out, "To: %s%s", to, mime_eol);
1096             if (from)
1097                 BIO_printf(out, "From: %s%s", from, mime_eol);
1098             if (subject)
1099                 BIO_printf(out, "Subject: %s%s", subject, mime_eol);
1100             if (operation == SMIME_RESIGN)
1101                 ret = SMIME_write_CMS(out, cms, indata, flags);
1102             else
1103                 ret = SMIME_write_CMS(out, cms, in, flags);
1104         } else if (outformat == FORMAT_PEM) {
1105             ret = PEM_write_bio_CMS_stream(out, cms, in, flags);
1106         } else if (outformat == FORMAT_ASN1) {
1107             ret = i2d_CMS_bio_stream(out, cms, in, flags);
1108         } else {
1109             BIO_printf(bio_err, "Bad output format for CMS file\n");
1110             goto end;
1111         }
1112         if (ret <= 0) {
1113             ret = 6;
1114             goto end;
1115         }
1116     }
1117     ret = 0;
1118  end:
1119     if (ret)
1120         ERR_print_errors(bio_err);
1121     sk_X509_pop_free(encerts, X509_free);
1122     sk_X509_pop_free(other, X509_free);
1123     X509_VERIFY_PARAM_free(vpm);
1124     sk_OPENSSL_STRING_free(sksigners);
1125     sk_OPENSSL_STRING_free(skkeys);
1126     OPENSSL_free(secret_key);
1127     OPENSSL_free(secret_keyid);
1128     OPENSSL_free(pwri_tmp);
1129     ASN1_OBJECT_free(econtent_type);
1130     CMS_ReceiptRequest_free(rr);
1131     sk_OPENSSL_STRING_free(rr_to);
1132     sk_OPENSSL_STRING_free(rr_from);
1133     for (key_param = key_first; key_param;) {
1134         cms_key_param *tparam;
1135         sk_OPENSSL_STRING_free(key_param->param);
1136         tparam = key_param->next;
1137         OPENSSL_free(key_param);
1138         key_param = tparam;
1139     }
1140     X509_STORE_free(store);
1141     X509_free(cert);
1142     X509_free(recip);
1143     X509_free(signer);
1144     EVP_PKEY_free(key);
1145     CMS_ContentInfo_free(cms);
1146     CMS_ContentInfo_free(rcms);
1147     release_engine(e);
1148     BIO_free(rctin);
1149     BIO_free(in);
1150     BIO_free(indata);
1151     BIO_free_all(out);
1152     OPENSSL_free(passin);
1153     return ret;
1154 }
1155
1156 static int save_certs(char *signerfile, STACK_OF(X509) *signers)
1157 {
1158     int i;
1159     BIO *tmp;
1160     if (signerfile == NULL)
1161         return 1;
1162     tmp = BIO_new_file(signerfile, "w");
1163     if (tmp == NULL)
1164         return 0;
1165     for (i = 0; i < sk_X509_num(signers); i++)
1166         PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
1167     BIO_free(tmp);
1168     return 1;
1169 }
1170
1171 /* Minimal callback just to output policy info (if any) */
1172
1173 static int cms_cb(int ok, X509_STORE_CTX *ctx)
1174 {
1175     int error;
1176
1177     error = X509_STORE_CTX_get_error(ctx);
1178
1179     verify_err = error;
1180
1181     if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
1182         && ((error != X509_V_OK) || (ok != 2)))
1183         return ok;
1184
1185     policies_print(ctx);
1186
1187     return ok;
1188
1189 }
1190
1191 static void gnames_stack_print(STACK_OF(GENERAL_NAMES) *gns)
1192 {
1193     STACK_OF(GENERAL_NAME) *gens;
1194     GENERAL_NAME *gen;
1195     int i, j;
1196
1197     for (i = 0; i < sk_GENERAL_NAMES_num(gns); i++) {
1198         gens = sk_GENERAL_NAMES_value(gns, i);
1199         for (j = 0; j < sk_GENERAL_NAME_num(gens); j++) {
1200             gen = sk_GENERAL_NAME_value(gens, j);
1201             BIO_puts(bio_err, "    ");
1202             GENERAL_NAME_print(bio_err, gen);
1203             BIO_puts(bio_err, "\n");
1204         }
1205     }
1206     return;
1207 }
1208
1209 static void receipt_request_print(CMS_ContentInfo *cms)
1210 {
1211     STACK_OF(CMS_SignerInfo) *sis;
1212     CMS_SignerInfo *si;
1213     CMS_ReceiptRequest *rr;
1214     int allorfirst;
1215     STACK_OF(GENERAL_NAMES) *rto, *rlist;
1216     ASN1_STRING *scid;
1217     int i, rv;
1218     sis = CMS_get0_SignerInfos(cms);
1219     for (i = 0; i < sk_CMS_SignerInfo_num(sis); i++) {
1220         si = sk_CMS_SignerInfo_value(sis, i);
1221         rv = CMS_get1_ReceiptRequest(si, &rr);
1222         BIO_printf(bio_err, "Signer %d:\n", i + 1);
1223         if (rv == 0) {
1224             BIO_puts(bio_err, "  No Receipt Request\n");
1225         } else if (rv < 0) {
1226             BIO_puts(bio_err, "  Receipt Request Parse Error\n");
1227             ERR_print_errors(bio_err);
1228         } else {
1229             const char *id;
1230             int idlen;
1231             CMS_ReceiptRequest_get0_values(rr, &scid, &allorfirst,
1232                                            &rlist, &rto);
1233             BIO_puts(bio_err, "  Signed Content ID:\n");
1234             idlen = ASN1_STRING_length(scid);
1235             id = (const char *)ASN1_STRING_get0_data(scid);
1236             BIO_dump_indent(bio_err, id, idlen, 4);
1237             BIO_puts(bio_err, "  Receipts From");
1238             if (rlist != NULL) {
1239                 BIO_puts(bio_err, " List:\n");
1240                 gnames_stack_print(rlist);
1241             } else if (allorfirst == 1) {
1242                 BIO_puts(bio_err, ": First Tier\n");
1243             } else if (allorfirst == 0) {
1244                 BIO_puts(bio_err, ": All\n");
1245             } else {
1246                 BIO_printf(bio_err, " Unknown (%d)\n", allorfirst);
1247             }
1248             BIO_puts(bio_err, "  Receipts To:\n");
1249             gnames_stack_print(rto);
1250         }
1251         CMS_ReceiptRequest_free(rr);
1252     }
1253 }
1254
1255 static STACK_OF(GENERAL_NAMES) *make_names_stack(STACK_OF(OPENSSL_STRING) *ns)
1256 {
1257     int i;
1258     STACK_OF(GENERAL_NAMES) *ret;
1259     GENERAL_NAMES *gens = NULL;
1260     GENERAL_NAME *gen = NULL;
1261     ret = sk_GENERAL_NAMES_new_null();
1262     if (ret == NULL)
1263         goto err;
1264     for (i = 0; i < sk_OPENSSL_STRING_num(ns); i++) {
1265         char *str = sk_OPENSSL_STRING_value(ns, i);
1266         gen = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_EMAIL, str, 0);
1267         if (gen == NULL)
1268             goto err;
1269         gens = GENERAL_NAMES_new();
1270         if (gens == NULL)
1271             goto err;
1272         if (!sk_GENERAL_NAME_push(gens, gen))
1273             goto err;
1274         gen = NULL;
1275         if (!sk_GENERAL_NAMES_push(ret, gens))
1276             goto err;
1277         gens = NULL;
1278     }
1279
1280     return ret;
1281
1282  err:
1283     sk_GENERAL_NAMES_pop_free(ret, GENERAL_NAMES_free);
1284     GENERAL_NAMES_free(gens);
1285     GENERAL_NAME_free(gen);
1286     return NULL;
1287 }
1288
1289 static CMS_ReceiptRequest *make_receipt_request(STACK_OF(OPENSSL_STRING)
1290                                                 *rr_to, int rr_allorfirst, STACK_OF(OPENSSL_STRING)
1291                                                 *rr_from)
1292 {
1293     STACK_OF(GENERAL_NAMES) *rct_to = NULL, *rct_from = NULL;
1294     CMS_ReceiptRequest *rr;
1295     rct_to = make_names_stack(rr_to);
1296     if (rct_to == NULL)
1297         goto err;
1298     if (rr_from != NULL) {
1299         rct_from = make_names_stack(rr_from);
1300         if (rct_from == NULL)
1301             goto err;
1302     } else {
1303         rct_from = NULL;
1304     }
1305     rr = CMS_ReceiptRequest_create0(NULL, -1, rr_allorfirst, rct_from,
1306                                     rct_to);
1307     return rr;
1308  err:
1309     sk_GENERAL_NAMES_pop_free(rct_to, GENERAL_NAMES_free);
1310     return NULL;
1311 }
1312
1313 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
1314                               STACK_OF(OPENSSL_STRING) *param)
1315 {
1316     char *keyopt;
1317     int i;
1318     if (sk_OPENSSL_STRING_num(param) <= 0)
1319         return 1;
1320     for (i = 0; i < sk_OPENSSL_STRING_num(param); i++) {
1321         keyopt = sk_OPENSSL_STRING_value(param, i);
1322         if (pkey_ctrl_string(pctx, keyopt) <= 0) {
1323             BIO_printf(bio_err, "parameter error \"%s\"\n", keyopt);
1324             ERR_print_errors(bio_err);
1325             return 0;
1326         }
1327     }
1328     return 1;
1329 }
1330
1331 #endif