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