a280d8e19c94b2abdafc07329ff1249e130cbad2
[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 smime_cb(int ok, X509_STORE_CTX *ctx);
73
74 #define SMIME_OP        0x10
75 #define SMIME_IP        0x20
76 #define SMIME_SIGNERS   0x40
77 #define SMIME_ENCRYPT           (1 | SMIME_OP)
78 #define SMIME_DECRYPT           (2 | SMIME_IP)
79 #define SMIME_SIGN              (3 | SMIME_OP | SMIME_SIGNERS)
80 #define SMIME_VERIFY            (4 | SMIME_IP)
81 #define SMIME_CMSOUT            (5 | SMIME_IP | SMIME_OP)
82 #define SMIME_RESIGN            (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
83 #define SMIME_DATAOUT           (7 | SMIME_IP)
84 #define SMIME_DATA_CREATE       (8 | SMIME_OP)
85 #define SMIME_DIGEST_VERIFY     (9 | SMIME_IP)
86 #define SMIME_DIGEST_CREATE     (10 | SMIME_OP)
87 #define SMIME_UNCOMPRESS        (11 | SMIME_IP)
88 #define SMIME_COMPRESS          (12 | SMIME_OP)
89 #define SMIME_ENCRYPTED_DECRYPT (13 | SMIME_IP)
90 #define SMIME_ENCRYPTED_ENCRYPT (14 | SMIME_OP)
91
92 int MAIN(int, char **);
93
94 int MAIN(int argc, char **argv)
95         {
96         ENGINE *e = NULL;
97         int operation = 0;
98         int ret = 0;
99         char **args;
100         const char *inmode = "r", *outmode = "w";
101         char *infile = NULL, *outfile = NULL;
102         char *signerfile = NULL, *recipfile = NULL;
103         STACK *sksigners = NULL, *skkeys = NULL;
104         char *certfile = NULL, *keyfile = NULL, *contfile=NULL;
105         const EVP_CIPHER *cipher = NULL;
106         CMS_ContentInfo *cms = NULL;
107         X509_STORE *store = NULL;
108         X509 *cert = NULL, *recip = NULL, *signer = NULL;
109         EVP_PKEY *key = NULL;
110         STACK_OF(X509) *encerts = NULL, *other = NULL;
111         BIO *in = NULL, *out = NULL, *indata = NULL;
112         int badarg = 0;
113         int flags = CMS_DETACHED;
114         char *to = NULL, *from = NULL, *subject = NULL;
115         char *CAfile = NULL, *CApath = NULL;
116         char *passargin = NULL, *passin = NULL;
117         char *inrand = NULL;
118         int need_rand = 0;
119         const EVP_MD *sign_md = NULL;
120         int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
121         int keyform = FORMAT_PEM;
122 #ifndef OPENSSL_NO_ENGINE
123         char *engine=NULL;
124 #endif
125         unsigned char *secret_key = NULL;
126         size_t secret_keylen = 0;
127
128         X509_VERIFY_PARAM *vpm = NULL;
129
130         args = argv + 1;
131         ret = 1;
132
133         apps_startup();
134
135         if (bio_err == NULL)
136                 {
137                 if ((bio_err = BIO_new(BIO_s_file())) != NULL)
138                         BIO_set_fp(bio_err, stderr, BIO_NOCLOSE|BIO_FP_TEXT);
139                 }
140
141         if (!load_config(bio_err, NULL))
142                 goto end;
143
144         while (!badarg && *args && *args[0] == '-')
145                 {
146                 if (!strcmp (*args, "-encrypt"))
147                         operation = SMIME_ENCRYPT;
148                 else if (!strcmp (*args, "-decrypt"))
149                         operation = SMIME_DECRYPT;
150                 else if (!strcmp (*args, "-sign"))
151                         operation = SMIME_SIGN;
152                 else if (!strcmp (*args, "-resign"))
153                         operation = SMIME_RESIGN;
154                 else if (!strcmp (*args, "-verify"))
155                         operation = SMIME_VERIFY;
156                 else if (!strcmp (*args, "-cmsout"))
157                         operation = SMIME_CMSOUT;
158                 else if (!strcmp (*args, "-data_out"))
159                         operation = SMIME_DATAOUT;
160                 else if (!strcmp (*args, "-data_create"))
161                         operation = SMIME_DATA_CREATE;
162                 else if (!strcmp (*args, "-digest_verify"))
163                         operation = SMIME_DIGEST_VERIFY;
164                 else if (!strcmp (*args, "-digest_create"))
165                         operation = SMIME_DIGEST_CREATE;
166                 else if (!strcmp (*args, "-compress"))
167                         operation = SMIME_COMPRESS;
168                 else if (!strcmp (*args, "-uncompress"))
169                         operation = SMIME_UNCOMPRESS;
170                 else if (!strcmp (*args, "-EncryptedData_decrypt"))
171                         operation = SMIME_ENCRYPTED_DECRYPT;
172                 else if (!strcmp (*args, "-EncryptedData_encrypt"))
173                         operation = SMIME_ENCRYPTED_ENCRYPT;
174 #ifndef OPENSSL_NO_DES
175                 else if (!strcmp (*args, "-des3")) 
176                                 cipher = EVP_des_ede3_cbc();
177                 else if (!strcmp (*args, "-des")) 
178                                 cipher = EVP_des_cbc();
179 #endif
180 #ifndef OPENSSL_NO_SEED
181                 else if (!strcmp (*args, "-seed")) 
182                                 cipher = EVP_seed_cbc();
183 #endif
184 #ifndef OPENSSL_NO_RC2
185                 else if (!strcmp (*args, "-rc2-40")) 
186                                 cipher = EVP_rc2_40_cbc();
187                 else if (!strcmp (*args, "-rc2-128")) 
188                                 cipher = EVP_rc2_cbc();
189                 else if (!strcmp (*args, "-rc2-64")) 
190                                 cipher = EVP_rc2_64_cbc();
191 #endif
192 #ifndef OPENSSL_NO_AES
193                 else if (!strcmp(*args,"-aes128"))
194                                 cipher = EVP_aes_128_cbc();
195                 else if (!strcmp(*args,"-aes192"))
196                                 cipher = EVP_aes_192_cbc();
197                 else if (!strcmp(*args,"-aes256"))
198                                 cipher = EVP_aes_256_cbc();
199 #endif
200 #ifndef OPENSSL_NO_CAMELLIA
201                 else if (!strcmp(*args,"-camellia128"))
202                                 cipher = EVP_camellia_128_cbc();
203                 else if (!strcmp(*args,"-camellia192"))
204                                 cipher = EVP_camellia_192_cbc();
205                 else if (!strcmp(*args,"-camellia256"))
206                                 cipher = EVP_camellia_256_cbc();
207 #endif
208                 else if (!strcmp (*args, "-text")) 
209                                 flags |= CMS_TEXT;
210                 else if (!strcmp (*args, "-nointern")) 
211                                 flags |= CMS_NOINTERN;
212                 else if (!strcmp (*args, "-noverify") 
213                         || !strcmp (*args, "-no_signer_cert_verify")) 
214                                 flags |= CMS_NO_SIGNER_CERT_VERIFY;
215                 else if (!strcmp (*args, "-nocerts")) 
216                                 flags |= CMS_NOCERTS;
217                 else if (!strcmp (*args, "-noattr")) 
218                                 flags |= CMS_NOATTR;
219                 else if (!strcmp (*args, "-nodetach")) 
220                                 flags &= ~CMS_DETACHED;
221                 else if (!strcmp (*args, "-nosmimecap"))
222                                 flags |= CMS_NOSMIMECAP;
223                 else if (!strcmp (*args, "-binary"))
224                                 flags |= CMS_BINARY;
225                 else if (!strcmp (*args, "-keyid"))
226                                 flags |= CMS_USE_KEYID;
227                 else if (!strcmp (*args, "-nosigs"))
228                                 flags |= CMS_NOSIGS;
229                 else if (!strcmp (*args, "-no_content_verify"))
230                                 flags |= CMS_NO_CONTENT_VERIFY;
231                 else if (!strcmp (*args, "-no_attr_verify"))
232                                 flags |= CMS_NO_ATTR_VERIFY;
233                 else if (!strcmp (*args, "-stream"))
234                                 flags |= CMS_STREAM;
235                 else if (!strcmp (*args, "-indef"))
236                                 flags |= CMS_STREAM;
237                 else if (!strcmp (*args, "-noindef"))
238                                 flags &= ~CMS_STREAM;
239                 else if (!strcmp (*args, "-nooldmime"))
240                                 flags |= CMS_NOOLDMIMETYPE;
241                 else if (!strcmp (*args, "-crlfeol"))
242                                 flags |= CMS_CRLFEOL;
243                 else if (!strcmp(*args,"-secretkey"))
244                         {
245                         long ltmp;
246                         if (!args[1])
247                                 goto argerr;
248                         args++;
249                         secret_key = string_to_hex(*args, &ltmp);
250                         if (!secret_key)
251                                 {
252                                 BIO_printf(bio_err, "Invalid key %s\n", *args);
253                                 goto argerr;
254                                 }
255                         secret_keylen = (size_t)ltmp;
256                         }
257                 else if (!strcmp(*args,"-rand"))
258                         {
259                         if (!args[1])
260                                 goto argerr;
261                         args++;
262                         inrand = *args;
263                         need_rand = 1;
264                         }
265 #ifndef OPENSSL_NO_ENGINE
266                 else if (!strcmp(*args,"-engine"))
267                         {
268                         if (!args[1])
269                                 goto argerr;
270                         engine = *++args;
271                         }
272 #endif
273                 else if (!strcmp(*args,"-passin"))
274                         {
275                         if (!args[1])
276                                 goto argerr;
277                         passargin = *++args;
278                         }
279                 else if (!strcmp (*args, "-to"))
280                         {
281                         if (!args[1])
282                                 goto argerr;
283                         to = *++args;
284                         }
285                 else if (!strcmp (*args, "-from"))
286                         {
287                         if (!args[1])
288                                 goto argerr;
289                         from = *++args;
290                         }
291                 else if (!strcmp (*args, "-subject"))
292                         {
293                         if (!args[1])
294                                 goto argerr;
295                         subject = *++args;
296                         }
297                 else if (!strcmp (*args, "-signer"))
298                         {
299                         if (!args[1])
300                                 goto argerr;
301                         /* If previous -signer argument add signer to list */
302
303                         if (signerfile)
304                                 {
305                                 if (!sksigners)
306                                         sksigners = sk_new_null();
307                                 sk_push(sksigners, signerfile);
308                                 if (!keyfile)
309                                         keyfile = signerfile;
310                                 if (!skkeys)
311                                         skkeys = sk_new_null();
312                                 sk_push(skkeys, keyfile);
313                                 keyfile = NULL;
314                                 }
315                         signerfile = *++args;
316                         }
317                 else if (!strcmp (*args, "-recip"))
318                         {
319                         if (!args[1])
320                                 goto argerr;
321                         recipfile = *++args;
322                         }
323                 else if (!strcmp (*args, "-md"))
324                         {
325                         if (!args[1])
326                                 goto argerr;
327                         sign_md = EVP_get_digestbyname(*++args);
328                         if (sign_md == NULL)
329                                 {
330                                 BIO_printf(bio_err, "Unknown digest %s\n",
331                                                         *args);
332                                 goto argerr;
333                                 }
334                         }
335                 else if (!strcmp (*args, "-inkey"))
336                         {
337                         if (!args[1])   
338                                 goto argerr;
339                         /* If previous -inkey arument add signer to list */
340                         if (keyfile)
341                                 {
342                                 if (!signerfile)
343                                         {
344                                         BIO_puts(bio_err, "Illegal -inkey without -signer\n");
345                                         goto argerr;
346                                         }
347                                 if (!sksigners)
348                                         sksigners = sk_new_null();
349                                 sk_push(sksigners, signerfile);
350                                 signerfile = NULL;
351                                 if (!skkeys)
352                                         skkeys = sk_new_null();
353                                 sk_push(skkeys, keyfile);
354                                 }
355                         keyfile = *++args;
356                         }
357                 else if (!strcmp (*args, "-keyform"))
358                         {
359                         if (!args[1])
360                                 goto argerr;
361                         keyform = str2fmt(*++args);
362                         }
363                 else if (!strcmp (*args, "-certfile"))
364                         {
365                         if (!args[1])
366                                 goto argerr;
367                         certfile = *++args;
368                         }
369                 else if (!strcmp (*args, "-CAfile"))
370                         {
371                         if (!args[1])
372                                 goto argerr;
373                         CAfile = *++args;
374                         }
375                 else if (!strcmp (*args, "-CApath"))
376                         {
377                         if (!args[1])
378                                 goto argerr;
379                         CApath = *++args;
380                         }
381                 else if (!strcmp (*args, "-in"))
382                         {
383                         if (!args[1])
384                                 goto argerr;
385                         infile = *++args;
386                         }
387                 else if (!strcmp (*args, "-inform"))
388                         {
389                         if (!args[1])
390                                 goto argerr;
391                         informat = str2fmt(*++args);
392                         }
393                 else if (!strcmp (*args, "-outform"))
394                         {
395                         if (!args[1])
396                                 goto argerr;
397                         outformat = str2fmt(*++args);
398                         }
399                 else if (!strcmp (*args, "-out"))
400                         {
401                         if (!args[1])
402                                 goto argerr;
403                         outfile = *++args;
404                         }
405                 else if (!strcmp (*args, "-content"))
406                         {
407                         if (!args[1])
408                                 goto argerr;
409                         contfile = *++args;
410                         }
411                 else if (args_verify(&args, NULL, &badarg, bio_err, &vpm))
412                         continue;
413                 else if ((cipher = EVP_get_cipherbyname(*args + 1)) == NULL)
414                         badarg = 1;
415                 args++;
416                 }
417
418         if (!(operation & SMIME_SIGNERS) && (skkeys || sksigners))
419                 {
420                 BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
421                 goto argerr;
422                 }
423
424         if (operation & SMIME_SIGNERS)
425                 {
426                 /* Check to see if any final signer needs to be appended */
427                 if (keyfile && !signerfile)
428                         {
429                         BIO_puts(bio_err, "Illegal -inkey without -signer\n");
430                         goto argerr;
431                         }
432                 if (signerfile)
433                         {
434                         if (!sksigners)
435                                 sksigners = sk_new_null();
436                         sk_push(sksigners, signerfile);
437                         if (!skkeys)
438                                 skkeys = sk_new_null();
439                         if (!keyfile)
440                                 keyfile = signerfile;
441                         sk_push(skkeys, keyfile);
442                         }
443                 if (!sksigners)
444                         {
445                         BIO_printf(bio_err, "No signer certificate specified\n");
446                         badarg = 1;
447                         }
448                 signerfile = NULL;
449                 keyfile = NULL;
450                 need_rand = 1;
451                 }
452         else if (operation == SMIME_DECRYPT)
453                 {
454                 if (!recipfile && !keyfile)
455                         {
456                         BIO_printf(bio_err, "No recipient certificate or key specified\n");
457                         badarg = 1;
458                         }
459                 }
460         else if (operation == SMIME_ENCRYPT)
461                 {
462                 if (!*args)
463                         {
464                         BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
465                         badarg = 1;
466                         }
467                 need_rand = 1;
468                 }
469         else if (!operation)
470                 badarg = 1;
471
472         if (badarg)
473                 {
474                 argerr:
475                 BIO_printf (bio_err, "Usage smime [options] cert.pem ...\n");
476                 BIO_printf (bio_err, "where options are\n");
477                 BIO_printf (bio_err, "-encrypt       encrypt message\n");
478                 BIO_printf (bio_err, "-decrypt       decrypt encrypted message\n");
479                 BIO_printf (bio_err, "-sign          sign message\n");
480                 BIO_printf (bio_err, "-verify        verify signed message\n");
481                 BIO_printf (bio_err, "-cmsout        output CMS structure\n");
482 #ifndef OPENSSL_NO_DES
483                 BIO_printf (bio_err, "-des3          encrypt with triple DES\n");
484                 BIO_printf (bio_err, "-des           encrypt with DES\n");
485 #endif
486 #ifndef OPENSSL_NO_SEED
487                 BIO_printf (bio_err, "-seed          encrypt with SEED\n");
488 #endif
489 #ifndef OPENSSL_NO_RC2
490                 BIO_printf (bio_err, "-rc2-40        encrypt with RC2-40 (default)\n");
491                 BIO_printf (bio_err, "-rc2-64        encrypt with RC2-64\n");
492                 BIO_printf (bio_err, "-rc2-128       encrypt with RC2-128\n");
493 #endif
494 #ifndef OPENSSL_NO_AES
495                 BIO_printf (bio_err, "-aes128, -aes192, -aes256\n");
496                 BIO_printf (bio_err, "               encrypt PEM output with cbc aes\n");
497 #endif
498 #ifndef OPENSSL_NO_CAMELLIA
499                 BIO_printf (bio_err, "-camellia128, -camellia192, -camellia256\n");
500                 BIO_printf (bio_err, "               encrypt PEM output with cbc camellia\n");
501 #endif
502                 BIO_printf (bio_err, "-nointern      don't search certificates in message for signer\n");
503                 BIO_printf (bio_err, "-nosigs        don't verify message signature\n");
504                 BIO_printf (bio_err, "-noverify      don't verify signers certificate\n");
505                 BIO_printf (bio_err, "-nocerts       don't include signers certificate when signing\n");
506                 BIO_printf (bio_err, "-nodetach      use opaque signing\n");
507                 BIO_printf (bio_err, "-noattr        don't include any signed attributes\n");
508                 BIO_printf (bio_err, "-binary        don't translate message to text\n");
509                 BIO_printf (bio_err, "-certfile file other certificates file\n");
510                 BIO_printf (bio_err, "-signer file   signer certificate file\n");
511                 BIO_printf (bio_err, "-recip  file   recipient certificate file for decryption\n");
512                 BIO_printf (bio_err, "-skeyid        use subject key identifier\n");
513                 BIO_printf (bio_err, "-in file       input file\n");
514                 BIO_printf (bio_err, "-inform arg    input format SMIME (default), PEM or DER\n");
515                 BIO_printf (bio_err, "-inkey file    input private key (if not signer or recipient)\n");
516                 BIO_printf (bio_err, "-keyform arg   input private key format (PEM or ENGINE)\n");
517                 BIO_printf (bio_err, "-out file      output file\n");
518                 BIO_printf (bio_err, "-outform arg   output format SMIME (default), PEM or DER\n");
519                 BIO_printf (bio_err, "-content file  supply or override content for detached signature\n");
520                 BIO_printf (bio_err, "-to addr       to address\n");
521                 BIO_printf (bio_err, "-from ad       from address\n");
522                 BIO_printf (bio_err, "-subject s     subject\n");
523                 BIO_printf (bio_err, "-text          include or delete text MIME headers\n");
524                 BIO_printf (bio_err, "-CApath dir    trusted certificates directory\n");
525                 BIO_printf (bio_err, "-CAfile file   trusted certificates file\n");
526                 BIO_printf (bio_err, "-crl_check     check revocation status of signer's certificate using CRLs\n");
527                 BIO_printf (bio_err, "-crl_check_all check revocation status of signer's certificate chain using CRLs\n");
528 #ifndef OPENSSL_NO_ENGINE
529                 BIO_printf (bio_err, "-engine e      use engine e, possibly a hardware device.\n");
530 #endif
531                 BIO_printf (bio_err, "-passin arg    input file pass phrase source\n");
532                 BIO_printf(bio_err,  "-rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
533                 BIO_printf(bio_err,  "               load the file (or the files in the directory) into\n");
534                 BIO_printf(bio_err,  "               the random number generator\n");
535                 BIO_printf (bio_err, "cert.pem       recipient certificate(s) for encryption\n");
536                 goto end;
537                 }
538
539 #ifndef OPENSSL_NO_ENGINE
540         e = setup_engine(bio_err, engine, 0);
541 #endif
542
543         if (!app_passwd(bio_err, passargin, NULL, &passin, NULL))
544                 {
545                 BIO_printf(bio_err, "Error getting password\n");
546                 goto end;
547                 }
548
549         if (need_rand)
550                 {
551                 app_RAND_load_file(NULL, bio_err, (inrand != NULL));
552                 if (inrand != NULL)
553                         BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
554                                 app_RAND_load_files(inrand));
555                 }
556
557         ret = 2;
558
559         if (!(operation & SMIME_SIGNERS))
560                 flags &= ~CMS_DETACHED;
561
562         if (operation & SMIME_OP)
563                 {
564                 if (outformat == FORMAT_ASN1)
565                         outmode = "wb";
566                 }
567         else
568                 {
569                 if (flags & CMS_BINARY)
570                         outmode = "wb";
571                 }
572
573         if (operation & SMIME_IP)
574                 {
575                 if (informat == FORMAT_ASN1)
576                         inmode = "rb";
577                 }
578         else
579                 {
580                 if (flags & CMS_BINARY)
581                         inmode = "rb";
582                 }
583
584         if (operation == SMIME_ENCRYPT)
585                 {
586                 if (!cipher)
587                         {
588 #ifndef OPENSSL_NO_DES                  
589                         cipher = EVP_des_ede3_cbc();
590 #else
591                         BIO_printf(bio_err, "No cipher selected\n");
592                         goto end;
593 #endif
594                         }
595                 encerts = sk_X509_new_null();
596                 while (*args)
597                         {
598                         if (!(cert = load_cert(bio_err,*args,FORMAT_PEM,
599                                 NULL, e, "recipient certificate file")))
600                                 {
601 #if 0                           /* An appropriate message is already printed */
602                                 BIO_printf(bio_err, "Can't read recipient certificate file %s\n", *args);
603 #endif
604                                 goto end;
605                                 }
606                         sk_X509_push(encerts, cert);
607                         cert = NULL;
608                         args++;
609                         }
610                 }
611
612         if (certfile)
613                 {
614                 if (!(other = load_certs(bio_err,certfile,FORMAT_PEM, NULL,
615                         e, "certificate file")))
616                         {
617                         ERR_print_errors(bio_err);
618                         goto end;
619                         }
620                 }
621
622         if (recipfile && (operation == SMIME_DECRYPT))
623                 {
624                 if (!(recip = load_cert(bio_err,recipfile,FORMAT_PEM,NULL,
625                         e, "recipient certificate file")))
626                         {
627                         ERR_print_errors(bio_err);
628                         goto end;
629                         }
630                 }
631
632         if (operation == SMIME_DECRYPT)
633                 {
634                 if (!keyfile)
635                         keyfile = recipfile;
636                 }
637         else if (operation == SMIME_SIGN)
638                 {
639                 if (!keyfile)
640                         keyfile = signerfile;
641                 }
642         else keyfile = NULL;
643
644         if (keyfile)
645                 {
646                 key = load_key(bio_err, keyfile, keyform, 0, passin, e,
647                                "signing key file");
648                 if (!key)
649                         goto end;
650                 }
651
652         if (infile)
653                 {
654                 if (!(in = BIO_new_file(infile, inmode)))
655                         {
656                         BIO_printf (bio_err,
657                                  "Can't open input file %s\n", infile);
658                         goto end;
659                         }
660                 }
661         else
662                 in = BIO_new_fp(stdin, BIO_NOCLOSE);
663
664         if (operation & SMIME_IP)
665                 {
666                 if (informat == FORMAT_SMIME) 
667                         cms = SMIME_read_CMS(in, &indata);
668                 else if (informat == FORMAT_PEM) 
669                         cms = PEM_read_bio_CMS(in, NULL, NULL, NULL);
670                 else if (informat == FORMAT_ASN1) 
671                         cms = d2i_CMS_bio(in, NULL);
672                 else
673                         {
674                         BIO_printf(bio_err, "Bad input format for CMS file\n");
675                         goto end;
676                         }
677
678                 if (!cms)
679                         {
680                         BIO_printf(bio_err, "Error reading S/MIME message\n");
681                         goto end;
682                         }
683                 if (contfile)
684                         {
685                         BIO_free(indata);
686                         if (!(indata = BIO_new_file(contfile, "rb")))
687                                 {
688                                 BIO_printf(bio_err, "Can't read content file %s\n", contfile);
689                                 goto end;
690                                 }
691                         }
692                 }
693
694         if (outfile)
695                 {
696                 if (!(out = BIO_new_file(outfile, outmode)))
697                         {
698                         BIO_printf (bio_err,
699                                  "Can't open output file %s\n", outfile);
700                         goto end;
701                         }
702                 }
703         else
704                 {
705                 out = BIO_new_fp(stdout, BIO_NOCLOSE);
706 #ifdef OPENSSL_SYS_VMS
707                 {
708                     BIO *tmpbio = BIO_new(BIO_f_linebuffer());
709                     out = BIO_push(tmpbio, out);
710                 }
711 #endif
712                 }
713
714         if (operation == SMIME_VERIFY)
715                 {
716                 if (!(store = setup_verify(bio_err, CAfile, CApath)))
717                         goto end;
718                 X509_STORE_set_verify_cb_func(store, smime_cb);
719                 if (vpm)
720                         X509_STORE_set1_param(store, vpm);
721                 }
722
723
724         ret = 3;
725
726         if (operation == SMIME_DATA_CREATE)
727                 {
728                 cms = CMS_data_create(in, flags);
729                 }
730         else if (operation == SMIME_DIGEST_CREATE)
731                 {
732                 cms = CMS_digest_create(in, sign_md, flags);
733                 }
734         else if (operation == SMIME_COMPRESS)
735                 {
736                 cms = CMS_compress(in, -1, flags);
737                 }
738         else if (operation == SMIME_ENCRYPT)
739                 {
740                 cms = CMS_encrypt(encerts, in, cipher, flags);
741                 }
742         else if (operation == SMIME_ENCRYPTED_ENCRYPT)
743                 {
744                 cms = CMS_EncryptedData_encrypt(in, cipher,
745                                                 secret_key, secret_keylen,
746                                                 flags);
747                 }
748         else if (operation & SMIME_SIGNERS)
749                 {
750                 int i;
751                 /* If detached data content we only enable streaming if
752                  * S/MIME output format.
753                  */
754                 if (operation == SMIME_SIGN)
755                         {
756                         if (flags & CMS_DETACHED)
757                                 {
758                                 if (outformat != FORMAT_SMIME)
759                                         flags &= ~CMS_STREAM;
760                                 }
761                         flags |= CMS_PARTIAL;
762                         cms = CMS_sign(NULL, NULL, other, in, flags);
763                         if (!cms)
764                                 goto end;
765                         }
766                 else
767                         flags |= CMS_REUSE_DIGEST;
768                 for (i = 0; i < sk_num(sksigners); i++)
769                         {
770                         signerfile = sk_value(sksigners, i);
771                         keyfile = sk_value(skkeys, i);
772                         signer = load_cert(bio_err, signerfile,FORMAT_PEM, NULL,
773                                         e, "signer certificate");
774                         if (!signer)
775                                 goto end;
776                         key = load_key(bio_err, keyfile, keyform, 0, passin, e,
777                                "signing key file");
778                         if (!key)
779                                 goto end;
780                         if (!CMS_add1_signer(cms, signer, key, sign_md, flags))
781                                 goto end;
782                         X509_free(signer);
783                         signer = NULL;
784                         EVP_PKEY_free(key);
785                         key = NULL;
786                         }
787                 /* If not streaming or resigning finalize structure */
788                 if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM))
789                         {
790                         if (!CMS_final(cms, in, flags))
791                                 goto end;
792                         }
793                 }
794
795         if (!cms)
796                 {
797                 BIO_printf(bio_err, "Error creating CMS structure\n");
798                 goto end;
799                 }
800
801         ret = 4;
802         if (operation == SMIME_DECRYPT)
803                 {
804                 if (!CMS_decrypt(cms, key, recip, indata, out, flags))
805                         {
806                         BIO_printf(bio_err, "Error decrypting CMS structure\n");
807                         goto end;
808                         }
809                 }
810         else if (operation == SMIME_DATAOUT)
811                 {
812                 if (!CMS_data(cms, out, flags))
813                         goto end;
814                 }
815         else if (operation == SMIME_UNCOMPRESS)
816                 {
817                 if (!CMS_uncompress(cms, indata, out, flags))
818                         goto end;
819                 }
820         else if (operation == SMIME_DIGEST_VERIFY)
821                 {
822                 if (CMS_digest_verify(cms, indata, out, flags) > 0)
823                         BIO_printf(bio_err, "Verification successful\n");
824                 else
825                         {
826                         BIO_printf(bio_err, "Verification failure\n");
827                         goto end;
828                         }
829                 }
830         else if (operation == SMIME_ENCRYPTED_DECRYPT)
831                 {
832                 if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen,
833                                                 indata, out, flags))
834                         goto end;
835                 }
836         else if (operation == SMIME_VERIFY)
837                 {
838                 if (CMS_verify(cms, other, store, indata, out, flags) > 0)
839                         BIO_printf(bio_err, "Verification successful\n");
840                 else
841                         {
842                         BIO_printf(bio_err, "Verification failure\n");
843                         goto end;
844                         }
845                 if (signerfile)
846                         {
847                         STACK_OF(X509) *signers;
848                         signers = CMS_get0_signers(cms);
849                         if (!save_certs(signerfile, signers))
850                                 {
851                                 BIO_printf(bio_err,
852                                                 "Error writing signers to %s\n",
853                                                                 signerfile);
854                                 ret = 5;
855                                 goto end;
856                                 }
857                         sk_X509_free(signers);
858                         }
859                 }
860         else
861                 {
862                 if (outformat == FORMAT_SMIME) 
863                         {
864                         if (to)
865                                 BIO_printf(out, "To: %s\n", to);
866                         if (from)
867                                 BIO_printf(out, "From: %s\n", from);
868                         if (subject)
869                                 BIO_printf(out, "Subject: %s\n", subject);
870                         if (operation == SMIME_RESIGN)
871                                 ret = SMIME_write_CMS(out, cms, indata, flags);
872                         else
873                                 ret = SMIME_write_CMS(out, cms, in, flags);
874                         }
875                 else if (outformat == FORMAT_PEM) 
876                         ret = PEM_write_bio_CMS_stream(out, cms, in, flags);
877                 else if (outformat == FORMAT_ASN1) 
878                         ret = i2d_CMS_bio_stream(out,cms, in, flags);
879                 else
880                         {
881                         BIO_printf(bio_err, "Bad output format for CMS file\n");
882                         goto end;
883                         }
884                 if (ret <= 0)
885                         {
886                         ret = 6;
887                         goto end;
888                         }
889                 }
890         ret = 0;
891 end:
892         if (ret)
893                 ERR_print_errors(bio_err);
894         if (need_rand)
895                 app_RAND_write_file(NULL, bio_err);
896         sk_X509_pop_free(encerts, X509_free);
897         sk_X509_pop_free(other, X509_free);
898         if (vpm)
899                 X509_VERIFY_PARAM_free(vpm);
900         if (sksigners)
901                 sk_free(sksigners);
902         if (skkeys)
903                 sk_free(skkeys);
904         if (secret_key)
905                 OPENSSL_free(secret_key);
906         X509_STORE_free(store);
907         X509_free(cert);
908         X509_free(recip);
909         X509_free(signer);
910         EVP_PKEY_free(key);
911         CMS_ContentInfo_free(cms);
912         BIO_free(in);
913         BIO_free(indata);
914         BIO_free_all(out);
915         if (passin) OPENSSL_free(passin);
916         return (ret);
917 }
918
919 static int save_certs(char *signerfile, STACK_OF(X509) *signers)
920         {
921         int i;
922         BIO *tmp;
923         if (!signerfile)
924                 return 1;
925         tmp = BIO_new_file(signerfile, "w");
926         if (!tmp) return 0;
927         for(i = 0; i < sk_X509_num(signers); i++)
928                 PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
929         BIO_free(tmp);
930         return 1;
931         }
932         
933
934 /* Minimal callback just to output policy info (if any) */
935
936 static int smime_cb(int ok, X509_STORE_CTX *ctx)
937         {
938         int error;
939
940         error = X509_STORE_CTX_get_error(ctx);
941
942         if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
943                 && ((error != X509_V_OK) || (ok != 2)))
944                 return ok;
945
946         policies_print(NULL, ctx);
947
948         return ok;
949
950         }
951
952 #endif