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