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