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