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