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