2cbd43b2a68b6b923b26f51237149b5d1a35d127
[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, *secret_keyid = NULL;
126         size_t secret_keylen = 0, secret_keyidlen = 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,"-secretkeyid"))
258                         {
259                         long ltmp;
260                         if (!args[1])
261                                 goto argerr;
262                         args++;
263                         secret_keyid = string_to_hex(*args, &ltmp);
264                         if (!secret_keyid)
265                                 {
266                                 BIO_printf(bio_err, "Invalid id %s\n", *args);
267                                 goto argerr;
268                                 }
269                         secret_keyidlen = (size_t)ltmp;
270                         }
271                 else if (!strcmp(*args,"-rand"))
272                         {
273                         if (!args[1])
274                                 goto argerr;
275                         args++;
276                         inrand = *args;
277                         need_rand = 1;
278                         }
279 #ifndef OPENSSL_NO_ENGINE
280                 else if (!strcmp(*args,"-engine"))
281                         {
282                         if (!args[1])
283                                 goto argerr;
284                         engine = *++args;
285                         }
286 #endif
287                 else if (!strcmp(*args,"-passin"))
288                         {
289                         if (!args[1])
290                                 goto argerr;
291                         passargin = *++args;
292                         }
293                 else if (!strcmp (*args, "-to"))
294                         {
295                         if (!args[1])
296                                 goto argerr;
297                         to = *++args;
298                         }
299                 else if (!strcmp (*args, "-from"))
300                         {
301                         if (!args[1])
302                                 goto argerr;
303                         from = *++args;
304                         }
305                 else if (!strcmp (*args, "-subject"))
306                         {
307                         if (!args[1])
308                                 goto argerr;
309                         subject = *++args;
310                         }
311                 else if (!strcmp (*args, "-signer"))
312                         {
313                         if (!args[1])
314                                 goto argerr;
315                         /* If previous -signer argument add signer to list */
316
317                         if (signerfile)
318                                 {
319                                 if (!sksigners)
320                                         sksigners = sk_new_null();
321                                 sk_push(sksigners, signerfile);
322                                 if (!keyfile)
323                                         keyfile = signerfile;
324                                 if (!skkeys)
325                                         skkeys = sk_new_null();
326                                 sk_push(skkeys, keyfile);
327                                 keyfile = NULL;
328                                 }
329                         signerfile = *++args;
330                         }
331                 else if (!strcmp (*args, "-recip"))
332                         {
333                         if (!args[1])
334                                 goto argerr;
335                         recipfile = *++args;
336                         }
337                 else if (!strcmp (*args, "-md"))
338                         {
339                         if (!args[1])
340                                 goto argerr;
341                         sign_md = EVP_get_digestbyname(*++args);
342                         if (sign_md == NULL)
343                                 {
344                                 BIO_printf(bio_err, "Unknown digest %s\n",
345                                                         *args);
346                                 goto argerr;
347                                 }
348                         }
349                 else if (!strcmp (*args, "-inkey"))
350                         {
351                         if (!args[1])   
352                                 goto argerr;
353                         /* If previous -inkey arument add signer to list */
354                         if (keyfile)
355                                 {
356                                 if (!signerfile)
357                                         {
358                                         BIO_puts(bio_err, "Illegal -inkey without -signer\n");
359                                         goto argerr;
360                                         }
361                                 if (!sksigners)
362                                         sksigners = sk_new_null();
363                                 sk_push(sksigners, signerfile);
364                                 signerfile = NULL;
365                                 if (!skkeys)
366                                         skkeys = sk_new_null();
367                                 sk_push(skkeys, keyfile);
368                                 }
369                         keyfile = *++args;
370                         }
371                 else if (!strcmp (*args, "-keyform"))
372                         {
373                         if (!args[1])
374                                 goto argerr;
375                         keyform = str2fmt(*++args);
376                         }
377                 else if (!strcmp (*args, "-certfile"))
378                         {
379                         if (!args[1])
380                                 goto argerr;
381                         certfile = *++args;
382                         }
383                 else if (!strcmp (*args, "-CAfile"))
384                         {
385                         if (!args[1])
386                                 goto argerr;
387                         CAfile = *++args;
388                         }
389                 else if (!strcmp (*args, "-CApath"))
390                         {
391                         if (!args[1])
392                                 goto argerr;
393                         CApath = *++args;
394                         }
395                 else if (!strcmp (*args, "-in"))
396                         {
397                         if (!args[1])
398                                 goto argerr;
399                         infile = *++args;
400                         }
401                 else if (!strcmp (*args, "-inform"))
402                         {
403                         if (!args[1])
404                                 goto argerr;
405                         informat = str2fmt(*++args);
406                         }
407                 else if (!strcmp (*args, "-outform"))
408                         {
409                         if (!args[1])
410                                 goto argerr;
411                         outformat = str2fmt(*++args);
412                         }
413                 else if (!strcmp (*args, "-out"))
414                         {
415                         if (!args[1])
416                                 goto argerr;
417                         outfile = *++args;
418                         }
419                 else if (!strcmp (*args, "-content"))
420                         {
421                         if (!args[1])
422                                 goto argerr;
423                         contfile = *++args;
424                         }
425                 else if (args_verify(&args, NULL, &badarg, bio_err, &vpm))
426                         continue;
427                 else if ((cipher = EVP_get_cipherbyname(*args + 1)) == NULL)
428                         badarg = 1;
429                 args++;
430                 }
431
432         if (!(operation & SMIME_SIGNERS) && (skkeys || sksigners))
433                 {
434                 BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
435                 goto argerr;
436                 }
437
438         if (operation & SMIME_SIGNERS)
439                 {
440                 /* Check to see if any final signer needs to be appended */
441                 if (keyfile && !signerfile)
442                         {
443                         BIO_puts(bio_err, "Illegal -inkey without -signer\n");
444                         goto argerr;
445                         }
446                 if (signerfile)
447                         {
448                         if (!sksigners)
449                                 sksigners = sk_new_null();
450                         sk_push(sksigners, signerfile);
451                         if (!skkeys)
452                                 skkeys = sk_new_null();
453                         if (!keyfile)
454                                 keyfile = signerfile;
455                         sk_push(skkeys, keyfile);
456                         }
457                 if (!sksigners)
458                         {
459                         BIO_printf(bio_err, "No signer certificate specified\n");
460                         badarg = 1;
461                         }
462                 signerfile = NULL;
463                 keyfile = NULL;
464                 need_rand = 1;
465                 }
466         else if (operation == SMIME_DECRYPT)
467                 {
468                 if (!recipfile && !keyfile && !secret_key)
469                         {
470                         BIO_printf(bio_err, "No recipient certificate or key specified\n");
471                         badarg = 1;
472                         }
473                 }
474         else if (operation == SMIME_ENCRYPT)
475                 {
476                 if (!*args && !secret_key)
477                         {
478                         BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
479                         badarg = 1;
480                         }
481                 need_rand = 1;
482                 }
483         else if (!operation)
484                 badarg = 1;
485
486         if (badarg)
487                 {
488                 argerr:
489                 BIO_printf (bio_err, "Usage smime [options] cert.pem ...\n");
490                 BIO_printf (bio_err, "where options are\n");
491                 BIO_printf (bio_err, "-encrypt       encrypt message\n");
492                 BIO_printf (bio_err, "-decrypt       decrypt encrypted message\n");
493                 BIO_printf (bio_err, "-sign          sign message\n");
494                 BIO_printf (bio_err, "-verify        verify signed message\n");
495                 BIO_printf (bio_err, "-cmsout        output CMS structure\n");
496 #ifndef OPENSSL_NO_DES
497                 BIO_printf (bio_err, "-des3          encrypt with triple DES\n");
498                 BIO_printf (bio_err, "-des           encrypt with DES\n");
499 #endif
500 #ifndef OPENSSL_NO_SEED
501                 BIO_printf (bio_err, "-seed          encrypt with SEED\n");
502 #endif
503 #ifndef OPENSSL_NO_RC2
504                 BIO_printf (bio_err, "-rc2-40        encrypt with RC2-40 (default)\n");
505                 BIO_printf (bio_err, "-rc2-64        encrypt with RC2-64\n");
506                 BIO_printf (bio_err, "-rc2-128       encrypt with RC2-128\n");
507 #endif
508 #ifndef OPENSSL_NO_AES
509                 BIO_printf (bio_err, "-aes128, -aes192, -aes256\n");
510                 BIO_printf (bio_err, "               encrypt PEM output with cbc aes\n");
511 #endif
512 #ifndef OPENSSL_NO_CAMELLIA
513                 BIO_printf (bio_err, "-camellia128, -camellia192, -camellia256\n");
514                 BIO_printf (bio_err, "               encrypt PEM output with cbc camellia\n");
515 #endif
516                 BIO_printf (bio_err, "-nointern      don't search certificates in message for signer\n");
517                 BIO_printf (bio_err, "-nosigs        don't verify message signature\n");
518                 BIO_printf (bio_err, "-noverify      don't verify signers certificate\n");
519                 BIO_printf (bio_err, "-nocerts       don't include signers certificate when signing\n");
520                 BIO_printf (bio_err, "-nodetach      use opaque signing\n");
521                 BIO_printf (bio_err, "-noattr        don't include any signed attributes\n");
522                 BIO_printf (bio_err, "-binary        don't translate message to text\n");
523                 BIO_printf (bio_err, "-certfile file other certificates file\n");
524                 BIO_printf (bio_err, "-signer file   signer certificate file\n");
525                 BIO_printf (bio_err, "-recip  file   recipient certificate file for decryption\n");
526                 BIO_printf (bio_err, "-skeyid        use subject key identifier\n");
527                 BIO_printf (bio_err, "-in file       input file\n");
528                 BIO_printf (bio_err, "-inform arg    input format SMIME (default), PEM or DER\n");
529                 BIO_printf (bio_err, "-inkey file    input private key (if not signer or recipient)\n");
530                 BIO_printf (bio_err, "-keyform arg   input private key format (PEM or ENGINE)\n");
531                 BIO_printf (bio_err, "-out file      output file\n");
532                 BIO_printf (bio_err, "-outform arg   output format SMIME (default), PEM or DER\n");
533                 BIO_printf (bio_err, "-content file  supply or override content for detached signature\n");
534                 BIO_printf (bio_err, "-to addr       to address\n");
535                 BIO_printf (bio_err, "-from ad       from address\n");
536                 BIO_printf (bio_err, "-subject s     subject\n");
537                 BIO_printf (bio_err, "-text          include or delete text MIME headers\n");
538                 BIO_printf (bio_err, "-CApath dir    trusted certificates directory\n");
539                 BIO_printf (bio_err, "-CAfile file   trusted certificates file\n");
540                 BIO_printf (bio_err, "-crl_check     check revocation status of signer's certificate using CRLs\n");
541                 BIO_printf (bio_err, "-crl_check_all check revocation status of signer's certificate chain using CRLs\n");
542 #ifndef OPENSSL_NO_ENGINE
543                 BIO_printf (bio_err, "-engine e      use engine e, possibly a hardware device.\n");
544 #endif
545                 BIO_printf (bio_err, "-passin arg    input file pass phrase source\n");
546                 BIO_printf(bio_err,  "-rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
547                 BIO_printf(bio_err,  "               load the file (or the files in the directory) into\n");
548                 BIO_printf(bio_err,  "               the random number generator\n");
549                 BIO_printf (bio_err, "cert.pem       recipient certificate(s) for encryption\n");
550                 goto end;
551                 }
552
553 #ifndef OPENSSL_NO_ENGINE
554         e = setup_engine(bio_err, engine, 0);
555 #endif
556
557         if (!app_passwd(bio_err, passargin, NULL, &passin, NULL))
558                 {
559                 BIO_printf(bio_err, "Error getting password\n");
560                 goto end;
561                 }
562
563         if (need_rand)
564                 {
565                 app_RAND_load_file(NULL, bio_err, (inrand != NULL));
566                 if (inrand != NULL)
567                         BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
568                                 app_RAND_load_files(inrand));
569                 }
570
571         ret = 2;
572
573         if (!(operation & SMIME_SIGNERS))
574                 flags &= ~CMS_DETACHED;
575
576         if (operation & SMIME_OP)
577                 {
578                 if (outformat == FORMAT_ASN1)
579                         outmode = "wb";
580                 }
581         else
582                 {
583                 if (flags & CMS_BINARY)
584                         outmode = "wb";
585                 }
586
587         if (operation & SMIME_IP)
588                 {
589                 if (informat == FORMAT_ASN1)
590                         inmode = "rb";
591                 }
592         else
593                 {
594                 if (flags & CMS_BINARY)
595                         inmode = "rb";
596                 }
597
598         if (operation == SMIME_ENCRYPT)
599                 {
600                 if (!cipher)
601                         {
602 #ifndef OPENSSL_NO_DES                  
603                         cipher = EVP_des_ede3_cbc();
604 #else
605                         BIO_printf(bio_err, "No cipher selected\n");
606                         goto end;
607 #endif
608                         }
609
610                 if (secret_key && !secret_keyid)
611                         {
612                         BIO_printf(bio_err, "No sectre key id\n");
613                         goto end;
614                         }
615
616                 if (*args)
617                         encerts = sk_X509_new_null();
618                 while (*args)
619                         {
620                         if (!(cert = load_cert(bio_err,*args,FORMAT_PEM,
621                                 NULL, e, "recipient certificate file")))
622                                 goto end;
623                         sk_X509_push(encerts, cert);
624                         cert = NULL;
625                         args++;
626                         }
627                 }
628
629         if (certfile)
630                 {
631                 if (!(other = load_certs(bio_err,certfile,FORMAT_PEM, NULL,
632                         e, "certificate file")))
633                         {
634                         ERR_print_errors(bio_err);
635                         goto end;
636                         }
637                 }
638
639         if (recipfile && (operation == SMIME_DECRYPT))
640                 {
641                 if (!(recip = load_cert(bio_err,recipfile,FORMAT_PEM,NULL,
642                         e, "recipient certificate file")))
643                         {
644                         ERR_print_errors(bio_err);
645                         goto end;
646                         }
647                 }
648
649         if (operation == SMIME_DECRYPT)
650                 {
651                 if (!keyfile)
652                         keyfile = recipfile;
653                 }
654         else if (operation == SMIME_SIGN)
655                 {
656                 if (!keyfile)
657                         keyfile = signerfile;
658                 }
659         else keyfile = NULL;
660
661         if (keyfile)
662                 {
663                 key = load_key(bio_err, keyfile, keyform, 0, passin, e,
664                                "signing key file");
665                 if (!key)
666                         goto end;
667                 }
668
669         if (infile)
670                 {
671                 if (!(in = BIO_new_file(infile, inmode)))
672                         {
673                         BIO_printf (bio_err,
674                                  "Can't open input file %s\n", infile);
675                         goto end;
676                         }
677                 }
678         else
679                 in = BIO_new_fp(stdin, BIO_NOCLOSE);
680
681         if (operation & SMIME_IP)
682                 {
683                 if (informat == FORMAT_SMIME) 
684                         cms = SMIME_read_CMS(in, &indata);
685                 else if (informat == FORMAT_PEM) 
686                         cms = PEM_read_bio_CMS(in, NULL, NULL, NULL);
687                 else if (informat == FORMAT_ASN1) 
688                         cms = d2i_CMS_bio(in, NULL);
689                 else
690                         {
691                         BIO_printf(bio_err, "Bad input format for CMS file\n");
692                         goto end;
693                         }
694
695                 if (!cms)
696                         {
697                         BIO_printf(bio_err, "Error reading S/MIME message\n");
698                         goto end;
699                         }
700                 if (contfile)
701                         {
702                         BIO_free(indata);
703                         if (!(indata = BIO_new_file(contfile, "rb")))
704                                 {
705                                 BIO_printf(bio_err, "Can't read content file %s\n", contfile);
706                                 goto end;
707                                 }
708                         }
709                 }
710
711         if (outfile)
712                 {
713                 if (!(out = BIO_new_file(outfile, outmode)))
714                         {
715                         BIO_printf (bio_err,
716                                  "Can't open output file %s\n", outfile);
717                         goto end;
718                         }
719                 }
720         else
721                 {
722                 out = BIO_new_fp(stdout, BIO_NOCLOSE);
723 #ifdef OPENSSL_SYS_VMS
724                 {
725                     BIO *tmpbio = BIO_new(BIO_f_linebuffer());
726                     out = BIO_push(tmpbio, out);
727                 }
728 #endif
729                 }
730
731         if (operation == SMIME_VERIFY)
732                 {
733                 if (!(store = setup_verify(bio_err, CAfile, CApath)))
734                         goto end;
735                 X509_STORE_set_verify_cb_func(store, smime_cb);
736                 if (vpm)
737                         X509_STORE_set1_param(store, vpm);
738                 }
739
740
741         ret = 3;
742
743         if (operation == SMIME_DATA_CREATE)
744                 {
745                 cms = CMS_data_create(in, flags);
746                 }
747         else if (operation == SMIME_DIGEST_CREATE)
748                 {
749                 cms = CMS_digest_create(in, sign_md, flags);
750                 }
751         else if (operation == SMIME_COMPRESS)
752                 {
753                 cms = CMS_compress(in, -1, flags);
754                 }
755         else if (operation == SMIME_ENCRYPT)
756                 {
757                 flags |= CMS_PARTIAL;
758                 cms = CMS_encrypt(encerts, in, cipher, flags);
759                 if (!cms)
760                         goto end;
761                 if (secret_key)
762                         {
763                         if (!CMS_add0_recipient_key(cms, NID_undef, 
764                                                 secret_key, secret_keylen,
765                                                 secret_keyid, secret_keyidlen,
766                                                 NULL, NULL, NULL))
767                                 goto end;
768                         /* NULL these because call absorbs them */
769                         secret_key = NULL;
770                         secret_keyid = NULL;
771                         }
772                 if (!(flags & CMS_STREAM))
773                         {
774                         if (!CMS_final(cms, in, flags))
775                                 goto end;
776                         }
777                 }
778         else if (operation == SMIME_ENCRYPTED_ENCRYPT)
779                 {
780                 cms = CMS_EncryptedData_encrypt(in, cipher,
781                                                 secret_key, secret_keylen,
782                                                 flags);
783
784                 }
785         else if (operation & SMIME_SIGNERS)
786                 {
787                 int i;
788                 /* If detached data content we only enable streaming if
789                  * S/MIME output format.
790                  */
791                 if (operation == SMIME_SIGN)
792                         {
793                         if (flags & CMS_DETACHED)
794                                 {
795                                 if (outformat != FORMAT_SMIME)
796                                         flags &= ~CMS_STREAM;
797                                 }
798                         flags |= CMS_PARTIAL;
799                         cms = CMS_sign(NULL, NULL, other, in, flags);
800                         if (!cms)
801                                 goto end;
802                         }
803                 else
804                         flags |= CMS_REUSE_DIGEST;
805                 for (i = 0; i < sk_num(sksigners); i++)
806                         {
807                         signerfile = sk_value(sksigners, i);
808                         keyfile = sk_value(skkeys, i);
809                         signer = load_cert(bio_err, signerfile,FORMAT_PEM, NULL,
810                                         e, "signer certificate");
811                         if (!signer)
812                                 goto end;
813                         key = load_key(bio_err, keyfile, keyform, 0, passin, e,
814                                "signing key file");
815                         if (!key)
816                                 goto end;
817                         if (!CMS_add1_signer(cms, signer, key, sign_md, flags))
818                                 goto end;
819                         X509_free(signer);
820                         signer = NULL;
821                         EVP_PKEY_free(key);
822                         key = NULL;
823                         }
824                 /* If not streaming or resigning finalize structure */
825                 if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM))
826                         {
827                         if (!CMS_final(cms, in, flags))
828                                 goto end;
829                         }
830                 }
831
832         if (!cms)
833                 {
834                 BIO_printf(bio_err, "Error creating CMS structure\n");
835                 goto end;
836                 }
837
838         ret = 4;
839         if (operation == SMIME_DECRYPT)
840                 {
841
842                 if (secret_key)
843                         {
844                         if (!CMS_decrypt_set1_key(cms,
845                                                 secret_key, secret_keylen,
846                                                 secret_keyid, secret_keyidlen))
847                                 {
848                                 BIO_puts(bio_err,
849                                         "Error decrypting CMS using secret key\n");
850                                 goto end;
851                                 }
852                         }
853
854                 if (key)
855                         {
856                         if (!CMS_decrypt_set1_pkey(cms, key, recip))
857                                 {
858                                 BIO_puts(bio_err,
859                                         "Error decrypting CMS using private key\n");
860                                 goto end;
861                                 }
862                         }
863
864                 if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags))
865                         {
866                         BIO_printf(bio_err, "Error decrypting CMS structure\n");
867                         goto end;
868                         }
869                 }
870         else if (operation == SMIME_DATAOUT)
871                 {
872                 if (!CMS_data(cms, out, flags))
873                         goto end;
874                 }
875         else if (operation == SMIME_UNCOMPRESS)
876                 {
877                 if (!CMS_uncompress(cms, indata, out, flags))
878                         goto end;
879                 }
880         else if (operation == SMIME_DIGEST_VERIFY)
881                 {
882                 if (CMS_digest_verify(cms, indata, out, flags) > 0)
883                         BIO_printf(bio_err, "Verification successful\n");
884                 else
885                         {
886                         BIO_printf(bio_err, "Verification failure\n");
887                         goto end;
888                         }
889                 }
890         else if (operation == SMIME_ENCRYPTED_DECRYPT)
891                 {
892                 if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen,
893                                                 indata, out, flags))
894                         goto end;
895                 }
896         else if (operation == SMIME_VERIFY)
897                 {
898                 if (CMS_verify(cms, other, store, indata, out, flags) > 0)
899                         BIO_printf(bio_err, "Verification successful\n");
900                 else
901                         {
902                         BIO_printf(bio_err, "Verification failure\n");
903                         goto end;
904                         }
905                 if (signerfile)
906                         {
907                         STACK_OF(X509) *signers;
908                         signers = CMS_get0_signers(cms);
909                         if (!save_certs(signerfile, signers))
910                                 {
911                                 BIO_printf(bio_err,
912                                                 "Error writing signers to %s\n",
913                                                                 signerfile);
914                                 ret = 5;
915                                 goto end;
916                                 }
917                         sk_X509_free(signers);
918                         }
919                 }
920         else
921                 {
922                 if (outformat == FORMAT_SMIME) 
923                         {
924                         if (to)
925                                 BIO_printf(out, "To: %s\n", to);
926                         if (from)
927                                 BIO_printf(out, "From: %s\n", from);
928                         if (subject)
929                                 BIO_printf(out, "Subject: %s\n", subject);
930                         if (operation == SMIME_RESIGN)
931                                 ret = SMIME_write_CMS(out, cms, indata, flags);
932                         else
933                                 ret = SMIME_write_CMS(out, cms, in, flags);
934                         }
935                 else if (outformat == FORMAT_PEM) 
936                         ret = PEM_write_bio_CMS_stream(out, cms, in, flags);
937                 else if (outformat == FORMAT_ASN1) 
938                         ret = i2d_CMS_bio_stream(out,cms, in, flags);
939                 else
940                         {
941                         BIO_printf(bio_err, "Bad output format for CMS file\n");
942                         goto end;
943                         }
944                 if (ret <= 0)
945                         {
946                         ret = 6;
947                         goto end;
948                         }
949                 }
950         ret = 0;
951 end:
952         if (ret)
953                 ERR_print_errors(bio_err);
954         if (need_rand)
955                 app_RAND_write_file(NULL, bio_err);
956         sk_X509_pop_free(encerts, X509_free);
957         sk_X509_pop_free(other, X509_free);
958         if (vpm)
959                 X509_VERIFY_PARAM_free(vpm);
960         if (sksigners)
961                 sk_free(sksigners);
962         if (skkeys)
963                 sk_free(skkeys);
964         if (secret_key)
965                 OPENSSL_free(secret_key);
966         if (secret_keyid)
967                 OPENSSL_free(secret_keyid);
968         X509_STORE_free(store);
969         X509_free(cert);
970         X509_free(recip);
971         X509_free(signer);
972         EVP_PKEY_free(key);
973         CMS_ContentInfo_free(cms);
974         BIO_free(in);
975         BIO_free(indata);
976         BIO_free_all(out);
977         if (passin) OPENSSL_free(passin);
978         return (ret);
979 }
980
981 static int save_certs(char *signerfile, STACK_OF(X509) *signers)
982         {
983         int i;
984         BIO *tmp;
985         if (!signerfile)
986                 return 1;
987         tmp = BIO_new_file(signerfile, "w");
988         if (!tmp) return 0;
989         for(i = 0; i < sk_X509_num(signers); i++)
990                 PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
991         BIO_free(tmp);
992         return 1;
993         }
994         
995
996 /* Minimal callback just to output policy info (if any) */
997
998 static int smime_cb(int ok, X509_STORE_CTX *ctx)
999         {
1000         int error;
1001
1002         error = X509_STORE_CTX_get_error(ctx);
1003
1004         if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
1005                 && ((error != X509_V_OK) || (ok != 2)))
1006                 return ok;
1007
1008         policies_print(NULL, ctx);
1009
1010         return ok;
1011
1012         }
1013
1014 #endif