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