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