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