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