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