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