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