xref: /openbsd/usr.bin/openssl/ts.c (revision d415bd75)
1 /* $OpenBSD: ts.c,v 1.26 2023/03/06 14:32:06 tb Exp $ */
2 /* Written by Zoltan Glozik (zglozik@stones.com) for the OpenSSL
3  * project 2002.
4  */
5 /* ====================================================================
6  * Copyright (c) 2001 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58 
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 
63 #include "apps.h"
64 
65 #include <openssl/bio.h>
66 #include <openssl/bn.h>
67 #include <openssl/err.h>
68 #include <openssl/pem.h>
69 #include <openssl/ts.h>
70 
71 /* Length of the nonce of the request in bits (must be a multiple of 8). */
72 #define	NONCE_LENGTH		64
73 
74 /* Macro definitions for the configuration file. */
75 #define	ENV_OID_FILE		"oid_file"
76 
77 /* Local function declarations. */
78 
79 static ASN1_OBJECT *txt2obj(const char *oid);
80 static CONF *load_config_file(const char *configfile);
81 
82 /* Query related functions. */
83 static int query_command(const char *data, char *digest, const EVP_MD *md,
84     const char *policy, int no_nonce, int cert, const char *in, const char *out,
85     int text);
86 static BIO *BIO_open_with_default(const char *file, const char *mode,
87     FILE *default_fp);
88 static TS_REQ *create_query(BIO *data_bio, char *digest, const EVP_MD *md,
89     const char *policy, int no_nonce, int cert);
90 static int create_digest(BIO *input, char *digest, const EVP_MD *md,
91     unsigned char **md_value);
92 static ASN1_INTEGER *create_nonce(int bits);
93 
94 /* Reply related functions. */
95 static int reply_command(CONF *conf, char *section, char *queryfile,
96     char *passin, char *inkey, char *signer, char *chain, const char *policy,
97     char *in, int token_in, char *out, int token_out, int text);
98 static TS_RESP *read_PKCS7(BIO *in_bio);
99 static TS_RESP *create_response(CONF *conf, const char *section,
100     char *queryfile, char *passin, char *inkey, char *signer, char *chain,
101     const char *policy);
102 static ASN1_INTEGER *serial_cb(TS_RESP_CTX *ctx, void *data);
103 static ASN1_INTEGER *next_serial(const char *serialfile);
104 static int save_ts_serial(const char *serialfile, ASN1_INTEGER *serial);
105 
106 /* Verify related functions. */
107 static int verify_command(char *data, char *digest, char *queryfile, char *in,
108     int token_in, char *ca_path, char *ca_file, char *untrusted);
109 static TS_VERIFY_CTX *create_verify_ctx(char *data, char *digest,
110     char *queryfile, char *ca_path, char *ca_file, char *untrusted);
111 static X509_STORE *create_cert_store(char *ca_path, char *ca_file);
112 static int verify_cb(int ok, X509_STORE_CTX *ctx);
113 
114 enum mode {
115 	CMD_NONE, CMD_QUERY, CMD_REPLY, CMD_VERIFY
116 };
117 
118 static struct {
119 	char *ca_file;
120 	char *ca_path;
121 	int cert;
122 	char *chain;
123 	char *configfile;
124 	char *data;
125 	char *digest;
126 	char *in;
127 	char *inkey;
128 	const EVP_MD *md;
129 	int mode;
130 	int no_nonce;
131 	char *out;
132 	char *passin;
133 	char *policy;
134 	char *queryfile;
135 	char *section;
136 	char *signer;
137 	int text;
138 	int token_in;
139 	int token_out;
140 	char *untrusted;
141 } cfg;
142 
143 static int
144 ts_opt_md(int argc, char **argv, int *argsused)
145 {
146 	char *name = argv[0];
147 
148 	if (*name++ != '-')
149 		return (1);
150 
151 	if ((cfg.md = EVP_get_digestbyname(name)) == NULL)
152 		return (1);
153 
154 	*argsused = 1;
155 	return (0);
156 }
157 
158 static int
159 ts_opt_query(void)
160 {
161 	if (cfg.mode != CMD_NONE)
162 		return (1);
163 	cfg.mode = CMD_QUERY;
164 	return (0);
165 }
166 
167 static int
168 ts_opt_reply(void)
169 {
170 	if (cfg.mode != CMD_NONE)
171 		return (1);
172 	cfg.mode = CMD_REPLY;
173 	return (0);
174 }
175 
176 static int
177 ts_opt_verify(void)
178 {
179 	if (cfg.mode != CMD_NONE)
180 		return (1);
181 	cfg.mode = CMD_VERIFY;
182 	return (0);
183 }
184 
185 static const struct option ts_options[] = {
186 	{
187 		.name = "CAfile",
188 		.argname = "file",
189 		.desc = "Certificate Authority file",
190 		.type = OPTION_ARG,
191 		.opt.arg = &cfg.ca_file,
192 	},
193 	{
194 		.name = "CApath",
195 		.argname = "path",
196 		.desc = "Certificate Authority path",
197 		.type = OPTION_ARG,
198 		.opt.arg = &cfg.ca_path,
199 	},
200 	{
201 		.name = "cert",
202 		.desc = "Include signing certificate in the response",
203 		.type = OPTION_FLAG,
204 		.opt.flag = &cfg.cert,
205 	},
206 	{
207 		.name = "chain",
208 		.argname = "file",
209 		.desc = "PEM certificates that will be included in the response",
210 		.type = OPTION_ARG,
211 		.opt.arg = &cfg.chain,
212 	},
213 	{
214 		.name = "config",
215 		.argname = "file",
216 		.desc = "Specify an alternative configuration file",
217 		.type = OPTION_ARG,
218 		.opt.arg = &cfg.configfile,
219 	},
220 	{
221 		.name = "data",
222 		.argname = "file",
223 		.desc = "Data file for which the time stamp request needs to be created",
224 		.type = OPTION_ARG,
225 		.opt.arg = &cfg.data,
226 	},
227 	{
228 		.name = "digest",
229 		.argname = "arg",
230 		.desc = "Specify the message imprint explicitly without the data file",
231 		.type = OPTION_ARG,
232 		.opt.arg = &cfg.digest,
233 	},
234 	{
235 		.name = "in",
236 		.argname = "file",
237 		.desc = "Input file",
238 		.type = OPTION_ARG,
239 		.opt.arg = &cfg.in,
240 	},
241 	{
242 		.name = "inkey",
243 		.argname = "file",
244 		.desc = "Input key file",
245 		.type = OPTION_ARG,
246 		.opt.arg = &cfg.inkey,
247 	},
248 	{
249 		.name = "no_nonce",
250 		.desc = "Specify no nonce in the request",
251 		.type = OPTION_FLAG,
252 		.opt.flag = &cfg.no_nonce,
253 	},
254 	{
255 		.name = "out",
256 		.argname = "file",
257 		.desc = "Output file",
258 		.type = OPTION_ARG,
259 		.opt.arg = &cfg.out,
260 	},
261 	{
262 		.name = "passin",
263 		.argname = "src",
264 		.desc = "Private key password source",
265 		.type = OPTION_ARG,
266 		.opt.arg = &cfg.passin,
267 	},
268 	{
269 		.name = "policy",
270 		.argname = "object_id",
271 		.desc = "Policy for the TSA to use when creating the time stamp token",
272 		.type = OPTION_ARG,
273 		.opt.arg = &cfg.policy,
274 	},
275 	{
276 		.name = "query",
277 		.desc = "Create and print a time stamp request",
278 		.type = OPTION_FUNC,
279 		.opt.func = ts_opt_query,
280 	},
281 	{
282 		.name = "queryfile",
283 		.argname = "file",
284 		.desc = "File containing a DER-encoded time stamp request",
285 		.type = OPTION_ARG,
286 		.opt.arg = &cfg.queryfile,
287 	},
288 	{
289 		.name = "reply",
290 		.desc = "Create a time stamp response",
291 		.type = OPTION_FUNC,
292 		.opt.func = ts_opt_reply,
293 	},
294 	{
295 		.name = "section",
296 		.argname = "arg",
297 		.desc = "TSA section containing the settings for response generation",
298 		.type = OPTION_ARG,
299 		.opt.arg = &cfg.section,
300 	},
301 	{
302 		.name = "signer",
303 		.argname = "file",
304 		.desc = "Signer certificate file",
305 		.type = OPTION_ARG,
306 		.opt.arg = &cfg.signer,
307 	},
308 	{
309 		.name = "text",
310 		.desc = "Output in human-readable text format",
311 		.type = OPTION_FLAG,
312 		.opt.flag = &cfg.text,
313 	},
314 	{
315 		.name = "token_in",
316 		.desc = "Input is a DER-encoded time stamp token",
317 		.type = OPTION_FLAG,
318 		.opt.flag = &cfg.token_in,
319 	},
320 	{
321 		.name = "token_out",
322 		.desc = "Output is a DER-encoded time stamp token",
323 		.type = OPTION_FLAG,
324 		.opt.flag = &cfg.token_out,
325 	},
326 	{
327 		.name = "untrusted",
328 		.argname = "file",
329 		.desc = "File containing untrusted certificates",
330 		.type = OPTION_ARG,
331 		.opt.arg = &cfg.untrusted,
332 	},
333 	{
334 		.name = "verify",
335 		.desc = "Verify a time stamp response",
336 		.type = OPTION_FUNC,
337 		.opt.func = ts_opt_verify,
338 	},
339 	{
340 		.name = NULL,
341 		.desc = "",
342 		.type = OPTION_ARGV_FUNC,
343 		.opt.argvfunc = ts_opt_md,
344 	},
345 	{ NULL },
346 };
347 
348 static void
349 ts_usage(void)
350 {
351 	fprintf(stderr, "usage:\n"
352 	    "ts -query [-md4 | -md5 | -ripemd160 | -sha1] [-cert]\n"
353 	    "    [-config configfile] [-data file_to_hash]\n"
354 	    "    [-digest digest_bytes] [-in request.tsq] [-no_nonce]\n"
355 	    "    [-out request.tsq] [-policy object_id] [-text]\n");
356 	fprintf(stderr, "\n"
357 	    "ts -reply [-chain certs_file.pem] [-config configfile]\n"
358 	    "    [-in response.tsr] [-inkey private.pem] [-out response.tsr]\n"
359 	    "    [-passin arg] [-policy object_id] [-queryfile request.tsq]\n"
360 	    "    [-section tsa_section] [-signer tsa_cert.pem] [-text]\n"
361 	    "    [-token_in] [-token_out]\n");
362 	fprintf(stderr, "\n"
363 	    "ts -verify [-CAfile trusted_certs.pem]\n"
364 	    "    [-CApath trusted_cert_path] [-data file_to_hash]\n"
365 	    "    [-digest digest_bytes] [-in response.tsr]\n"
366 	    "    [-queryfile request.tsq] [-token_in]\n"
367 	    "    [-untrusted cert_file.pem]\n");
368 	fprintf(stderr, "\n");
369 	options_usage(ts_options);
370 	fprintf(stderr, "\n");
371 }
372 
373 int
374 ts_main(int argc, char **argv)
375 {
376 	int ret = 1;
377 	CONF *conf = NULL;
378 	char *password = NULL;	/* Password itself. */
379 
380 	if (pledge("stdio cpath wpath rpath tty", NULL) == -1) {
381 		perror("pledge");
382 		exit(1);
383 	}
384 
385 	memset(&cfg, 0, sizeof(cfg));
386 	cfg.mode = CMD_NONE;
387 
388 	if (options_parse(argc, argv, ts_options, NULL, NULL) != 0)
389 		goto usage;
390 
391 	/* Get the password if required. */
392 	if (cfg.mode == CMD_REPLY && cfg.passin != NULL &&
393 	    !app_passwd(bio_err, cfg.passin, NULL, &password, NULL)) {
394 		BIO_printf(bio_err, "Error getting password.\n");
395 		goto cleanup;
396 	}
397 	/*
398 	 * Check consistency of parameters and execute the appropriate
399 	 * function.
400 	 */
401 	switch (cfg.mode) {
402 	case CMD_NONE:
403 		goto usage;
404 	case CMD_QUERY:
405 		/*
406 		 * Data file and message imprint cannot be specified at the
407 		 * same time.
408 		 */
409 		ret = cfg.data != NULL && cfg.digest != NULL;
410 		if (ret)
411 			goto usage;
412 		/* Load the config file for possible policy OIDs. */
413 		conf = load_config_file(cfg.configfile);
414 		ret = !query_command(cfg.data, cfg.digest,
415 		    cfg.md, cfg.policy, cfg.no_nonce,
416 		    cfg.cert, cfg.in, cfg.out,
417 		    cfg.text);
418 		break;
419 	case CMD_REPLY:
420 		conf = load_config_file(cfg.configfile);
421 		if (cfg.in == NULL) {
422 			ret = !(cfg.queryfile != NULL && conf != NULL &&
423 			    !cfg.token_in);
424 			if (ret)
425 				goto usage;
426 		} else {
427 			/* 'in' and 'queryfile' are exclusive. */
428 			ret = !(cfg.queryfile == NULL);
429 			if (ret)
430 				goto usage;
431 		}
432 
433 		ret = !reply_command(conf, cfg.section,
434 		    cfg.queryfile, password, cfg.inkey,
435 		    cfg.signer, cfg.chain, cfg.policy,
436 		    cfg.in, cfg.token_in, cfg.out,
437 		    cfg.token_out, cfg.text);
438 		break;
439 	case CMD_VERIFY:
440 		ret = !(((cfg.queryfile != NULL && cfg.data == NULL &&
441 		    cfg.digest == NULL) ||
442 		    (cfg.queryfile == NULL && cfg.data != NULL &&
443 		    cfg.digest == NULL) ||
444 		    (cfg.queryfile == NULL && cfg.data == NULL &&
445 		    cfg.digest != NULL)) &&
446 		    cfg.in != NULL);
447 		if (ret)
448 			goto usage;
449 
450 		ret = !verify_command(cfg.data, cfg.digest,
451 		    cfg.queryfile, cfg.in, cfg.token_in,
452 		    cfg.ca_path, cfg.ca_file, cfg.untrusted);
453 	}
454 
455 	goto cleanup;
456 
457  usage:
458 	ts_usage();
459 
460  cleanup:
461 	/* Clean up. */
462 	NCONF_free(conf);
463 	free(password);
464 	OBJ_cleanup();
465 
466 	return (ret);
467 }
468 
469 /*
470  * Configuration file-related function definitions.
471  */
472 
473 static ASN1_OBJECT *
474 txt2obj(const char *oid)
475 {
476 	ASN1_OBJECT *oid_obj = NULL;
477 
478 	if ((oid_obj = OBJ_txt2obj(oid, 0)) == NULL)
479 		BIO_printf(bio_err, "cannot convert %s to OID\n", oid);
480 
481 	return oid_obj;
482 }
483 
484 static CONF *
485 load_config_file(const char *configfile)
486 {
487 	CONF *conf = NULL;
488 	long errorline = -1;
489 
490 	if (configfile == NULL)
491 		configfile = getenv("OPENSSL_CONF");
492 
493 	if (configfile != NULL &&
494 	    ((conf = NCONF_new(NULL)) == NULL ||
495 	    NCONF_load(conf, configfile, &errorline) <= 0)) {
496 		if (errorline <= 0)
497 			BIO_printf(bio_err, "error loading the config file "
498 			    "'%s'\n", configfile);
499 		else
500 			BIO_printf(bio_err, "error on line %ld of config file "
501 			    "'%s'\n", errorline, configfile);
502 	}
503 	if (conf != NULL) {
504 		const char *p;
505 
506 		BIO_printf(bio_err, "Using configuration from %s\n",
507 		    configfile);
508 		p = NCONF_get_string(conf, NULL, ENV_OID_FILE);
509 		if (p != NULL) {
510 			BIO *oid_bio = BIO_new_file(p, "r");
511 			if (oid_bio == NULL)
512 				ERR_print_errors(bio_err);
513 			else {
514 				OBJ_create_objects(oid_bio);
515 				BIO_free_all(oid_bio);
516 			}
517 		} else
518 			ERR_clear_error();
519 		if (!add_oid_section(bio_err, conf))
520 			ERR_print_errors(bio_err);
521 	}
522 	return conf;
523 }
524 
525 /*
526  * Query-related method definitions.
527  */
528 
529 static int
530 query_command(const char *data, char *digest, const EVP_MD *md,
531     const char *policy, int no_nonce, int cert, const char *in, const char *out,
532     int text)
533 {
534 	int ret = 0;
535 	TS_REQ *query = NULL;
536 	BIO *in_bio = NULL;
537 	BIO *data_bio = NULL;
538 	BIO *out_bio = NULL;
539 
540 	/* Build query object either from file or from scratch. */
541 	if (in != NULL) {
542 		if ((in_bio = BIO_new_file(in, "rb")) == NULL)
543 			goto end;
544 		query = d2i_TS_REQ_bio(in_bio, NULL);
545 	} else {
546 		/* Open the file if no explicit digest bytes were specified. */
547 		if (digest == NULL &&
548 		    (data_bio = BIO_open_with_default(data, "rb", stdin)) == NULL)
549 			goto end;
550 		/* Creating the query object. */
551 		query = create_query(data_bio, digest, md,
552 		    policy, no_nonce, cert);
553 		/* Saving the random number generator state. */
554 	}
555 	if (query == NULL)
556 		goto end;
557 
558 	/* Write query either in ASN.1 or in text format. */
559 	if ((out_bio = BIO_open_with_default(out, "wb", stdout)) == NULL)
560 		goto end;
561 	if (text) {
562 		/* Text output. */
563 		if (!TS_REQ_print_bio(out_bio, query))
564 			goto end;
565 	} else {
566 		/* ASN.1 output. */
567 		if (!i2d_TS_REQ_bio(out_bio, query))
568 			goto end;
569 	}
570 
571 	ret = 1;
572 
573  end:
574 	ERR_print_errors(bio_err);
575 
576 	/* Clean up. */
577 	BIO_free_all(in_bio);
578 	BIO_free_all(data_bio);
579 	BIO_free_all(out_bio);
580 	TS_REQ_free(query);
581 
582 	return ret;
583 }
584 
585 static BIO *
586 BIO_open_with_default(const char *file, const char *mode, FILE *default_fp)
587 {
588 	return file == NULL ? BIO_new_fp(default_fp, BIO_NOCLOSE) :
589 	    BIO_new_file(file, mode);
590 }
591 
592 static TS_REQ *
593 create_query(BIO *data_bio, char *digest, const EVP_MD *md, const char *policy,
594     int no_nonce, int cert)
595 {
596 	int ret = 0;
597 	TS_REQ *ts_req = NULL;
598 	int len;
599 	TS_MSG_IMPRINT *msg_imprint = NULL;
600 	X509_ALGOR *algo = NULL;
601 	unsigned char *data = NULL;
602 	ASN1_OBJECT *policy_obj = NULL;
603 	ASN1_INTEGER *nonce_asn1 = NULL;
604 
605 	/* Setting default message digest. */
606 	if (md == NULL && (md = EVP_get_digestbyname("sha1")) == NULL)
607 		goto err;
608 
609 	/* Creating request object. */
610 	if ((ts_req = TS_REQ_new()) == NULL)
611 		goto err;
612 
613 	/* Setting version. */
614 	if (!TS_REQ_set_version(ts_req, 1))
615 		goto err;
616 
617 	/* Creating and adding MSG_IMPRINT object. */
618 	if ((msg_imprint = TS_MSG_IMPRINT_new()) == NULL)
619 		goto err;
620 
621 	/* Adding algorithm. */
622 	if ((algo = X509_ALGOR_new()) == NULL)
623 		goto err;
624 	if ((algo->algorithm = OBJ_nid2obj(EVP_MD_type(md))) == NULL)
625 		goto err;
626 	if ((algo->parameter = ASN1_TYPE_new()) == NULL)
627 		goto err;
628 	algo->parameter->type = V_ASN1_NULL;
629 	if (!TS_MSG_IMPRINT_set_algo(msg_imprint, algo))
630 		goto err;
631 
632 	/* Adding message digest. */
633 	if ((len = create_digest(data_bio, digest, md, &data)) == 0)
634 		goto err;
635 	if (!TS_MSG_IMPRINT_set_msg(msg_imprint, data, len))
636 		goto err;
637 
638 	if (!TS_REQ_set_msg_imprint(ts_req, msg_imprint))
639 		goto err;
640 
641 	/* Setting policy if requested. */
642 	if (policy != NULL && (policy_obj = txt2obj(policy)) == NULL)
643 		goto err;
644 	if (policy_obj != NULL && !TS_REQ_set_policy_id(ts_req, policy_obj))
645 		goto err;
646 
647 	/* Setting nonce if requested. */
648 	if (!no_nonce && (nonce_asn1 = create_nonce(NONCE_LENGTH)) == NULL)
649 		goto err;
650 	if (nonce_asn1 != NULL && !TS_REQ_set_nonce(ts_req, nonce_asn1))
651 		goto err;
652 
653 	/* Setting certificate request flag if requested. */
654 	if (!TS_REQ_set_cert_req(ts_req, cert))
655 		goto err;
656 
657 	ret = 1;
658 
659  err:
660 	if (!ret) {
661 		TS_REQ_free(ts_req);
662 		ts_req = NULL;
663 		BIO_printf(bio_err, "could not create query\n");
664 	}
665 	TS_MSG_IMPRINT_free(msg_imprint);
666 	X509_ALGOR_free(algo);
667 	free(data);
668 	ASN1_OBJECT_free(policy_obj);
669 	ASN1_INTEGER_free(nonce_asn1);
670 
671 	return ts_req;
672 }
673 
674 static int
675 create_digest(BIO *input, char *digest, const EVP_MD *md,
676     unsigned char **md_value)
677 {
678 	int md_value_len;
679 	EVP_MD_CTX *md_ctx = NULL;
680 
681 	md_value_len = EVP_MD_size(md);
682 	if (md_value_len < 0)
683 		goto err;
684 
685 	if (input != NULL) {
686 		/* Digest must be computed from an input file. */
687 		unsigned char buffer[4096];
688 		int length;
689 
690 		*md_value = malloc(md_value_len);
691 		if (*md_value == NULL)
692 			goto err;
693 
694 		if ((md_ctx = EVP_MD_CTX_new()) == NULL)
695 			goto err;
696 
697 		if (!EVP_DigestInit(md_ctx, md))
698 			goto err;
699 
700 		while ((length = BIO_read(input, buffer, sizeof(buffer))) > 0) {
701 			if (!EVP_DigestUpdate(md_ctx, buffer, length))
702 				goto err;
703 		}
704 
705 		if (!EVP_DigestFinal(md_ctx, *md_value, NULL))
706 			goto err;
707 
708 		EVP_MD_CTX_free(md_ctx);
709 		md_ctx = NULL;
710 
711 	} else {
712 		/* Digest bytes are specified with digest. */
713 		long digest_len;
714 
715 		*md_value = string_to_hex(digest, &digest_len);
716 		if (*md_value == NULL || md_value_len != digest_len) {
717 			free(*md_value);
718 			*md_value = NULL;
719 			BIO_printf(bio_err, "bad digest, %d bytes "
720 			    "must be specified\n", md_value_len);
721 			goto err;
722 		}
723 	}
724 
725 	return md_value_len;
726 
727  err:
728 	EVP_MD_CTX_free(md_ctx);
729 	return 0;
730 }
731 
732 static ASN1_INTEGER *
733 create_nonce(int bits)
734 {
735 	unsigned char buf[20];
736 	ASN1_INTEGER *nonce = NULL;
737 	int len = (bits - 1) / 8 + 1;
738 	int i;
739 
740 	/* Generating random byte sequence. */
741 	if (len > (int) sizeof(buf))
742 		goto err;
743 	arc4random_buf(buf, len);
744 
745 	/* Find the first non-zero byte and creating ASN1_INTEGER object. */
746 	for (i = 0; i < len && !buf[i]; ++i)
747 		;
748 	if ((nonce = ASN1_INTEGER_new()) == NULL)
749 		goto err;
750 	free(nonce->data);
751 	/* Allocate at least one byte. */
752 	nonce->length = len - i;
753 	if ((nonce->data = malloc(nonce->length + 1)) == NULL)
754 		goto err;
755 	memcpy(nonce->data, buf + i, nonce->length);
756 
757 	return nonce;
758 
759  err:
760 	BIO_printf(bio_err, "could not create nonce\n");
761 	ASN1_INTEGER_free(nonce);
762 	return NULL;
763 }
764 
765 /*
766  * Reply-related method definitions.
767  */
768 
769 static int
770 reply_command(CONF *conf, char *section, char *queryfile, char *passin,
771     char *inkey, char *signer, char *chain, const char *policy, char *in,
772     int token_in, char *out, int token_out, int text)
773 {
774 	int ret = 0;
775 	TS_RESP *response = NULL;
776 	BIO *in_bio = NULL;
777 	BIO *query_bio = NULL;
778 	BIO *inkey_bio = NULL;
779 	BIO *signer_bio = NULL;
780 	BIO *out_bio = NULL;
781 
782 	/* Build response object either from response or query. */
783 	if (in != NULL) {
784 		if ((in_bio = BIO_new_file(in, "rb")) == NULL)
785 			goto end;
786 		if (token_in) {
787 			/*
788 			 * We have a ContentInfo (PKCS7) object, add
789 			 * 'granted' status info around it.
790 			 */
791 			response = read_PKCS7(in_bio);
792 		} else {
793 			/* We have a ready-made TS_RESP object. */
794 			response = d2i_TS_RESP_bio(in_bio, NULL);
795 		}
796 	} else {
797 		response = create_response(conf, section, queryfile, passin,
798 				inkey, signer, chain, policy);
799 		if (response != NULL)
800 			BIO_printf(bio_err, "Response has been generated.\n");
801 		else
802 			BIO_printf(bio_err, "Response is not generated.\n");
803 	}
804 	if (response == NULL)
805 		goto end;
806 
807 	/* Write response either in ASN.1 or text format. */
808 	if ((out_bio = BIO_open_with_default(out, "wb", stdout)) == NULL)
809 		goto end;
810 	if (text) {
811 		/* Text output. */
812 		if (token_out) {
813 			TS_TST_INFO *tst_info = TS_RESP_get_tst_info(response);
814 			if (!TS_TST_INFO_print_bio(out_bio, tst_info))
815 				goto end;
816 		} else {
817 			if (!TS_RESP_print_bio(out_bio, response))
818 				goto end;
819 		}
820 	} else {
821 		/* ASN.1 DER output. */
822 		if (token_out) {
823 			PKCS7 *token = TS_RESP_get_token(response);
824 			if (!i2d_PKCS7_bio(out_bio, token))
825 				goto end;
826 		} else {
827 			if (!i2d_TS_RESP_bio(out_bio, response))
828 				goto end;
829 		}
830 	}
831 
832 	ret = 1;
833 
834  end:
835 	ERR_print_errors(bio_err);
836 
837 	/* Clean up. */
838 	BIO_free_all(in_bio);
839 	BIO_free_all(query_bio);
840 	BIO_free_all(inkey_bio);
841 	BIO_free_all(signer_bio);
842 	BIO_free_all(out_bio);
843 	TS_RESP_free(response);
844 
845 	return ret;
846 }
847 
848 /* Reads a PKCS7 token and adds default 'granted' status info to it. */
849 static TS_RESP *
850 read_PKCS7(BIO *in_bio)
851 {
852 	int ret = 0;
853 	PKCS7 *token = NULL;
854 	TS_TST_INFO *tst_info = NULL;
855 	TS_RESP *resp = NULL;
856 	TS_STATUS_INFO *si = NULL;
857 
858 	/* Read PKCS7 object and extract the signed time stamp info. */
859 	if ((token = d2i_PKCS7_bio(in_bio, NULL)) == NULL)
860 		goto end;
861 	if ((tst_info = PKCS7_to_TS_TST_INFO(token)) == NULL)
862 		goto end;
863 
864 	/* Creating response object. */
865 	if ((resp = TS_RESP_new()) == NULL)
866 		goto end;
867 
868 	/* Create granted status info. */
869 	if ((si = TS_STATUS_INFO_new()) == NULL)
870 		goto end;
871 	if (!TS_STATUS_INFO_set_status(si, TS_STATUS_GRANTED))
872 		goto end;
873 	if (!TS_RESP_set_status_info(resp, si))
874 		goto end;
875 
876 	/* Setting encapsulated token. */
877 	TS_RESP_set_tst_info(resp, token, tst_info);
878 	token = NULL;		/* Ownership is lost. */
879 	tst_info = NULL;	/* Ownership is lost. */
880 
881 	ret = 1;
882  end:
883 	PKCS7_free(token);
884 	TS_TST_INFO_free(tst_info);
885 	if (!ret) {
886 		TS_RESP_free(resp);
887 		resp = NULL;
888 	}
889 	TS_STATUS_INFO_free(si);
890 	return resp;
891 }
892 
893 static TS_RESP *
894 create_response(CONF *conf, const char *section, char *queryfile, char *passin,
895     char *inkey, char *signer, char *chain, const char *policy)
896 {
897 	int ret = 0;
898 	TS_RESP *response = NULL;
899 	BIO *query_bio = NULL;
900 	TS_RESP_CTX *resp_ctx = NULL;
901 
902 	if ((query_bio = BIO_new_file(queryfile, "rb")) == NULL)
903 		goto end;
904 
905 	/* Getting TSA configuration section. */
906 	if ((section = TS_CONF_get_tsa_section(conf, section)) == NULL)
907 		goto end;
908 
909 	/* Setting up response generation context. */
910 	if ((resp_ctx = TS_RESP_CTX_new()) == NULL)
911 		goto end;
912 
913 	/* Setting serial number provider callback. */
914 	if (!TS_CONF_set_serial(conf, section, serial_cb, resp_ctx))
915 		goto end;
916 
917 	/* Setting TSA signer certificate. */
918 	if (!TS_CONF_set_signer_cert(conf, section, signer, resp_ctx))
919 		goto end;
920 
921 	/* Setting TSA signer certificate chain. */
922 	if (!TS_CONF_set_certs(conf, section, chain, resp_ctx))
923 		goto end;
924 
925 	/* Setting TSA signer private key. */
926 	if (!TS_CONF_set_signer_key(conf, section, inkey, passin, resp_ctx))
927 		goto end;
928 
929 	/* Setting default policy OID. */
930 	if (!TS_CONF_set_def_policy(conf, section, policy, resp_ctx))
931 		goto end;
932 
933 	/* Setting acceptable policy OIDs. */
934 	if (!TS_CONF_set_policies(conf, section, resp_ctx))
935 		goto end;
936 
937 	/* Setting the acceptable one-way hash algorithms. */
938 	if (!TS_CONF_set_digests(conf, section, resp_ctx))
939 		goto end;
940 
941 	/* Setting guaranteed time stamp accuracy. */
942 	if (!TS_CONF_set_accuracy(conf, section, resp_ctx))
943 		goto end;
944 
945 	/* Setting the precision of the time. */
946 	if (!TS_CONF_set_clock_precision_digits(conf, section, resp_ctx))
947 		goto end;
948 
949 	/* Setting the ordering flaf if requested. */
950 	if (!TS_CONF_set_ordering(conf, section, resp_ctx))
951 		goto end;
952 
953 	/* Setting the TSA name required flag if requested. */
954 	if (!TS_CONF_set_tsa_name(conf, section, resp_ctx))
955 		goto end;
956 
957 	/* Setting the ESS cert id chain flag if requested. */
958 	if (!TS_CONF_set_ess_cert_id_chain(conf, section, resp_ctx))
959 		goto end;
960 
961 	/* Creating the response. */
962 	if ((response = TS_RESP_create_response(resp_ctx, query_bio)) == NULL)
963 		goto end;
964 
965 	ret = 1;
966  end:
967 	if (!ret) {
968 		TS_RESP_free(response);
969 		response = NULL;
970 	}
971 	TS_RESP_CTX_free(resp_ctx);
972 	BIO_free_all(query_bio);
973 
974 	return response;
975 }
976 
977 static ASN1_INTEGER *
978 serial_cb(TS_RESP_CTX *ctx, void *data)
979 {
980 	const char *serial_file = (const char *) data;
981 	ASN1_INTEGER *serial = next_serial(serial_file);
982 
983 	if (serial == NULL) {
984 		TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
985 		    "Error during serial number "
986 		    "generation.");
987 		TS_RESP_CTX_add_failure_info(ctx,
988 		    TS_INFO_ADD_INFO_NOT_AVAILABLE);
989 	} else
990 		save_ts_serial(serial_file, serial);
991 
992 	return serial;
993 }
994 
995 static ASN1_INTEGER *
996 next_serial(const char *serialfile)
997 {
998 	int ret = 0;
999 	BIO *in = NULL;
1000 	ASN1_INTEGER *serial = NULL;
1001 	BIGNUM *bn = NULL;
1002 
1003 	if ((serial = ASN1_INTEGER_new()) == NULL)
1004 		goto err;
1005 
1006 	if ((in = BIO_new_file(serialfile, "r")) == NULL) {
1007 		ERR_clear_error();
1008 		BIO_printf(bio_err, "Warning: could not open file %s for "
1009 		    "reading, using serial number: 1\n", serialfile);
1010 		if (!ASN1_INTEGER_set(serial, 1))
1011 			goto err;
1012 	} else {
1013 		char buf[1024];
1014 		if (!a2i_ASN1_INTEGER(in, serial, buf, sizeof(buf))) {
1015 			BIO_printf(bio_err, "unable to load number from %s\n",
1016 			    serialfile);
1017 			goto err;
1018 		}
1019 		if ((bn = ASN1_INTEGER_to_BN(serial, NULL)) == NULL)
1020 			goto err;
1021 		ASN1_INTEGER_free(serial);
1022 		serial = NULL;
1023 		if (!BN_add_word(bn, 1))
1024 			goto err;
1025 		if ((serial = BN_to_ASN1_INTEGER(bn, NULL)) == NULL)
1026 			goto err;
1027 	}
1028 	ret = 1;
1029  err:
1030 	if (!ret) {
1031 		ASN1_INTEGER_free(serial);
1032 		serial = NULL;
1033 	}
1034 	BIO_free_all(in);
1035 	BN_free(bn);
1036 	return serial;
1037 }
1038 
1039 static int
1040 save_ts_serial(const char *serialfile, ASN1_INTEGER *serial)
1041 {
1042 	int ret = 0;
1043 	BIO *out = NULL;
1044 
1045 	if ((out = BIO_new_file(serialfile, "w")) == NULL)
1046 		goto err;
1047 	if (i2a_ASN1_INTEGER(out, serial) <= 0)
1048 		goto err;
1049 	if (BIO_puts(out, "\n") <= 0)
1050 		goto err;
1051 	ret = 1;
1052  err:
1053 	if (!ret)
1054 		BIO_printf(bio_err, "could not save serial number to %s\n",
1055 		    serialfile);
1056 	BIO_free_all(out);
1057 	return ret;
1058 }
1059 
1060 /*
1061  * Verify-related method definitions.
1062  */
1063 
1064 static int
1065 verify_command(char *data, char *digest, char *queryfile, char *in,
1066     int token_in, char *ca_path, char *ca_file, char *untrusted)
1067 {
1068 	BIO *in_bio = NULL;
1069 	PKCS7 *token = NULL;
1070 	TS_RESP *response = NULL;
1071 	TS_VERIFY_CTX *verify_ctx = NULL;
1072 	int ret = 0;
1073 
1074 	/* Decode the token (PKCS7) or response (TS_RESP) files. */
1075 	if ((in_bio = BIO_new_file(in, "rb")) == NULL)
1076 		goto end;
1077 	if (token_in) {
1078 		if ((token = d2i_PKCS7_bio(in_bio, NULL)) == NULL)
1079 			goto end;
1080 	} else {
1081 		if ((response = d2i_TS_RESP_bio(in_bio, NULL)) == NULL)
1082 			goto end;
1083 	}
1084 
1085 	if ((verify_ctx = create_verify_ctx(data, digest, queryfile,
1086 	    ca_path, ca_file, untrusted)) == NULL)
1087 		goto end;
1088 
1089 	/* Checking the token or response against the request. */
1090 	ret = token_in ?
1091 	    TS_RESP_verify_token(verify_ctx, token) :
1092 	    TS_RESP_verify_response(verify_ctx, response);
1093 
1094  end:
1095 	printf("Verification: ");
1096 	if (ret)
1097 		printf("OK\n");
1098 	else {
1099 		printf("FAILED\n");
1100 		/* Print errors, if there are any. */
1101 		ERR_print_errors(bio_err);
1102 	}
1103 
1104 	/* Clean up. */
1105 	BIO_free_all(in_bio);
1106 	PKCS7_free(token);
1107 	TS_RESP_free(response);
1108 	TS_VERIFY_CTX_free(verify_ctx);
1109 	return ret;
1110 }
1111 
1112 static TS_VERIFY_CTX *
1113 create_verify_ctx(char *data, char *digest, char *queryfile, char *ca_path,
1114     char *ca_file, char *untrusted)
1115 {
1116 	TS_VERIFY_CTX *ctx = NULL;
1117 	BIO *input = NULL;
1118 	TS_REQ *request = NULL;
1119 	X509_STORE *store;
1120 	STACK_OF(X509) *certs;
1121 	int ret = 0;
1122 
1123 	if (data != NULL || digest != NULL) {
1124 		if ((ctx = TS_VERIFY_CTX_new()) == NULL)
1125 			goto err;
1126 		TS_VERIFY_CTX_set_flags(ctx, TS_VFY_VERSION | TS_VFY_SIGNER);
1127 		if (data != NULL) {
1128 			BIO *data_bio;
1129 
1130 			TS_VERIFY_CTX_add_flags(ctx, TS_VFY_DATA);
1131 			if ((data_bio = BIO_new_file(data, "rb")) == NULL)
1132 				goto err;
1133 			TS_VERIFY_CTX_set_data(ctx, data_bio);
1134 		} else if (digest != NULL) {
1135 			unsigned char *imprint;
1136 			long imprint_len;
1137 
1138 			TS_VERIFY_CTX_add_flags(ctx, TS_VFY_IMPRINT);
1139 			if ((imprint = string_to_hex(digest,
1140 			    &imprint_len)) == NULL) {
1141 				BIO_printf(bio_err, "invalid digest string\n");
1142 				goto err;
1143 			}
1144 			TS_VERIFY_CTX_set_imprint(ctx, imprint, imprint_len);
1145 		}
1146 	} else if (queryfile != NULL) {
1147 		/*
1148 		 * The request has just to be read, decoded and converted to
1149 		 * a verify context object.
1150 		 */
1151 		if ((input = BIO_new_file(queryfile, "rb")) == NULL)
1152 			goto err;
1153 		if ((request = d2i_TS_REQ_bio(input, NULL)) == NULL)
1154 			goto err;
1155 		if ((ctx = TS_REQ_to_TS_VERIFY_CTX(request, NULL)) == NULL)
1156 			goto err;
1157 	} else
1158 		return NULL;
1159 
1160 	/* Add the signature verification flag and arguments. */
1161 	TS_VERIFY_CTX_add_flags(ctx, TS_VFY_SIGNATURE);
1162 
1163 	/* Initialising the X509_STORE object. */
1164 	if ((store = create_cert_store(ca_path, ca_file)) == NULL)
1165 		goto err;
1166 	TS_VERIFY_CTX_set_store(ctx, store);
1167 
1168 	/* Loading untrusted certificates. */
1169 	if (untrusted != NULL) {
1170 		if ((certs = TS_CONF_load_certs(untrusted)) == NULL)
1171 			goto err;
1172 		TS_VERIFY_CTX_set_certs(ctx, certs);
1173 	}
1174 
1175 	ret = 1;
1176  err:
1177 	if (!ret) {
1178 		TS_VERIFY_CTX_free(ctx);
1179 		ctx = NULL;
1180 	}
1181 	BIO_free_all(input);
1182 	TS_REQ_free(request);
1183 	return ctx;
1184 }
1185 
1186 static X509_STORE *
1187 create_cert_store(char *ca_path, char *ca_file)
1188 {
1189 	X509_STORE *cert_ctx = NULL;
1190 	X509_LOOKUP *lookup = NULL;
1191 	int i;
1192 
1193 	/* Creating the X509_STORE object. */
1194 	if ((cert_ctx = X509_STORE_new()) == NULL)
1195 		goto err;
1196 
1197 	/* Setting the callback for certificate chain verification. */
1198 	X509_STORE_set_verify_cb(cert_ctx, verify_cb);
1199 
1200 	/* Adding a trusted certificate directory source. */
1201 	if (ca_path != NULL) {
1202 		lookup = X509_STORE_add_lookup(cert_ctx,
1203 		    X509_LOOKUP_hash_dir());
1204 		if (lookup == NULL) {
1205 			BIO_printf(bio_err, "memory allocation failure\n");
1206 			goto err;
1207 		}
1208 		i = X509_LOOKUP_add_dir(lookup, ca_path, X509_FILETYPE_PEM);
1209 		if (!i) {
1210 			BIO_printf(bio_err, "Error loading directory %s\n",
1211 			    ca_path);
1212 			goto err;
1213 		}
1214 	}
1215 	/* Adding a trusted certificate file source. */
1216 	if (ca_file != NULL) {
1217 		lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());
1218 		if (lookup == NULL) {
1219 			BIO_printf(bio_err, "memory allocation failure\n");
1220 			goto err;
1221 		}
1222 		i = X509_LOOKUP_load_file(lookup, ca_file, X509_FILETYPE_PEM);
1223 		if (!i) {
1224 			BIO_printf(bio_err, "Error loading file %s\n", ca_file);
1225 			goto err;
1226 		}
1227 	}
1228 	return cert_ctx;
1229  err:
1230 	X509_STORE_free(cert_ctx);
1231 	return NULL;
1232 }
1233 
1234 static int
1235 verify_cb(int ok, X509_STORE_CTX *ctx)
1236 {
1237 	/*
1238 	char buf[256];
1239 
1240 	if (!ok)
1241 		{
1242 		X509_NAME_oneline(X509_get_subject_name(ctx->current_cert),
1243 				  buf, sizeof(buf));
1244 		printf("%s\n", buf);
1245 		printf("error %d at %d depth lookup: %s\n",
1246 		       ctx->error, ctx->error_depth,
1247 			X509_verify_cert_error_string(ctx->error));
1248 		}
1249 	*/
1250 
1251 	return ok;
1252 }
1253