Code style: space after 'if'
[openssl.git] / apps / cms.c
1 /* apps/cms.c */
2 /*
3  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
4  * project.
5  */
6 /* ====================================================================
7  * Copyright (c) 2008 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    licensing@OpenSSL.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  */
54
55 /* CMS utility function */
56
57 #include <stdio.h>
58 #include <string.h>
59 #include "apps.h"
60
61 #ifndef OPENSSL_NO_CMS
62
63 # include <openssl/crypto.h>
64 # include <openssl/pem.h>
65 # include <openssl/err.h>
66 # include <openssl/x509_vfy.h>
67 # include <openssl/x509v3.h>
68 # include <openssl/cms.h>
69
70 # undef PROG
71 # define PROG cms_main
72 static int save_certs(char *signerfile, STACK_OF(X509) *signers);
73 static int cms_cb(int ok, X509_STORE_CTX *ctx);
74 static void receipt_request_print(BIO *out, CMS_ContentInfo *cms);
75 static CMS_ReceiptRequest *make_receipt_request(STACK_OF(OPENSSL_STRING)
76                                                 *rr_to, int rr_allorfirst, STACK_OF(OPENSSL_STRING)
77                                                 *rr_from);
78 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
79                               STACK_OF(OPENSSL_STRING) *param);
80
81 # define SMIME_OP        0x10
82 # define SMIME_IP        0x20
83 # define SMIME_SIGNERS   0x40
84 # define SMIME_ENCRYPT           (1 | SMIME_OP)
85 # define SMIME_DECRYPT           (2 | SMIME_IP)
86 # define SMIME_SIGN              (3 | SMIME_OP | SMIME_SIGNERS)
87 # define SMIME_VERIFY            (4 | SMIME_IP)
88 # define SMIME_CMSOUT            (5 | SMIME_IP | SMIME_OP)
89 # define SMIME_RESIGN            (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
90 # define SMIME_DATAOUT           (7 | SMIME_IP)
91 # define SMIME_DATA_CREATE       (8 | SMIME_OP)
92 # define SMIME_DIGEST_VERIFY     (9 | SMIME_IP)
93 # define SMIME_DIGEST_CREATE     (10 | SMIME_OP)
94 # define SMIME_UNCOMPRESS        (11 | SMIME_IP)
95 # define SMIME_COMPRESS          (12 | SMIME_OP)
96 # define SMIME_ENCRYPTED_DECRYPT (13 | SMIME_IP)
97 # define SMIME_ENCRYPTED_ENCRYPT (14 | SMIME_OP)
98 # define SMIME_SIGN_RECEIPT      (15 | SMIME_IP | SMIME_OP)
99 # define SMIME_VERIFY_RECEIPT    (16 | SMIME_IP)
100
101 int verify_err = 0;
102
103 typedef struct cms_key_param_st cms_key_param;
104
105 struct cms_key_param_st {
106     int idx;
107     STACK_OF(OPENSSL_STRING) *param;
108     cms_key_param *next;
109 };
110
111 int MAIN(int, char **);
112
113 int MAIN(int argc, char **argv)
114 {
115     ENGINE *e = NULL;
116     int operation = 0;
117     int ret = 0;
118     char **args;
119     const char *inmode = "r", *outmode = "w";
120     char *infile = NULL, *outfile = NULL, *rctfile = NULL;
121     char *signerfile = NULL, *recipfile = NULL;
122     STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
123     char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
124     char *certsoutfile = NULL;
125     const EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL;
126     CMS_ContentInfo *cms = NULL, *rcms = NULL;
127     X509_STORE *store = NULL;
128     X509 *cert = NULL, *recip = NULL, *signer = NULL;
129     EVP_PKEY *key = NULL;
130     STACK_OF(X509) *encerts = NULL, *other = NULL;
131     BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL;
132     int badarg = 0;
133     int flags = CMS_DETACHED, noout = 0, print = 0;
134     int verify_retcode = 0;
135     int rr_print = 0, rr_allorfirst = -1;
136     STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL;
137     CMS_ReceiptRequest *rr = NULL;
138     char *to = NULL, *from = NULL, *subject = NULL;
139     char *CAfile = NULL, *CApath = NULL;
140     char *passargin = NULL, *passin = NULL;
141     char *inrand = NULL;
142     int need_rand = 0;
143     const EVP_MD *sign_md = NULL;
144     int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
145     int rctformat = FORMAT_SMIME, keyform = FORMAT_PEM;
146 # ifndef OPENSSL_NO_ENGINE
147     char *engine = NULL;
148 # endif
149     unsigned char *secret_key = NULL, *secret_keyid = NULL;
150     unsigned char *pwri_pass = NULL, *pwri_tmp = NULL;
151     size_t secret_keylen = 0, secret_keyidlen = 0;
152
153     cms_key_param *key_first = NULL, *key_param = NULL;
154
155     ASN1_OBJECT *econtent_type = NULL;
156
157     X509_VERIFY_PARAM *vpm = NULL;
158
159     args = argv + 1;
160     ret = 1;
161
162     apps_startup();
163
164     if (bio_err == NULL) {
165         if ((bio_err = BIO_new(BIO_s_file())) != NULL)
166             BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
167     }
168
169     if (!load_config(bio_err, NULL))
170         goto end;
171
172     while (!badarg && *args && *args[0] == '-') {
173         if (!strcmp(*args, "-encrypt"))
174             operation = SMIME_ENCRYPT;
175         else if (!strcmp(*args, "-decrypt"))
176             operation = SMIME_DECRYPT;
177         else if (!strcmp(*args, "-sign"))
178             operation = SMIME_SIGN;
179         else if (!strcmp(*args, "-sign_receipt"))
180             operation = SMIME_SIGN_RECEIPT;
181         else if (!strcmp(*args, "-resign"))
182             operation = SMIME_RESIGN;
183         else if (!strcmp(*args, "-verify"))
184             operation = SMIME_VERIFY;
185         else if (!strcmp(*args, "-verify_retcode"))
186             verify_retcode = 1;
187         else if (!strcmp(*args, "-verify_receipt")) {
188             operation = SMIME_VERIFY_RECEIPT;
189             if (!args[1])
190                 goto argerr;
191             args++;
192             rctfile = *args;
193         } else if (!strcmp(*args, "-cmsout"))
194             operation = SMIME_CMSOUT;
195         else if (!strcmp(*args, "-data_out"))
196             operation = SMIME_DATAOUT;
197         else if (!strcmp(*args, "-data_create"))
198             operation = SMIME_DATA_CREATE;
199         else if (!strcmp(*args, "-digest_verify"))
200             operation = SMIME_DIGEST_VERIFY;
201         else if (!strcmp(*args, "-digest_create"))
202             operation = SMIME_DIGEST_CREATE;
203         else if (!strcmp(*args, "-compress"))
204             operation = SMIME_COMPRESS;
205         else if (!strcmp(*args, "-uncompress"))
206             operation = SMIME_UNCOMPRESS;
207         else if (!strcmp(*args, "-EncryptedData_decrypt"))
208             operation = SMIME_ENCRYPTED_DECRYPT;
209         else if (!strcmp(*args, "-EncryptedData_encrypt"))
210             operation = SMIME_ENCRYPTED_ENCRYPT;
211 # ifndef OPENSSL_NO_DES
212         else if (!strcmp(*args, "-des3"))
213             cipher = EVP_des_ede3_cbc();
214         else if (!strcmp(*args, "-des"))
215             cipher = EVP_des_cbc();
216         else if (!strcmp(*args, "-des3-wrap"))
217             wrap_cipher = EVP_des_ede3_wrap();
218 # endif
219 # ifndef OPENSSL_NO_SEED
220         else if (!strcmp(*args, "-seed"))
221             cipher = EVP_seed_cbc();
222 # endif
223 # ifndef OPENSSL_NO_RC2
224         else if (!strcmp(*args, "-rc2-40"))
225             cipher = EVP_rc2_40_cbc();
226         else if (!strcmp(*args, "-rc2-128"))
227             cipher = EVP_rc2_cbc();
228         else if (!strcmp(*args, "-rc2-64"))
229             cipher = EVP_rc2_64_cbc();
230 # endif
231 # ifndef OPENSSL_NO_AES
232         else if (!strcmp(*args, "-aes128"))
233             cipher = EVP_aes_128_cbc();
234         else if (!strcmp(*args, "-aes192"))
235             cipher = EVP_aes_192_cbc();
236         else if (!strcmp(*args, "-aes256"))
237             cipher = EVP_aes_256_cbc();
238         else if (!strcmp(*args, "-aes128-wrap"))
239             wrap_cipher = EVP_aes_128_wrap();
240         else if (!strcmp(*args, "-aes192-wrap"))
241             wrap_cipher = EVP_aes_192_wrap();
242         else if (!strcmp(*args, "-aes256-wrap"))
243             wrap_cipher = EVP_aes_256_wrap();
244 # endif
245 # ifndef OPENSSL_NO_CAMELLIA
246         else if (!strcmp(*args, "-camellia128"))
247             cipher = EVP_camellia_128_cbc();
248         else if (!strcmp(*args, "-camellia192"))
249             cipher = EVP_camellia_192_cbc();
250         else if (!strcmp(*args, "-camellia256"))
251             cipher = EVP_camellia_256_cbc();
252 # endif
253         else if (!strcmp(*args, "-debug_decrypt"))
254             flags |= CMS_DEBUG_DECRYPT;
255         else if (!strcmp(*args, "-text"))
256             flags |= CMS_TEXT;
257         else if (!strcmp(*args, "-asciicrlf"))
258             flags |= CMS_ASCIICRLF;
259         else if (!strcmp(*args, "-nointern"))
260             flags |= CMS_NOINTERN;
261         else if (!strcmp(*args, "-noverify")
262                  || !strcmp(*args, "-no_signer_cert_verify"))
263             flags |= CMS_NO_SIGNER_CERT_VERIFY;
264         else if (!strcmp(*args, "-nocerts"))
265             flags |= CMS_NOCERTS;
266         else if (!strcmp(*args, "-noattr"))
267             flags |= CMS_NOATTR;
268         else if (!strcmp(*args, "-nodetach"))
269             flags &= ~CMS_DETACHED;
270         else if (!strcmp(*args, "-nosmimecap"))
271             flags |= CMS_NOSMIMECAP;
272         else if (!strcmp(*args, "-binary"))
273             flags |= CMS_BINARY;
274         else if (!strcmp(*args, "-keyid"))
275             flags |= CMS_USE_KEYID;
276         else if (!strcmp(*args, "-nosigs"))
277             flags |= CMS_NOSIGS;
278         else if (!strcmp(*args, "-no_content_verify"))
279             flags |= CMS_NO_CONTENT_VERIFY;
280         else if (!strcmp(*args, "-no_attr_verify"))
281             flags |= CMS_NO_ATTR_VERIFY;
282         else if (!strcmp(*args, "-stream"))
283             flags |= CMS_STREAM;
284         else if (!strcmp(*args, "-indef"))
285             flags |= CMS_STREAM;
286         else if (!strcmp(*args, "-noindef"))
287             flags &= ~CMS_STREAM;
288         else if (!strcmp(*args, "-nooldmime"))
289             flags |= CMS_NOOLDMIMETYPE;
290         else if (!strcmp(*args, "-crlfeol"))
291             flags |= CMS_CRLFEOL;
292         else if (!strcmp(*args, "-noout"))
293             noout = 1;
294         else if (!strcmp(*args, "-receipt_request_print"))
295             rr_print = 1;
296         else if (!strcmp(*args, "-receipt_request_all"))
297             rr_allorfirst = 0;
298         else if (!strcmp(*args, "-receipt_request_first"))
299             rr_allorfirst = 1;
300         else if (!strcmp(*args, "-receipt_request_from")) {
301             if (!args[1])
302                 goto argerr;
303             args++;
304             if (!rr_from)
305                 rr_from = sk_OPENSSL_STRING_new_null();
306             sk_OPENSSL_STRING_push(rr_from, *args);
307         } else if (!strcmp(*args, "-receipt_request_to")) {
308             if (!args[1])
309                 goto argerr;
310             args++;
311             if (!rr_to)
312                 rr_to = sk_OPENSSL_STRING_new_null();
313             sk_OPENSSL_STRING_push(rr_to, *args);
314         } else if (!strcmp(*args, "-print")) {
315             noout = 1;
316             print = 1;
317         } else if (!strcmp(*args, "-secretkey")) {
318             long ltmp;
319             if (!args[1])
320                 goto argerr;
321             args++;
322             secret_key = string_to_hex(*args, &ltmp);
323             if (!secret_key) {
324                 BIO_printf(bio_err, "Invalid key %s\n", *args);
325                 goto argerr;
326             }
327             secret_keylen = (size_t)ltmp;
328         } else if (!strcmp(*args, "-secretkeyid")) {
329             long ltmp;
330             if (!args[1])
331                 goto argerr;
332             args++;
333             secret_keyid = string_to_hex(*args, &ltmp);
334             if (!secret_keyid) {
335                 BIO_printf(bio_err, "Invalid id %s\n", *args);
336                 goto argerr;
337             }
338             secret_keyidlen = (size_t)ltmp;
339         } else if (!strcmp(*args, "-pwri_password")) {
340             if (!args[1])
341                 goto argerr;
342             args++;
343             pwri_pass = (unsigned char *)*args;
344         } else if (!strcmp(*args, "-econtent_type")) {
345             if (!args[1])
346                 goto argerr;
347             args++;
348             econtent_type = OBJ_txt2obj(*args, 0);
349             if (!econtent_type) {
350                 BIO_printf(bio_err, "Invalid OID %s\n", *args);
351                 goto argerr;
352             }
353         } else if (!strcmp(*args, "-rand")) {
354             if (!args[1])
355                 goto argerr;
356             args++;
357             inrand = *args;
358             need_rand = 1;
359         }
360 # ifndef OPENSSL_NO_ENGINE
361         else if (!strcmp(*args, "-engine")) {
362             if (!args[1])
363                 goto argerr;
364             engine = *++args;
365         }
366 # endif
367         else if (!strcmp(*args, "-passin")) {
368             if (!args[1])
369                 goto argerr;
370             passargin = *++args;
371         } else if (!strcmp(*args, "-to")) {
372             if (!args[1])
373                 goto argerr;
374             to = *++args;
375         } else if (!strcmp(*args, "-from")) {
376             if (!args[1])
377                 goto argerr;
378             from = *++args;
379         } else if (!strcmp(*args, "-subject")) {
380             if (!args[1])
381                 goto argerr;
382             subject = *++args;
383         } else if (!strcmp(*args, "-signer")) {
384             if (!args[1])
385                 goto argerr;
386             /* If previous -signer argument add signer to list */
387
388             if (signerfile) {
389                 if (!sksigners)
390                     sksigners = sk_OPENSSL_STRING_new_null();
391                 sk_OPENSSL_STRING_push(sksigners, signerfile);
392                 if (!keyfile)
393                     keyfile = signerfile;
394                 if (!skkeys)
395                     skkeys = sk_OPENSSL_STRING_new_null();
396                 sk_OPENSSL_STRING_push(skkeys, keyfile);
397                 keyfile = NULL;
398             }
399             signerfile = *++args;
400         } else if (!strcmp(*args, "-recip")) {
401             if (!args[1])
402                 goto argerr;
403             if (operation == SMIME_ENCRYPT) {
404                 if (!encerts)
405                     encerts = sk_X509_new_null();
406                 cert = load_cert(bio_err, *++args, FORMAT_PEM,
407                                  NULL, e, "recipient certificate file");
408                 if (!cert)
409                     goto end;
410                 sk_X509_push(encerts, cert);
411                 cert = NULL;
412             } else
413                 recipfile = *++args;
414         } else if (!strcmp(*args, "-certsout")) {
415             if (!args[1])
416                 goto argerr;
417             certsoutfile = *++args;
418         } else if (!strcmp(*args, "-md")) {
419             if (!args[1])
420                 goto argerr;
421             sign_md = EVP_get_digestbyname(*++args);
422             if (sign_md == NULL) {
423                 BIO_printf(bio_err, "Unknown digest %s\n", *args);
424                 goto argerr;
425             }
426         } else if (!strcmp(*args, "-inkey")) {
427             if (!args[1])
428                 goto argerr;
429             /* If previous -inkey arument add signer to list */
430             if (keyfile) {
431                 if (!signerfile) {
432                     BIO_puts(bio_err, "Illegal -inkey without -signer\n");
433                     goto argerr;
434                 }
435                 if (!sksigners)
436                     sksigners = sk_OPENSSL_STRING_new_null();
437                 sk_OPENSSL_STRING_push(sksigners, signerfile);
438                 signerfile = NULL;
439                 if (!skkeys)
440                     skkeys = sk_OPENSSL_STRING_new_null();
441                 sk_OPENSSL_STRING_push(skkeys, keyfile);
442             }
443             keyfile = *++args;
444         } else if (!strcmp(*args, "-keyform")) {
445             if (!args[1])
446                 goto argerr;
447             keyform = str2fmt(*++args);
448         } else if (!strcmp(*args, "-keyopt")) {
449             int keyidx = -1;
450             if (!args[1])
451                 goto argerr;
452             if (operation == SMIME_ENCRYPT) {
453                 if (encerts)
454                     keyidx += sk_X509_num(encerts);
455             } else {
456                 if (keyfile || signerfile)
457                     keyidx++;
458                 if (skkeys)
459                     keyidx += sk_OPENSSL_STRING_num(skkeys);
460             }
461             if (keyidx < 0) {
462                 BIO_printf(bio_err, "No key specified\n");
463                 goto argerr;
464             }
465             if (key_param == NULL || key_param->idx != keyidx) {
466                 cms_key_param *nparam;
467                 nparam = OPENSSL_malloc(sizeof(cms_key_param));
468                 if (!nparam) {
469                     BIO_printf(bio_err, "Out of memory\n");
470                     goto argerr;
471                 }
472                 nparam->idx = keyidx;
473                 nparam->param = sk_OPENSSL_STRING_new_null();
474                 nparam->next = NULL;
475                 if (key_first == NULL)
476                     key_first = nparam;
477                 else
478                     key_param->next = nparam;
479                 key_param = nparam;
480             }
481             sk_OPENSSL_STRING_push(key_param->param, *++args);
482         } else if (!strcmp(*args, "-rctform")) {
483             if (!args[1])
484                 goto argerr;
485             rctformat = str2fmt(*++args);
486         } else if (!strcmp(*args, "-certfile")) {
487             if (!args[1])
488                 goto argerr;
489             certfile = *++args;
490         } else if (!strcmp(*args, "-CAfile")) {
491             if (!args[1])
492                 goto argerr;
493             CAfile = *++args;
494         } else if (!strcmp(*args, "-CApath")) {
495             if (!args[1])
496                 goto argerr;
497             CApath = *++args;
498         } else if (!strcmp(*args, "-in")) {
499             if (!args[1])
500                 goto argerr;
501             infile = *++args;
502         } else if (!strcmp(*args, "-inform")) {
503             if (!args[1])
504                 goto argerr;
505             informat = str2fmt(*++args);
506         } else if (!strcmp(*args, "-outform")) {
507             if (!args[1])
508                 goto argerr;
509             outformat = str2fmt(*++args);
510         } else if (!strcmp(*args, "-out")) {
511             if (!args[1])
512                 goto argerr;
513             outfile = *++args;
514         } else if (!strcmp(*args, "-content")) {
515             if (!args[1])
516                 goto argerr;
517             contfile = *++args;
518         } else if (args_verify(&args, NULL, &badarg, bio_err, &vpm))
519             continue;
520         else if ((cipher = EVP_get_cipherbyname(*args + 1)) == NULL)
521             badarg = 1;
522         args++;
523     }
524
525     if (((rr_allorfirst != -1) || rr_from) && !rr_to) {
526         BIO_puts(bio_err, "No Signed Receipts Recipients\n");
527         goto argerr;
528     }
529
530     if (!(operation & SMIME_SIGNERS) && (rr_to || rr_from)) {
531         BIO_puts(bio_err, "Signed receipts only allowed with -sign\n");
532         goto argerr;
533     }
534     if (!(operation & SMIME_SIGNERS) && (skkeys || sksigners)) {
535         BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
536         goto argerr;
537     }
538
539     if (operation & SMIME_SIGNERS) {
540         if (keyfile && !signerfile) {
541             BIO_puts(bio_err, "Illegal -inkey without -signer\n");
542             goto argerr;
543         }
544         /* Check to see if any final signer needs to be appended */
545         if (signerfile) {
546             if (!sksigners)
547                 sksigners = sk_OPENSSL_STRING_new_null();
548             sk_OPENSSL_STRING_push(sksigners, signerfile);
549             if (!skkeys)
550                 skkeys = sk_OPENSSL_STRING_new_null();
551             if (!keyfile)
552                 keyfile = signerfile;
553             sk_OPENSSL_STRING_push(skkeys, keyfile);
554         }
555         if (!sksigners) {
556             BIO_printf(bio_err, "No signer certificate specified\n");
557             badarg = 1;
558         }
559         signerfile = NULL;
560         keyfile = NULL;
561         need_rand = 1;
562     }
563
564     else if (operation == SMIME_DECRYPT) {
565         if (!recipfile && !keyfile && !secret_key && !pwri_pass) {
566             BIO_printf(bio_err,
567                        "No recipient certificate or key specified\n");
568             badarg = 1;
569         }
570     } else if (operation == SMIME_ENCRYPT) {
571         if (!*args && !secret_key && !pwri_pass && !encerts) {
572             BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
573             badarg = 1;
574         }
575         need_rand = 1;
576     } else if (!operation)
577         badarg = 1;
578
579     if (badarg) {
580  argerr:
581         BIO_printf(bio_err, "Usage cms [options] cert.pem ...\n");
582         BIO_printf(bio_err, "where options are\n");
583         BIO_printf(bio_err, "-encrypt       encrypt message\n");
584         BIO_printf(bio_err, "-decrypt       decrypt encrypted message\n");
585         BIO_printf(bio_err, "-sign          sign message\n");
586         BIO_printf(bio_err, "-verify        verify signed message\n");
587         BIO_printf(bio_err, "-cmsout        output CMS structure\n");
588 # ifndef OPENSSL_NO_DES
589         BIO_printf(bio_err, "-des3          encrypt with triple DES\n");
590         BIO_printf(bio_err, "-des           encrypt with DES\n");
591 # endif
592 # ifndef OPENSSL_NO_SEED
593         BIO_printf(bio_err, "-seed          encrypt with SEED\n");
594 # endif
595 # ifndef OPENSSL_NO_RC2
596         BIO_printf(bio_err, "-rc2-40        encrypt with RC2-40 (default)\n");
597         BIO_printf(bio_err, "-rc2-64        encrypt with RC2-64\n");
598         BIO_printf(bio_err, "-rc2-128       encrypt with RC2-128\n");
599 # endif
600 # ifndef OPENSSL_NO_AES
601         BIO_printf(bio_err, "-aes128, -aes192, -aes256\n");
602         BIO_printf(bio_err,
603                    "               encrypt PEM output with cbc aes\n");
604 # endif
605 # ifndef OPENSSL_NO_CAMELLIA
606         BIO_printf(bio_err, "-camellia128, -camellia192, -camellia256\n");
607         BIO_printf(bio_err,
608                    "               encrypt PEM output with cbc camellia\n");
609 # endif
610         BIO_printf(bio_err,
611                    "-nointern      don't search certificates in message for signer\n");
612         BIO_printf(bio_err,
613                    "-nosigs        don't verify message signature\n");
614         BIO_printf(bio_err,
615                    "-noverify      don't verify signers certificate\n");
616         BIO_printf(bio_err,
617                    "-nocerts       don't include signers certificate when signing\n");
618         BIO_printf(bio_err, "-nodetach      use opaque signing\n");
619         BIO_printf(bio_err,
620                    "-noattr        don't include any signed attributes\n");
621         BIO_printf(bio_err,
622                    "-binary        don't translate message to text\n");
623         BIO_printf(bio_err, "-certfile file other certificates file\n");
624         BIO_printf(bio_err, "-certsout file certificate output file\n");
625         BIO_printf(bio_err, "-signer file   signer certificate file\n");
626         BIO_printf(bio_err,
627                    "-recip  file   recipient certificate file for decryption\n");
628         BIO_printf(bio_err, "-keyid         use subject key identifier\n");
629         BIO_printf(bio_err, "-in file       input file\n");
630         BIO_printf(bio_err,
631                    "-inform arg    input format SMIME (default), PEM or DER\n");
632         BIO_printf(bio_err,
633                    "-inkey file    input private key (if not signer or recipient)\n");
634         BIO_printf(bio_err,
635                    "-keyform arg   input private key format (PEM or ENGINE)\n");
636         BIO_printf(bio_err, "-keyopt nm:v   set public key parameters\n");
637         BIO_printf(bio_err, "-out file      output file\n");
638         BIO_printf(bio_err,
639                    "-outform arg   output format SMIME (default), PEM or DER\n");
640         BIO_printf(bio_err,
641                    "-content file  supply or override content for detached signature\n");
642         BIO_printf(bio_err, "-to addr       to address\n");
643         BIO_printf(bio_err, "-from ad       from address\n");
644         BIO_printf(bio_err, "-subject s     subject\n");
645         BIO_printf(bio_err,
646                    "-text          include or delete text MIME headers\n");
647         BIO_printf(bio_err,
648                    "-CApath dir    trusted certificates directory\n");
649         BIO_printf(bio_err, "-CAfile file   trusted certificates file\n");
650         BIO_printf(bio_err,
651                    "-trusted_first use locally trusted certificates first when building trust chain\n");
652         BIO_printf(bio_err,
653                    "-no_alt_chains only ever use the first certificate chain found\n");
654         BIO_printf(bio_err,
655                    "-crl_check     check revocation status of signer's certificate using CRLs\n");
656         BIO_printf(bio_err,
657                    "-crl_check_all check revocation status of signer's certificate chain using CRLs\n");
658 # ifndef OPENSSL_NO_ENGINE
659         BIO_printf(bio_err,
660                    "-engine e      use engine e, possibly a hardware device.\n");
661 # endif
662         BIO_printf(bio_err, "-passin arg    input file pass phrase source\n");
663         BIO_printf(bio_err, "-rand file%cfile%c...\n", LIST_SEPARATOR_CHAR,
664                    LIST_SEPARATOR_CHAR);
665         BIO_printf(bio_err,
666                    "               load the file (or the files in the directory) into\n");
667         BIO_printf(bio_err, "               the random number generator\n");
668         BIO_printf(bio_err,
669                    "cert.pem       recipient certificate(s) for encryption\n");
670         goto end;
671     }
672 # ifndef OPENSSL_NO_ENGINE
673     e = setup_engine(bio_err, engine, 0);
674 # endif
675
676     if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) {
677         BIO_printf(bio_err, "Error getting password\n");
678         goto end;
679     }
680
681     if (need_rand) {
682         app_RAND_load_file(NULL, bio_err, (inrand != NULL));
683         if (inrand != NULL)
684             BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
685                        app_RAND_load_files(inrand));
686     }
687
688     ret = 2;
689
690     if (!(operation & SMIME_SIGNERS))
691         flags &= ~CMS_DETACHED;
692
693     if (operation & SMIME_OP) {
694         if (outformat == FORMAT_ASN1)
695             outmode = "wb";
696     } else {
697         if (flags & CMS_BINARY)
698             outmode = "wb";
699     }
700
701     if (operation & SMIME_IP) {
702         if (informat == FORMAT_ASN1)
703             inmode = "rb";
704     } else {
705         if (flags & CMS_BINARY)
706             inmode = "rb";
707     }
708
709     if (operation == SMIME_ENCRYPT) {
710         if (!cipher) {
711 # ifndef OPENSSL_NO_DES
712             cipher = EVP_des_ede3_cbc();
713 # else
714             BIO_printf(bio_err, "No cipher selected\n");
715             goto end;
716 # endif
717         }
718
719         if (secret_key && !secret_keyid) {
720             BIO_printf(bio_err, "No secret key id\n");
721             goto end;
722         }
723
724         if (*args && !encerts)
725             encerts = sk_X509_new_null();
726         while (*args) {
727             if (!(cert = load_cert(bio_err, *args, FORMAT_PEM,
728                                    NULL, e, "recipient certificate file")))
729                 goto end;
730             sk_X509_push(encerts, cert);
731             cert = NULL;
732             args++;
733         }
734     }
735
736     if (certfile) {
737         if (!(other = load_certs(bio_err, certfile, FORMAT_PEM, NULL,
738                                  e, "certificate file"))) {
739             ERR_print_errors(bio_err);
740             goto end;
741         }
742     }
743
744     if (recipfile && (operation == SMIME_DECRYPT)) {
745         if (!(recip = load_cert(bio_err, recipfile, FORMAT_PEM, NULL,
746                                 e, "recipient certificate file"))) {
747             ERR_print_errors(bio_err);
748             goto end;
749         }
750     }
751
752     if (operation == SMIME_SIGN_RECEIPT) {
753         if (!(signer = load_cert(bio_err, signerfile, FORMAT_PEM, NULL,
754                                  e, "receipt signer certificate file"))) {
755             ERR_print_errors(bio_err);
756             goto end;
757         }
758     }
759
760     if (operation == SMIME_DECRYPT) {
761         if (!keyfile)
762             keyfile = recipfile;
763     } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) {
764         if (!keyfile)
765             keyfile = signerfile;
766     } else
767         keyfile = NULL;
768
769     if (keyfile) {
770         key = load_key(bio_err, keyfile, keyform, 0, passin, e,
771                        "signing key file");
772         if (!key)
773             goto end;
774     }
775
776     if (infile) {
777         if (!(in = BIO_new_file(infile, inmode))) {
778             BIO_printf(bio_err, "Can't open input file %s\n", infile);
779             goto end;
780         }
781     } else
782         in = BIO_new_fp(stdin, BIO_NOCLOSE);
783
784     if (operation & SMIME_IP) {
785         if (informat == FORMAT_SMIME)
786             cms = SMIME_read_CMS(in, &indata);
787         else if (informat == FORMAT_PEM)
788             cms = PEM_read_bio_CMS(in, NULL, NULL, NULL);
789         else if (informat == FORMAT_ASN1)
790             cms = d2i_CMS_bio(in, NULL);
791         else {
792             BIO_printf(bio_err, "Bad input format for CMS file\n");
793             goto end;
794         }
795
796         if (!cms) {
797             BIO_printf(bio_err, "Error reading S/MIME message\n");
798             goto end;
799         }
800         if (contfile) {
801             BIO_free(indata);
802             if (!(indata = BIO_new_file(contfile, "rb"))) {
803                 BIO_printf(bio_err, "Can't read content file %s\n", contfile);
804                 goto end;
805             }
806         }
807         if (certsoutfile) {
808             STACK_OF(X509) *allcerts;
809             allcerts = CMS_get1_certs(cms);
810             if (!save_certs(certsoutfile, allcerts)) {
811                 BIO_printf(bio_err,
812                            "Error writing certs to %s\n", certsoutfile);
813                 ret = 5;
814                 goto end;
815             }
816             sk_X509_pop_free(allcerts, X509_free);
817         }
818     }
819
820     if (rctfile) {
821         char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r";
822         if (!(rctin = BIO_new_file(rctfile, rctmode))) {
823             BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile);
824             goto end;
825         }
826
827         if (rctformat == FORMAT_SMIME)
828             rcms = SMIME_read_CMS(rctin, NULL);
829         else if (rctformat == FORMAT_PEM)
830             rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL);
831         else if (rctformat == FORMAT_ASN1)
832             rcms = d2i_CMS_bio(rctin, NULL);
833         else {
834             BIO_printf(bio_err, "Bad input format for receipt\n");
835             goto end;
836         }
837
838         if (!rcms) {
839             BIO_printf(bio_err, "Error reading receipt\n");
840             goto end;
841         }
842     }
843
844     if (outfile) {
845         if (!(out = BIO_new_file(outfile, outmode))) {
846             BIO_printf(bio_err, "Can't open output file %s\n", outfile);
847             goto end;
848         }
849     } else {
850         out = BIO_new_fp(stdout, BIO_NOCLOSE);
851 # ifdef OPENSSL_SYS_VMS
852         {
853             BIO *tmpbio = BIO_new(BIO_f_linebuffer());
854             out = BIO_push(tmpbio, out);
855         }
856 # endif
857     }
858
859     if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) {
860         if (!(store = setup_verify(bio_err, CAfile, CApath)))
861             goto end;
862         X509_STORE_set_verify_cb(store, cms_cb);
863         if (vpm)
864             X509_STORE_set1_param(store, vpm);
865     }
866
867     ret = 3;
868
869     if (operation == SMIME_DATA_CREATE) {
870         cms = CMS_data_create(in, flags);
871     } else if (operation == SMIME_DIGEST_CREATE) {
872         cms = CMS_digest_create(in, sign_md, flags);
873     } else if (operation == SMIME_COMPRESS) {
874         cms = CMS_compress(in, -1, flags);
875     } else if (operation == SMIME_ENCRYPT) {
876         int i;
877         flags |= CMS_PARTIAL;
878         cms = CMS_encrypt(NULL, in, cipher, flags);
879         if (!cms)
880             goto end;
881         for (i = 0; i < sk_X509_num(encerts); i++) {
882             CMS_RecipientInfo *ri;
883             cms_key_param *kparam;
884             int tflags = flags;
885             X509 *x = sk_X509_value(encerts, i);
886             for (kparam = key_first; kparam; kparam = kparam->next) {
887                 if (kparam->idx == i) {
888                     tflags |= CMS_KEY_PARAM;
889                     break;
890                 }
891             }
892             ri = CMS_add1_recipient_cert(cms, x, tflags);
893             if (!ri)
894                 goto end;
895             if (kparam) {
896                 EVP_PKEY_CTX *pctx;
897                 pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
898                 if (!cms_set_pkey_param(pctx, kparam->param))
899                     goto end;
900             }
901             if (CMS_RecipientInfo_type(ri) == CMS_RECIPINFO_AGREE
902                 && wrap_cipher) {
903                 EVP_CIPHER_CTX *wctx;
904                 wctx = CMS_RecipientInfo_kari_get0_ctx(ri);
905                 EVP_EncryptInit_ex(wctx, wrap_cipher, NULL, NULL, NULL);
906             }
907         }
908
909         if (secret_key) {
910             if (!CMS_add0_recipient_key(cms, NID_undef,
911                                         secret_key, secret_keylen,
912                                         secret_keyid, secret_keyidlen,
913                                         NULL, NULL, NULL))
914                 goto end;
915             /* NULL these because call absorbs them */
916             secret_key = NULL;
917             secret_keyid = NULL;
918         }
919         if (pwri_pass) {
920             pwri_tmp = (unsigned char *)BUF_strdup((char *)pwri_pass);
921             if (!pwri_tmp)
922                 goto end;
923             if (!CMS_add0_recipient_password(cms,
924                                              -1, NID_undef, NID_undef,
925                                              pwri_tmp, -1, NULL))
926                 goto end;
927             pwri_tmp = NULL;
928         }
929         if (!(flags & CMS_STREAM)) {
930             if (!CMS_final(cms, in, NULL, flags))
931                 goto end;
932         }
933     } else if (operation == SMIME_ENCRYPTED_ENCRYPT) {
934         cms = CMS_EncryptedData_encrypt(in, cipher,
935                                         secret_key, secret_keylen, flags);
936
937     } else if (operation == SMIME_SIGN_RECEIPT) {
938         CMS_ContentInfo *srcms = NULL;
939         STACK_OF(CMS_SignerInfo) *sis;
940         CMS_SignerInfo *si;
941         sis = CMS_get0_SignerInfos(cms);
942         if (!sis)
943             goto end;
944         si = sk_CMS_SignerInfo_value(sis, 0);
945         srcms = CMS_sign_receipt(si, signer, key, other, flags);
946         if (!srcms)
947             goto end;
948         CMS_ContentInfo_free(cms);
949         cms = srcms;
950     } else if (operation & SMIME_SIGNERS) {
951         int i;
952         /*
953          * If detached data content we enable streaming if S/MIME output
954          * format.
955          */
956         if (operation == SMIME_SIGN) {
957
958             if (flags & CMS_DETACHED) {
959                 if (outformat == FORMAT_SMIME)
960                     flags |= CMS_STREAM;
961             }
962             flags |= CMS_PARTIAL;
963             cms = CMS_sign(NULL, NULL, other, in, flags);
964             if (!cms)
965                 goto end;
966             if (econtent_type)
967                 CMS_set1_eContentType(cms, econtent_type);
968
969             if (rr_to) {
970                 rr = make_receipt_request(rr_to, rr_allorfirst, rr_from);
971                 if (!rr) {
972                     BIO_puts(bio_err,
973                              "Signed Receipt Request Creation Error\n");
974                     goto end;
975                 }
976             }
977         } else
978             flags |= CMS_REUSE_DIGEST;
979         for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
980             CMS_SignerInfo *si;
981             cms_key_param *kparam;
982             int tflags = flags;
983             signerfile = sk_OPENSSL_STRING_value(sksigners, i);
984             keyfile = sk_OPENSSL_STRING_value(skkeys, i);
985
986             signer = load_cert(bio_err, signerfile, FORMAT_PEM, NULL,
987                                e, "signer certificate");
988             if (!signer)
989                 goto end;
990             key = load_key(bio_err, keyfile, keyform, 0, passin, e,
991                            "signing key file");
992             if (!key)
993                 goto end;
994             for (kparam = key_first; kparam; kparam = kparam->next) {
995                 if (kparam->idx == i) {
996                     tflags |= CMS_KEY_PARAM;
997                     break;
998                 }
999             }
1000             si = CMS_add1_signer(cms, signer, key, sign_md, tflags);
1001             if (!si)
1002                 goto end;
1003             if (kparam) {
1004                 EVP_PKEY_CTX *pctx;
1005                 pctx = CMS_SignerInfo_get0_pkey_ctx(si);
1006                 if (!cms_set_pkey_param(pctx, kparam->param))
1007                     goto end;
1008             }
1009             if (rr && !CMS_add1_ReceiptRequest(si, rr))
1010                 goto end;
1011             X509_free(signer);
1012             signer = NULL;
1013             EVP_PKEY_free(key);
1014             key = NULL;
1015         }
1016         /* If not streaming or resigning finalize structure */
1017         if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM)) {
1018             if (!CMS_final(cms, in, NULL, flags))
1019                 goto end;
1020         }
1021     }
1022
1023     if (!cms) {
1024         BIO_printf(bio_err, "Error creating CMS structure\n");
1025         goto end;
1026     }
1027
1028     ret = 4;
1029     if (operation == SMIME_DECRYPT) {
1030         if (flags & CMS_DEBUG_DECRYPT)
1031             CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags);
1032
1033         if (secret_key) {
1034             if (!CMS_decrypt_set1_key(cms,
1035                                       secret_key, secret_keylen,
1036                                       secret_keyid, secret_keyidlen)) {
1037                 BIO_puts(bio_err, "Error decrypting CMS using secret key\n");
1038                 goto end;
1039             }
1040         }
1041
1042         if (key) {
1043             if (!CMS_decrypt_set1_pkey(cms, key, recip)) {
1044                 BIO_puts(bio_err, "Error decrypting CMS using private key\n");
1045                 goto end;
1046             }
1047         }
1048
1049         if (pwri_pass) {
1050             if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) {
1051                 BIO_puts(bio_err, "Error decrypting CMS using password\n");
1052                 goto end;
1053             }
1054         }
1055
1056         if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) {
1057             BIO_printf(bio_err, "Error decrypting CMS structure\n");
1058             goto end;
1059         }
1060     } else if (operation == SMIME_DATAOUT) {
1061         if (!CMS_data(cms, out, flags))
1062             goto end;
1063     } else if (operation == SMIME_UNCOMPRESS) {
1064         if (!CMS_uncompress(cms, indata, out, flags))
1065             goto end;
1066     } else if (operation == SMIME_DIGEST_VERIFY) {
1067         if (CMS_digest_verify(cms, indata, out, flags) > 0)
1068             BIO_printf(bio_err, "Verification successful\n");
1069         else {
1070             BIO_printf(bio_err, "Verification failure\n");
1071             goto end;
1072         }
1073     } else if (operation == SMIME_ENCRYPTED_DECRYPT) {
1074         if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen,
1075                                        indata, out, flags))
1076             goto end;
1077     } else if (operation == SMIME_VERIFY) {
1078         if (CMS_verify(cms, other, store, indata, out, flags) > 0)
1079             BIO_printf(bio_err, "Verification successful\n");
1080         else {
1081             BIO_printf(bio_err, "Verification failure\n");
1082             if (verify_retcode)
1083                 ret = verify_err + 32;
1084             goto end;
1085         }
1086         if (signerfile) {
1087             STACK_OF(X509) *signers;
1088             signers = CMS_get0_signers(cms);
1089             if (!save_certs(signerfile, signers)) {
1090                 BIO_printf(bio_err,
1091                            "Error writing signers to %s\n", signerfile);
1092                 ret = 5;
1093                 goto end;
1094             }
1095             sk_X509_free(signers);
1096         }
1097         if (rr_print)
1098             receipt_request_print(bio_err, cms);
1099
1100     } else if (operation == SMIME_VERIFY_RECEIPT) {
1101         if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0)
1102             BIO_printf(bio_err, "Verification successful\n");
1103         else {
1104             BIO_printf(bio_err, "Verification failure\n");
1105             goto end;
1106         }
1107     } else {
1108         if (noout) {
1109             if (print)
1110                 CMS_ContentInfo_print_ctx(out, cms, 0, NULL);
1111         } else if (outformat == FORMAT_SMIME) {
1112             if (to)
1113                 BIO_printf(out, "To: %s\n", to);
1114             if (from)
1115                 BIO_printf(out, "From: %s\n", from);
1116             if (subject)
1117                 BIO_printf(out, "Subject: %s\n", subject);
1118             if (operation == SMIME_RESIGN)
1119                 ret = SMIME_write_CMS(out, cms, indata, flags);
1120             else
1121                 ret = SMIME_write_CMS(out, cms, in, flags);
1122         } else if (outformat == FORMAT_PEM)
1123             ret = PEM_write_bio_CMS_stream(out, cms, in, flags);
1124         else if (outformat == FORMAT_ASN1)
1125             ret = i2d_CMS_bio_stream(out, cms, in, flags);
1126         else {
1127             BIO_printf(bio_err, "Bad output format for CMS file\n");
1128             goto end;
1129         }
1130         if (ret <= 0) {
1131             ret = 6;
1132             goto end;
1133         }
1134     }
1135     ret = 0;
1136  end:
1137     if (ret)
1138         ERR_print_errors(bio_err);
1139     if (need_rand)
1140         app_RAND_write_file(NULL, bio_err);
1141     sk_X509_pop_free(encerts, X509_free);
1142     sk_X509_pop_free(other, X509_free);
1143     if (vpm)
1144         X509_VERIFY_PARAM_free(vpm);
1145     if (sksigners)
1146         sk_OPENSSL_STRING_free(sksigners);
1147     if (skkeys)
1148         sk_OPENSSL_STRING_free(skkeys);
1149     if (secret_key)
1150         OPENSSL_free(secret_key);
1151     if (secret_keyid)
1152         OPENSSL_free(secret_keyid);
1153     if (pwri_tmp)
1154         OPENSSL_free(pwri_tmp);
1155     ASN1_OBJECT_free(econtent_type);
1156     if (rr)
1157         CMS_ReceiptRequest_free(rr);
1158     if (rr_to)
1159         sk_OPENSSL_STRING_free(rr_to);
1160     if (rr_from)
1161         sk_OPENSSL_STRING_free(rr_from);
1162     for (key_param = key_first; key_param;) {
1163         cms_key_param *tparam;
1164         sk_OPENSSL_STRING_free(key_param->param);
1165         tparam = key_param->next;
1166         OPENSSL_free(key_param);
1167         key_param = tparam;
1168     }
1169     X509_STORE_free(store);
1170     X509_free(cert);
1171     X509_free(recip);
1172     X509_free(signer);
1173     EVP_PKEY_free(key);
1174     CMS_ContentInfo_free(cms);
1175     CMS_ContentInfo_free(rcms);
1176     BIO_free(rctin);
1177     BIO_free(in);
1178     BIO_free(indata);
1179     BIO_free_all(out);
1180     if (passin)
1181         OPENSSL_free(passin);
1182     return (ret);
1183 }
1184
1185 static int save_certs(char *signerfile, STACK_OF(X509) *signers)
1186 {
1187     int i;
1188     BIO *tmp;
1189     if (!signerfile)
1190         return 1;
1191     tmp = BIO_new_file(signerfile, "w");
1192     if (!tmp)
1193         return 0;
1194     for (i = 0; i < sk_X509_num(signers); i++)
1195         PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
1196     BIO_free(tmp);
1197     return 1;
1198 }
1199
1200 /* Minimal callback just to output policy info (if any) */
1201
1202 static int cms_cb(int ok, X509_STORE_CTX *ctx)
1203 {
1204     int error;
1205
1206     error = X509_STORE_CTX_get_error(ctx);
1207
1208     verify_err = error;
1209
1210     if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
1211         && ((error != X509_V_OK) || (ok != 2)))
1212         return ok;
1213
1214     policies_print(NULL, ctx);
1215
1216     return ok;
1217
1218 }
1219
1220 static void gnames_stack_print(BIO *out, STACK_OF(GENERAL_NAMES) *gns)
1221 {
1222     STACK_OF(GENERAL_NAME) *gens;
1223     GENERAL_NAME *gen;
1224     int i, j;
1225     for (i = 0; i < sk_GENERAL_NAMES_num(gns); i++) {
1226         gens = sk_GENERAL_NAMES_value(gns, i);
1227         for (j = 0; j < sk_GENERAL_NAME_num(gens); j++) {
1228             gen = sk_GENERAL_NAME_value(gens, j);
1229             BIO_puts(out, "    ");
1230             GENERAL_NAME_print(out, gen);
1231             BIO_puts(out, "\n");
1232         }
1233     }
1234     return;
1235 }
1236
1237 static void receipt_request_print(BIO *out, CMS_ContentInfo *cms)
1238 {
1239     STACK_OF(CMS_SignerInfo) *sis;
1240     CMS_SignerInfo *si;
1241     CMS_ReceiptRequest *rr;
1242     int allorfirst;
1243     STACK_OF(GENERAL_NAMES) *rto, *rlist;
1244     ASN1_STRING *scid;
1245     int i, rv;
1246     sis = CMS_get0_SignerInfos(cms);
1247     for (i = 0; i < sk_CMS_SignerInfo_num(sis); i++) {
1248         si = sk_CMS_SignerInfo_value(sis, i);
1249         rv = CMS_get1_ReceiptRequest(si, &rr);
1250         BIO_printf(bio_err, "Signer %d:\n", i + 1);
1251         if (rv == 0)
1252             BIO_puts(bio_err, "  No Receipt Request\n");
1253         else if (rv < 0) {
1254             BIO_puts(bio_err, "  Receipt Request Parse Error\n");
1255             ERR_print_errors(bio_err);
1256         } else {
1257             char *id;
1258             int idlen;
1259             CMS_ReceiptRequest_get0_values(rr, &scid, &allorfirst,
1260                                            &rlist, &rto);
1261             BIO_puts(out, "  Signed Content ID:\n");
1262             idlen = ASN1_STRING_length(scid);
1263             id = (char *)ASN1_STRING_data(scid);
1264             BIO_dump_indent(out, id, idlen, 4);
1265             BIO_puts(out, "  Receipts From");
1266             if (rlist) {
1267                 BIO_puts(out, " List:\n");
1268                 gnames_stack_print(out, rlist);
1269             } else if (allorfirst == 1)
1270                 BIO_puts(out, ": First Tier\n");
1271             else if (allorfirst == 0)
1272                 BIO_puts(out, ": All\n");
1273             else
1274                 BIO_printf(out, " Unknown (%d)\n", allorfirst);
1275             BIO_puts(out, "  Receipts To:\n");
1276             gnames_stack_print(out, rto);
1277         }
1278         if (rr)
1279             CMS_ReceiptRequest_free(rr);
1280     }
1281 }
1282
1283 static STACK_OF(GENERAL_NAMES) *make_names_stack(STACK_OF(OPENSSL_STRING) *ns)
1284 {
1285     int i;
1286     STACK_OF(GENERAL_NAMES) *ret;
1287     GENERAL_NAMES *gens = NULL;
1288     GENERAL_NAME *gen = NULL;
1289     ret = sk_GENERAL_NAMES_new_null();
1290     if (!ret)
1291         goto err;
1292     for (i = 0; i < sk_OPENSSL_STRING_num(ns); i++) {
1293         char *str = sk_OPENSSL_STRING_value(ns, i);
1294         gen = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_EMAIL, str, 0);
1295         if (!gen)
1296             goto err;
1297         gens = GENERAL_NAMES_new();
1298         if (!gens)
1299             goto err;
1300         if (!sk_GENERAL_NAME_push(gens, gen))
1301             goto err;
1302         gen = NULL;
1303         if (!sk_GENERAL_NAMES_push(ret, gens))
1304             goto err;
1305         gens = NULL;
1306     }
1307
1308     return ret;
1309
1310  err:
1311     if (ret)
1312         sk_GENERAL_NAMES_pop_free(ret, GENERAL_NAMES_free);
1313     if (gens)
1314         GENERAL_NAMES_free(gens);
1315     if (gen)
1316         GENERAL_NAME_free(gen);
1317     return NULL;
1318 }
1319
1320 static CMS_ReceiptRequest *make_receipt_request(STACK_OF(OPENSSL_STRING)
1321                                                 *rr_to, int rr_allorfirst, STACK_OF(OPENSSL_STRING)
1322                                                 *rr_from)
1323 {
1324     STACK_OF(GENERAL_NAMES) *rct_to, *rct_from;
1325     CMS_ReceiptRequest *rr;
1326     rct_to = make_names_stack(rr_to);
1327     if (!rct_to)
1328         goto err;
1329     if (rr_from) {
1330         rct_from = make_names_stack(rr_from);
1331         if (!rct_from)
1332             goto err;
1333     } else
1334         rct_from = NULL;
1335     rr = CMS_ReceiptRequest_create0(NULL, -1, rr_allorfirst, rct_from,
1336                                     rct_to);
1337     return rr;
1338  err:
1339     return NULL;
1340 }
1341
1342 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
1343                               STACK_OF(OPENSSL_STRING) *param)
1344 {
1345     char *keyopt;
1346     int i;
1347     if (sk_OPENSSL_STRING_num(param) <= 0)
1348         return 1;
1349     for (i = 0; i < sk_OPENSSL_STRING_num(param); i++) {
1350         keyopt = sk_OPENSSL_STRING_value(param, i);
1351         if (pkey_ctrl_string(pctx, keyopt) <= 0) {
1352             BIO_printf(bio_err, "parameter error \"%s\"\n", keyopt);
1353             ERR_print_errors(bio_err);
1354             return 0;
1355         }
1356     }
1357     return 1;
1358 }
1359
1360 #endif