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