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