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