Big apps cleanup (option-parsing, etc)
[openssl.git] / apps / ts.c
1 /*
2  * Written by Zoltan Glozik (zglozik@stones.com) for the OpenSSL project
3  * 2002.
4  */
5 /* ====================================================================
6  * Copyright (c) 2001 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  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include "apps.h"
63 #include <openssl/bio.h>
64 #include <openssl/err.h>
65 #include <openssl/pem.h>
66 #include <openssl/rand.h>
67 #include <openssl/ts.h>
68 #include <openssl/bn.h>
69
70 /* Length of the nonce of the request in bits (must be a multiple of 8). */
71 #define NONCE_LENGTH            64
72
73 /* Macro definitions for the configuration file. */
74 #define ENV_OID_FILE            "oid_file"
75
76 /* Local function declarations. */
77
78 static ASN1_OBJECT *txt2obj(const char *oid);
79 static CONF *load_config_file(const char *configfile);
80
81 /* Query related functions. */
82 static int query_command(const char *data, char *digest,
83                          const EVP_MD *md, const char *policy, int no_nonce,
84                          int cert, const char *in, const char *out, int text);
85 static TS_REQ *create_query(BIO *data_bio, char *digest, const EVP_MD *md,
86                             const char *policy, int no_nonce, int cert);
87 static int create_digest(BIO *input, char *digest,
88                          const EVP_MD *md, unsigned char **md_value);
89 static ASN1_INTEGER *create_nonce(int bits);
90
91 /* Reply related functions. */
92 static int reply_command(CONF *conf, char *section, char *engine,
93                          char *queryfile, char *passin, char *inkey,
94                          char *signer, char *chain, const char *policy,
95                          char *in, int token_in, char *out, int token_out,
96                          int text);
97 static TS_RESP *read_PKCS7(BIO *in_bio);
98 static TS_RESP *create_response(CONF *conf, const char *section, char *engine,
99                                 char *queryfile, char *passin,
100                                 char *inkey, char *signer, char *chain,
101                                 const char *policy);
102 static ASN1_INTEGER *serial_cb(TS_RESP_CTX *ctx, void *data);
103 static ASN1_INTEGER *next_serial(const char *serialfile);
104 static int save_ts_serial(const char *serialfile, ASN1_INTEGER *serial);
105
106 /* Verify related functions. */
107 static int verify_command(char *data, char *digest, char *queryfile,
108                           char *in, int token_in,
109                           char *CApath, char *CAfile, char *untrusted);
110 static TS_VERIFY_CTX *create_verify_ctx(char *data, char *digest,
111                                         char *queryfile,
112                                         char *CApath, char *CAfile,
113                                         char *untrusted);
114 static X509_STORE *create_cert_store(char *CApath, char *CAfile);
115 static int verify_cb(int ok, X509_STORE_CTX *ctx);
116
117 typedef enum OPTION_choice {
118     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
119     OPT_ENGINE, OPT_CONFIG, OPT_SECTION, OPT_QUERY, OPT_DATA,
120     OPT_DIGEST, OPT_RAND, OPT_POLICY, OPT_NO_NONCE, OPT_CERT,
121     OPT_IN, OPT_TOKEN_IN, OPT_OUT, OPT_TOKEN_OUT, OPT_TEXT,
122     OPT_REPLY, OPT_QUERYFILE, OPT_PASSIN, OPT_INKEY, OPT_SIGNER,
123     OPT_CHAIN, OPT_VERIFY, OPT_CAPATH, OPT_CAFILE, OPT_UNTRUSTED,
124     OPT_MD
125 } OPTION_CHOICE;
126
127 OPTIONS ts_options[] = {
128     {"help", OPT_HELP, '-', "Display this summary"},
129     {"config", OPT_CONFIG, '<', "Configuration file"},
130     {"section", OPT_SECTION, 's', "Section to use within config file"},
131     {"query", OPT_QUERY, '-', "Generate a TS query"},
132     {"data", OPT_DATA, '<', "File to hash"},
133     {"digest", OPT_DIGEST, 's', "Digest (as a hex string)"},
134     {"rand", OPT_RAND, 's',
135      "Load the file(s) into the random number generator"},
136     {"policy", OPT_POLICY, 's', "Policy OID to use"},
137     {"no_nonce", OPT_NO_NONCE, '-', "Do not include a nonce"},
138     {"cert", OPT_CERT, '-', "Put cert request into query"},
139     {"in", OPT_IN, '<', "Input file"},
140     {"token_in", OPT_TOKEN_IN, '-', "Input is a PKCS#7 file"},
141     {"out", OPT_OUT, '>', "Output file"},
142     {"token_out", OPT_TOKEN_OUT, '-', "Output is a PKCS#7 file"},
143     {"text", OPT_TEXT, '-', "Output text (not DER)"},
144     {"reply", OPT_REPLY, '-', "Generate a TS reply"},
145     {"queryfile", OPT_QUERYFILE, '<', "File containing a TS query"},
146     {"passin", OPT_PASSIN, 's'},
147     {"inkey", OPT_INKEY, '<', "File with private key for reply"},
148     {"signer", OPT_SIGNER, 's'},
149     {"chain", OPT_CHAIN, '<', "File with signer CA chain"},
150     {"verify", OPT_VERIFY, '-', "Verify a TS response"},
151     {"CApath", OPT_CAPATH, '/', "Path to trusted CA files"},
152     {"CAfile", OPT_CAFILE, '<', "File with trusted CA certs"},
153     {"untrusted", OPT_UNTRUSTED, '<', "File with untrusted certs"},
154 #ifndef OPENSSL_NO_ENGINE
155     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
156 #endif
157     {"", OPT_MD, '-', "Any supported digest"},
158     {NULL}
159 };
160
161 /*
162  * This comand is so complex, special help is needed.
163  */
164 static char* opt_helplist[] = {
165     "Typical uses:",
166     "ts -query [-rand file...] [-config file] [-data file]",
167     "          [-digest hexstring] [-policy oid] [-no_nonce] [-cert]",
168     "          [-in file] [-out file] [-text]",
169     "  or",
170     "ts -reply [-config file] [-section tsa_section]",
171     "          [-queryfile file] [-passin password]",
172     "          [-signer tsa_cert.pem] [-inkey private_key.pem]",
173     "          [-chain certs_file.pem] [-policy oid]",
174     "          [-in file] [-token_in] [-out file] [-token_out]",
175 #ifndef OPENSSL_NO_ENGINE
176     "          [-text]",
177 #else
178     "          [-text] [-engine id]",
179 #endif
180     "  or",
181     "ts -verify -CApath dir -CAfile file.pem -untrusted file.pem",
182     "           [-data file] [-digest hexstring]",
183     "           [-queryfile file] -in file [-token_in]",
184     NULL,
185 };
186
187 int ts_main(int argc, char **argv)
188 {
189     CONF *conf = NULL;
190     char *CAfile = NULL, *untrusted = NULL, *engine = NULL, *prog, **helpp;
191     char *configfile = NULL, *section = NULL, *password = NULL;
192     char *data = NULL, *digest = NULL, *rnd = NULL, *policy = NULL;
193     char *in = NULL, *out = NULL, *queryfile = NULL, *passin = NULL;
194     char *inkey = NULL, *signer = NULL, *chain = NULL, *CApath = NULL;
195     const EVP_MD *md = NULL;
196     OPTION_CHOICE o, mode = OPT_ERR;
197     int ret = 1, no_nonce = 0, cert = 0, text = 0;
198     /* Input is ContentInfo instead of TimeStampResp. */
199     int token_in = 0;
200     /* Output is ContentInfo instead of TimeStampResp. */
201     int token_out = 0;
202
203     prog = opt_init(argc, argv, ts_options);
204     while ((o = opt_next()) != OPT_EOF) {
205         switch (o) {
206         case OPT_EOF:
207         case OPT_ERR:
208  opthelp:
209             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
210             goto end;
211         case OPT_HELP:
212             opt_help(ts_options);
213             for (helpp = opt_helplist; *helpp; ++helpp)
214                 BIO_printf(bio_err, "%s\n", *helpp);
215             ret = 0;
216             goto end;
217         case OPT_CONFIG:
218             configfile = opt_arg();
219             break;
220         case OPT_SECTION:
221             section = opt_arg();
222             break;
223         case OPT_QUERY:
224         case OPT_REPLY:
225         case OPT_VERIFY:
226             if (mode != OPT_ERR)
227                 goto opthelp;
228             mode = o;
229             break;
230         case OPT_DATA:
231             data = opt_arg();
232             break;
233         case OPT_DIGEST:
234             digest = opt_arg();
235             break;
236         case OPT_RAND:
237             rnd = opt_arg();
238             break;
239         case OPT_POLICY:
240             policy = opt_arg();
241             break;
242         case OPT_NO_NONCE:
243             no_nonce = 1;
244             break;
245         case OPT_CERT:
246             cert = 1;
247             break;
248         case OPT_IN:
249             in = opt_arg();
250             break;
251         case OPT_TOKEN_IN:
252             token_in = 1;
253             break;
254         case OPT_OUT:
255             out = opt_arg();
256             break;
257         case OPT_TOKEN_OUT:
258             token_out = 1;
259             break;
260         case OPT_TEXT:
261             text = 1;
262             break;
263         case OPT_QUERYFILE:
264             queryfile = opt_arg();
265             break;
266         case OPT_PASSIN:
267             passin = opt_arg();
268             break;
269         case OPT_INKEY:
270             inkey = opt_arg();
271             break;
272         case OPT_SIGNER:
273             signer = opt_arg();
274             break;
275         case OPT_CHAIN:
276             chain = opt_arg();
277             break;
278         case OPT_CAPATH:
279             CApath = opt_arg();
280             break;
281         case OPT_CAFILE:
282             CAfile = opt_arg();
283             break;
284         case OPT_UNTRUSTED:
285             untrusted = opt_arg();
286             break;
287         case OPT_ENGINE:
288             engine = opt_arg();
289             break;
290         case OPT_MD:
291             if (!opt_md(opt_unknown(), &md))
292                 goto opthelp;
293             break;
294         }
295     }
296     argc = opt_num_rest();
297     argv = opt_rest();
298     if (mode == OPT_ERR || argc != 0)
299         goto opthelp;
300
301     /* Seed the random number generator if it is going to be used. */
302     if (mode == OPT_QUERY && !no_nonce) {
303         if (!app_RAND_load_file(NULL, 1) && rnd == NULL)
304             BIO_printf(bio_err, "warning, not much extra random "
305                        "data, consider using the -rand option\n");
306         if (rnd != NULL)
307             BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
308                        app_RAND_load_files(rnd));
309     }
310
311     /* Get the password if required. */
312     if (mode == OPT_REPLY && passin &&
313         !app_passwd(passin, NULL, &password, NULL)) {
314         BIO_printf(bio_err, "Error getting password.\n");
315         goto end;
316     }
317
318     /*
319      * Check consistency of parameters and execute the appropriate function.
320      */
321     switch (mode) {
322     default:
323     case OPT_ERR:
324         goto opthelp;
325     case OPT_QUERY:
326         /*
327          * Data file and message imprint cannot be specified at the same
328          * time.
329          */
330         ret = data != NULL && digest != NULL;
331         if (ret)
332             goto opthelp;
333         /* Load the config file for possible policy OIDs. */
334         conf = load_config_file(configfile);
335         ret = !query_command(data, digest, md, policy, no_nonce, cert,
336                              in, out, text);
337         break;
338     case OPT_REPLY:
339         conf = load_config_file(configfile);
340         if (in == NULL) {
341             ret = !(queryfile != NULL && conf != NULL && !token_in);
342             if (ret)
343                 goto opthelp;
344         } else {
345             /* 'in' and 'queryfile' are exclusive. */
346             ret = !(queryfile == NULL);
347             if (ret)
348                 goto opthelp;
349         }
350         ret = !reply_command(conf, section, engine, queryfile,
351                              password, inkey, signer, chain, policy,
352                              in, token_in, out, token_out, text);
353         break;
354     case OPT_VERIFY:
355         ret = !(((queryfile && !data && !digest)
356                  || (!queryfile && data && !digest)
357                  || (!queryfile && !data && digest))
358                 && in != NULL);
359         if (ret)
360             goto opthelp;
361
362         ret = !verify_command(data, digest, queryfile, in, token_in,
363                               CApath, CAfile, untrusted);
364     }
365
366  end:
367     /* Clean up. */
368     app_RAND_write_file(NULL);
369     NCONF_free(conf);
370     OPENSSL_free(password);
371     OBJ_cleanup();
372
373     return (ret);
374 }
375
376 /*
377  * Configuration file-related function definitions.
378  */
379
380 static ASN1_OBJECT *txt2obj(const char *oid)
381 {
382     ASN1_OBJECT *oid_obj = NULL;
383
384     if (!(oid_obj = OBJ_txt2obj(oid, 0)))
385         BIO_printf(bio_err, "cannot convert %s to OID\n", oid);
386
387     return oid_obj;
388 }
389
390 static CONF *load_config_file(const char *configfile)
391 {
392     CONF *conf = NULL;
393     long errorline = -1;
394
395     if (!configfile)
396         configfile = getenv("OPENSSL_CONF");
397     if (!configfile)
398         configfile = getenv("SSLEAY_CONF");
399
400     if (configfile &&
401         (!(conf = NCONF_new(NULL)) ||
402          NCONF_load(conf, configfile, &errorline) <= 0)) {
403         if (errorline <= 0)
404             BIO_printf(bio_err, "error loading the config file "
405                        "'%s'\n", configfile);
406         else
407             BIO_printf(bio_err, "error on line %ld of config file "
408                        "'%s'\n", errorline, configfile);
409     }
410
411     if (conf != NULL) {
412         const char *p;
413
414         BIO_printf(bio_err, "Using configuration from %s\n", configfile);
415         p = NCONF_get_string(conf, NULL, ENV_OID_FILE);
416         if (p != NULL) {
417             BIO *oid_bio = BIO_new_file(p, "r");
418             if (!oid_bio)
419                 ERR_print_errors(bio_err);
420             else {
421                 OBJ_create_objects(oid_bio);
422                 BIO_free_all(oid_bio);
423             }
424         } else
425             ERR_clear_error();
426         if (!add_oid_section(conf))
427             ERR_print_errors(bio_err);
428     }
429     return conf;
430 }
431
432 /*
433  * Query-related method definitions.
434  */
435 static int query_command(const char *data, char *digest, const EVP_MD *md,
436                          const char *policy, int no_nonce,
437                          int cert, const char *in, const char *out, int text)
438 {
439     int ret = 0;
440     TS_REQ *query = NULL;
441     BIO *in_bio = NULL;
442     BIO *data_bio = NULL;
443     BIO *out_bio = NULL;
444
445     /* Build query object either from file or from scratch. */
446     if (in != NULL) {
447         if ((in_bio = BIO_new_file(in, "rb")) == NULL)
448             goto end;
449         query = d2i_TS_REQ_bio(in_bio, NULL);
450     } else {
451         /* Open the file if no explicit digest bytes were specified. */
452         if (!digest && !(data_bio = bio_open_default(data, "rb")))
453             goto end;
454         query = create_query(data_bio, digest, md, policy, no_nonce, cert);
455     }
456     if (query == NULL)
457         goto end;
458
459     /* Write query either in ASN.1 or in text format. */
460     if ((out_bio = bio_open_default(out, "wb")) == NULL)
461         goto end;
462     if (text) {
463         /* Text output. */
464         if (!TS_REQ_print_bio(out_bio, query))
465             goto end;
466     } else {
467         /* ASN.1 output. */
468         if (!i2d_TS_REQ_bio(out_bio, query))
469             goto end;
470     }
471
472     ret = 1;
473
474  end:
475     ERR_print_errors(bio_err);
476
477     /* Clean up. */
478     BIO_free_all(in_bio);
479     BIO_free_all(data_bio);
480     BIO_free_all(out_bio);
481     TS_REQ_free(query);
482
483     return ret;
484 }
485
486 static TS_REQ *create_query(BIO *data_bio, char *digest, const EVP_MD *md,
487                             const char *policy, int no_nonce, int cert)
488 {
489     int ret = 0;
490     TS_REQ *ts_req = NULL;
491     int len;
492     TS_MSG_IMPRINT *msg_imprint = NULL;
493     X509_ALGOR *algo = NULL;
494     unsigned char *data = NULL;
495     ASN1_OBJECT *policy_obj = NULL;
496     ASN1_INTEGER *nonce_asn1 = NULL;
497
498     /* Setting default message digest. */
499     if (!md && !(md = EVP_get_digestbyname("sha1")))
500         goto err;
501
502     /* Creating request object. */
503     if (!(ts_req = TS_REQ_new()))
504         goto err;
505
506     /* Setting version. */
507     if (!TS_REQ_set_version(ts_req, 1))
508         goto err;
509
510     /* Creating and adding MSG_IMPRINT object. */
511     if (!(msg_imprint = TS_MSG_IMPRINT_new()))
512         goto err;
513
514     /* Adding algorithm. */
515     if (!(algo = X509_ALGOR_new()))
516         goto err;
517     if (!(algo->algorithm = OBJ_nid2obj(EVP_MD_type(md))))
518         goto err;
519     if (!(algo->parameter = ASN1_TYPE_new()))
520         goto err;
521     algo->parameter->type = V_ASN1_NULL;
522     if (!TS_MSG_IMPRINT_set_algo(msg_imprint, algo))
523         goto err;
524
525     /* Adding message digest. */
526     if ((len = create_digest(data_bio, digest, md, &data)) == 0)
527         goto err;
528     if (!TS_MSG_IMPRINT_set_msg(msg_imprint, data, len))
529         goto err;
530
531     if (!TS_REQ_set_msg_imprint(ts_req, msg_imprint))
532         goto err;
533
534     /* Setting policy if requested. */
535     if (policy && !(policy_obj = txt2obj(policy)))
536         goto err;
537     if (policy_obj && !TS_REQ_set_policy_id(ts_req, policy_obj))
538         goto err;
539
540     /* Setting nonce if requested. */
541     if (!no_nonce && !(nonce_asn1 = create_nonce(NONCE_LENGTH)))
542         goto err;
543     if (nonce_asn1 && !TS_REQ_set_nonce(ts_req, nonce_asn1))
544         goto err;
545
546     /* Setting certificate request flag if requested. */
547     if (!TS_REQ_set_cert_req(ts_req, cert))
548         goto err;
549
550     ret = 1;
551  err:
552     if (!ret) {
553         TS_REQ_free(ts_req);
554         ts_req = NULL;
555         BIO_printf(bio_err, "could not create query\n");
556     }
557     TS_MSG_IMPRINT_free(msg_imprint);
558     X509_ALGOR_free(algo);
559     OPENSSL_free(data);
560     ASN1_OBJECT_free(policy_obj);
561     ASN1_INTEGER_free(nonce_asn1);
562     return ts_req;
563 }
564
565 static int create_digest(BIO *input, char *digest, const EVP_MD *md,
566                          unsigned char **md_value)
567 {
568     int md_value_len;
569
570     md_value_len = EVP_MD_size(md);
571     if (md_value_len < 0)
572         goto err;
573     if (input) {
574         /* Digest must be computed from an input file. */
575         EVP_MD_CTX md_ctx;
576         unsigned char buffer[4096];
577         int length;
578
579         *md_value = OPENSSL_malloc(md_value_len);
580         if (*md_value == 0)
581             goto err;
582
583         EVP_DigestInit(&md_ctx, md);
584         while ((length = BIO_read(input, buffer, sizeof(buffer))) > 0) {
585             EVP_DigestUpdate(&md_ctx, buffer, length);
586         }
587         if (!EVP_DigestFinal(&md_ctx, *md_value, NULL))
588             return 0;
589     } else {
590         /* Digest bytes are specified with digest. */
591         long digest_len;
592         *md_value = string_to_hex(digest, &digest_len);
593         if (!*md_value || md_value_len != digest_len) {
594             OPENSSL_free(*md_value);
595             *md_value = NULL;
596             BIO_printf(bio_err, "bad digest, %d bytes "
597                        "must be specified\n", md_value_len);
598             goto err;
599         }
600     }
601
602     return md_value_len;
603  err:
604     return 0;
605 }
606
607 static ASN1_INTEGER *create_nonce(int bits)
608 {
609     unsigned char buf[20];
610     ASN1_INTEGER *nonce = NULL;
611     int len = (bits - 1) / 8 + 1;
612     int i;
613
614     /* Generating random byte sequence. */
615     if (len > (int)sizeof(buf))
616         goto err;
617     if (RAND_bytes(buf, len) <= 0)
618         goto err;
619
620     /* Find the first non-zero byte and creating ASN1_INTEGER object. */
621     for (i = 0; i < len && !buf[i]; ++i) ;
622     if (!(nonce = ASN1_INTEGER_new()))
623         goto err;
624     OPENSSL_free(nonce->data);
625     /* Allocate at least one byte. */
626     nonce->length = len - i;
627     if (!(nonce->data = OPENSSL_malloc(nonce->length + 1)))
628         goto err;
629     memcpy(nonce->data, buf + i, nonce->length);
630
631     return nonce;
632  err:
633     BIO_printf(bio_err, "could not create nonce\n");
634     ASN1_INTEGER_free(nonce);
635     return NULL;
636 }
637
638 /*
639  * Reply-related method definitions.
640  */
641
642 static int reply_command(CONF *conf, char *section, char *engine,
643                          char *queryfile, char *passin, char *inkey,
644                          char *signer, char *chain, const char *policy,
645                          char *in, int token_in,
646                          char *out, int token_out, int text)
647 {
648     int ret = 0;
649     TS_RESP *response = NULL;
650     BIO *in_bio = NULL;
651     BIO *query_bio = NULL;
652     BIO *inkey_bio = NULL;
653     BIO *signer_bio = NULL;
654     BIO *out_bio = NULL;
655
656     /* Build response object either from response or query. */
657     if (in != NULL) {
658         if ((in_bio = BIO_new_file(in, "rb")) == NULL)
659             goto end;
660         if (token_in) {
661             /*
662              * We have a ContentInfo (PKCS7) object, add 'granted' status
663              * info around it.
664              */
665             response = read_PKCS7(in_bio);
666         } else {
667             /* We have a ready-made TS_RESP object. */
668             response = d2i_TS_RESP_bio(in_bio, NULL);
669         }
670     } else {
671         response = create_response(conf, section, engine, queryfile,
672                                    passin, inkey, signer, chain, policy);
673         if (response)
674             BIO_printf(bio_err, "Response has been generated.\n");
675         else
676             BIO_printf(bio_err, "Response is not generated.\n");
677     }
678     if (response == NULL)
679         goto end;
680
681     /* Write response either in ASN.1 or text format. */
682     if ((out_bio = bio_open_default(out, "wb")) == NULL)
683         goto end;
684     if (text) {
685         /* Text output. */
686         if (token_out) {
687             TS_TST_INFO *tst_info = TS_RESP_get_tst_info(response);
688             if (!TS_TST_INFO_print_bio(out_bio, tst_info))
689                 goto end;
690         } else {
691             if (!TS_RESP_print_bio(out_bio, response))
692                 goto end;
693         }
694     } else {
695         /* ASN.1 DER output. */
696         if (token_out) {
697             PKCS7 *token = TS_RESP_get_token(response);
698             if (!i2d_PKCS7_bio(out_bio, token))
699                 goto end;
700         } else {
701             if (!i2d_TS_RESP_bio(out_bio, response))
702                 goto end;
703         }
704     }
705
706     ret = 1;
707
708  end:
709     ERR_print_errors(bio_err);
710
711     /* Clean up. */
712     BIO_free_all(in_bio);
713     BIO_free_all(query_bio);
714     BIO_free_all(inkey_bio);
715     BIO_free_all(signer_bio);
716     BIO_free_all(out_bio);
717     TS_RESP_free(response);
718
719     return ret;
720 }
721
722 /* Reads a PKCS7 token and adds default 'granted' status info to it. */
723 static TS_RESP *read_PKCS7(BIO *in_bio)
724 {
725     int ret = 0;
726     PKCS7 *token = NULL;
727     TS_TST_INFO *tst_info = NULL;
728     TS_RESP *resp = NULL;
729     TS_STATUS_INFO *si = NULL;
730
731     /* Read PKCS7 object and extract the signed time stamp info. */
732     if (!(token = d2i_PKCS7_bio(in_bio, NULL)))
733         goto end;
734     if (!(tst_info = PKCS7_to_TS_TST_INFO(token)))
735         goto end;
736
737     /* Creating response object. */
738     if (!(resp = TS_RESP_new()))
739         goto end;
740
741     /* Create granted status info. */
742     if (!(si = TS_STATUS_INFO_new()))
743         goto end;
744     if (!(ASN1_INTEGER_set(si->status, TS_STATUS_GRANTED)))
745         goto end;
746     if (!TS_RESP_set_status_info(resp, si))
747         goto end;
748
749     /* Setting encapsulated token. */
750     TS_RESP_set_tst_info(resp, token, tst_info);
751     token = NULL;               /* Ownership is lost. */
752     tst_info = NULL;            /* Ownership is lost. */
753
754     ret = 1;
755  end:
756     PKCS7_free(token);
757     TS_TST_INFO_free(tst_info);
758     if (!ret) {
759         TS_RESP_free(resp);
760         resp = NULL;
761     }
762     TS_STATUS_INFO_free(si);
763     return resp;
764 }
765
766 static TS_RESP *create_response(CONF *conf, const char *section, char *engine,
767                                 char *queryfile, char *passin,
768                                 char *inkey, char *signer, char *chain,
769                                 const char *policy)
770 {
771     int ret = 0;
772     TS_RESP *response = NULL;
773     BIO *query_bio = NULL;
774     TS_RESP_CTX *resp_ctx = NULL;
775
776     if (!(query_bio = BIO_new_file(queryfile, "rb")))
777         goto end;
778
779     /* Getting TSA configuration section. */
780     if (!(section = TS_CONF_get_tsa_section(conf, section)))
781         goto end;
782
783     /* Setting up response generation context. */
784     if (!(resp_ctx = TS_RESP_CTX_new()))
785         goto end;
786
787     /* Setting serial number provider callback. */
788     if (!TS_CONF_set_serial(conf, section, serial_cb, resp_ctx))
789         goto end;
790 #ifndef OPENSSL_NO_ENGINE
791     /* Setting default OpenSSL engine. */
792     if (!TS_CONF_set_crypto_device(conf, section, engine))
793         goto end;
794 #endif
795
796     /* Setting TSA signer certificate. */
797     if (!TS_CONF_set_signer_cert(conf, section, signer, resp_ctx))
798         goto end;
799
800     /* Setting TSA signer certificate chain. */
801     if (!TS_CONF_set_certs(conf, section, chain, resp_ctx))
802         goto end;
803
804     /* Setting TSA signer private key. */
805     if (!TS_CONF_set_signer_key(conf, section, inkey, passin, resp_ctx))
806         goto end;
807
808     /* Setting default policy OID. */
809     if (!TS_CONF_set_def_policy(conf, section, policy, resp_ctx))
810         goto end;
811
812     /* Setting acceptable policy OIDs. */
813     if (!TS_CONF_set_policies(conf, section, resp_ctx))
814         goto end;
815
816     /* Setting the acceptable one-way hash algorithms. */
817     if (!TS_CONF_set_digests(conf, section, resp_ctx))
818         goto end;
819
820     /* Setting guaranteed time stamp accuracy. */
821     if (!TS_CONF_set_accuracy(conf, section, resp_ctx))
822         goto end;
823
824     /* Setting the precision of the time. */
825     if (!TS_CONF_set_clock_precision_digits(conf, section, resp_ctx))
826         goto end;
827
828     /* Setting the ordering flaf if requested. */
829     if (!TS_CONF_set_ordering(conf, section, resp_ctx))
830         goto end;
831
832     /* Setting the TSA name required flag if requested. */
833     if (!TS_CONF_set_tsa_name(conf, section, resp_ctx))
834         goto end;
835
836     /* Setting the ESS cert id chain flag if requested. */
837     if (!TS_CONF_set_ess_cert_id_chain(conf, section, resp_ctx))
838         goto end;
839
840     /* Creating the response. */
841     if (!(response = TS_RESP_create_response(resp_ctx, query_bio)))
842         goto end;
843
844     ret = 1;
845  end:
846     if (!ret) {
847         TS_RESP_free(response);
848         response = NULL;
849     }
850     TS_RESP_CTX_free(resp_ctx);
851     BIO_free_all(query_bio);
852
853     return response;
854 }
855
856 static ASN1_INTEGER *serial_cb(TS_RESP_CTX *ctx, void *data)
857 {
858     const char *serial_file = (const char *)data;
859     ASN1_INTEGER *serial = next_serial(serial_file);
860
861     if (!serial) {
862         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
863                                     "Error during serial number "
864                                     "generation.");
865         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_ADD_INFO_NOT_AVAILABLE);
866     } else
867         save_ts_serial(serial_file, serial);
868
869     return serial;
870 }
871
872 static ASN1_INTEGER *next_serial(const char *serialfile)
873 {
874     int ret = 0;
875     BIO *in = NULL;
876     ASN1_INTEGER *serial = NULL;
877     BIGNUM *bn = NULL;
878
879     if (!(serial = ASN1_INTEGER_new()))
880         goto err;
881
882     if (!(in = BIO_new_file(serialfile, "r"))) {
883         ERR_clear_error();
884         BIO_printf(bio_err, "Warning: could not open file %s for "
885                    "reading, using serial number: 1\n", serialfile);
886         if (!ASN1_INTEGER_set(serial, 1))
887             goto err;
888     } else {
889         char buf[1024];
890         if (!a2i_ASN1_INTEGER(in, serial, buf, sizeof(buf))) {
891             BIO_printf(bio_err, "unable to load number from %s\n",
892                        serialfile);
893             goto err;
894         }
895         if (!(bn = ASN1_INTEGER_to_BN(serial, NULL)))
896             goto err;
897         ASN1_INTEGER_free(serial);
898         serial = NULL;
899         if (!BN_add_word(bn, 1))
900             goto err;
901         if (!(serial = BN_to_ASN1_INTEGER(bn, NULL)))
902             goto err;
903     }
904     ret = 1;
905  err:
906     if (!ret) {
907         ASN1_INTEGER_free(serial);
908         serial = NULL;
909     }
910     BIO_free_all(in);
911     BN_free(bn);
912     return serial;
913 }
914
915 static int save_ts_serial(const char *serialfile, ASN1_INTEGER *serial)
916 {
917     int ret = 0;
918     BIO *out = NULL;
919
920     if (!(out = BIO_new_file(serialfile, "w")))
921         goto err;
922     if (i2a_ASN1_INTEGER(out, serial) <= 0)
923         goto err;
924     if (BIO_puts(out, "\n") <= 0)
925         goto err;
926     ret = 1;
927  err:
928     if (!ret)
929         BIO_printf(bio_err, "could not save serial number to %s\n",
930                    serialfile);
931     BIO_free_all(out);
932     return ret;
933 }
934
935 /*
936  * Verify-related method definitions.
937  */
938
939 static int verify_command(char *data, char *digest, char *queryfile,
940                           char *in, int token_in,
941                           char *CApath, char *CAfile, char *untrusted)
942 {
943     BIO *in_bio = NULL;
944     PKCS7 *token = NULL;
945     TS_RESP *response = NULL;
946     TS_VERIFY_CTX *verify_ctx = NULL;
947     int ret = 0;
948
949     /* Decode the token (PKCS7) or response (TS_RESP) files. */
950     if (!(in_bio = BIO_new_file(in, "rb")))
951         goto end;
952     if (token_in) {
953         if (!(token = d2i_PKCS7_bio(in_bio, NULL)))
954             goto end;
955     } else {
956         if (!(response = d2i_TS_RESP_bio(in_bio, NULL)))
957             goto end;
958     }
959
960     if (!(verify_ctx = create_verify_ctx(data, digest, queryfile,
961                                          CApath, CAfile, untrusted)))
962         goto end;
963
964     /* Checking the token or response against the request. */
965     ret = token_in ?
966         TS_RESP_verify_token(verify_ctx, token) :
967         TS_RESP_verify_response(verify_ctx, response);
968
969  end:
970     printf("Verification: ");
971     if (ret)
972         printf("OK\n");
973     else {
974         printf("FAILED\n");
975         /* Print errors, if there are any. */
976         ERR_print_errors(bio_err);
977     }
978
979     /* Clean up. */
980     BIO_free_all(in_bio);
981     PKCS7_free(token);
982     TS_RESP_free(response);
983     TS_VERIFY_CTX_free(verify_ctx);
984     return ret;
985 }
986
987 static TS_VERIFY_CTX *create_verify_ctx(char *data, char *digest,
988                                         char *queryfile,
989                                         char *CApath, char *CAfile,
990                                         char *untrusted)
991 {
992     TS_VERIFY_CTX *ctx = NULL;
993     BIO *input = NULL;
994     TS_REQ *request = NULL;
995     int ret = 0;
996
997     if (data != NULL || digest != NULL) {
998         if (!(ctx = TS_VERIFY_CTX_new()))
999             goto err;
1000         ctx->flags = TS_VFY_VERSION | TS_VFY_SIGNER;
1001         if (data != NULL) {
1002             ctx->flags |= TS_VFY_DATA;
1003             if (!(ctx->data = BIO_new_file(data, "rb")))
1004                 goto err;
1005         } else if (digest != NULL) {
1006             long imprint_len;
1007             ctx->flags |= TS_VFY_IMPRINT;
1008             if (!(ctx->imprint = string_to_hex(digest, &imprint_len))) {
1009                 BIO_printf(bio_err, "invalid digest string\n");
1010                 goto err;
1011             }
1012             ctx->imprint_len = imprint_len;
1013         }
1014
1015     } else if (queryfile != NULL) {
1016         /*
1017          * The request has just to be read, decoded and converted to a verify
1018          * context object.
1019          */
1020         if (!(input = BIO_new_file(queryfile, "rb")))
1021             goto err;
1022         if (!(request = d2i_TS_REQ_bio(input, NULL)))
1023             goto err;
1024         if (!(ctx = TS_REQ_to_TS_VERIFY_CTX(request, NULL)))
1025             goto err;
1026     } else
1027         return NULL;
1028
1029     /* Add the signature verification flag and arguments. */
1030     ctx->flags |= TS_VFY_SIGNATURE;
1031
1032     /* Initialising the X509_STORE object. */
1033     if (!(ctx->store = create_cert_store(CApath, CAfile)))
1034         goto err;
1035
1036     /* Loading untrusted certificates. */
1037     if (untrusted && !(ctx->certs = TS_CONF_load_certs(untrusted)))
1038         goto err;
1039
1040     ret = 1;
1041  err:
1042     if (!ret) {
1043         TS_VERIFY_CTX_free(ctx);
1044         ctx = NULL;
1045     }
1046     BIO_free_all(input);
1047     TS_REQ_free(request);
1048     return ctx;
1049 }
1050
1051 static X509_STORE *create_cert_store(char *CApath, char *CAfile)
1052 {
1053     X509_STORE *cert_ctx = NULL;
1054     X509_LOOKUP *lookup = NULL;
1055     int i;
1056
1057     /* Creating the X509_STORE object. */
1058     cert_ctx = X509_STORE_new();
1059
1060     /* Setting the callback for certificate chain verification. */
1061     X509_STORE_set_verify_cb(cert_ctx, verify_cb);
1062
1063     /* Adding a trusted certificate directory source. */
1064     if (CApath) {
1065         lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir());
1066         if (lookup == NULL) {
1067             BIO_printf(bio_err, "memory allocation failure\n");
1068             goto err;
1069         }
1070         i = X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM);
1071         if (!i) {
1072             BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1073             goto err;
1074         }
1075     }
1076
1077     /* Adding a trusted certificate file source. */
1078     if (CAfile) {
1079         lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());
1080         if (lookup == NULL) {
1081             BIO_printf(bio_err, "memory allocation failure\n");
1082             goto err;
1083         }
1084         i = X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM);
1085         if (!i) {
1086             BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1087             goto err;
1088         }
1089     }
1090
1091     return cert_ctx;
1092  err:
1093     X509_STORE_free(cert_ctx);
1094     return NULL;
1095 }
1096
1097 static int verify_cb(int ok, X509_STORE_CTX *ctx)
1098 {
1099     return ok;
1100 }