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