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