xref: /openbsd/lib/libcrypto/ts/ts_rsp_sign.c (revision d89ec533)
1 /* $OpenBSD: ts_rsp_sign.c,v 1.26 2021/12/12 21:30:14 tb Exp $ */
2 /* Written by Zoltan Glozik (zglozik@stones.com) for the OpenSSL
3  * project 2002.
4  */
5 /* ====================================================================
6  * Copyright (c) 2006 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 <sys/time.h>
60 
61 #include <string.h>
62 
63 #include <openssl/err.h>
64 #include <openssl/objects.h>
65 #include <openssl/pkcs7.h>
66 #include <openssl/ts.h>
67 
68 #include "evp_locl.h"
69 #include "x509_lcl.h"
70 
71 /* Private function declarations. */
72 
73 static ASN1_INTEGER *def_serial_cb(struct TS_resp_ctx *, void *);
74 static int def_time_cb(struct TS_resp_ctx *, void *, time_t *sec, long *usec);
75 static int def_extension_cb(struct TS_resp_ctx *, X509_EXTENSION *, void *);
76 
77 static void TS_RESP_CTX_init(TS_RESP_CTX *ctx);
78 static void TS_RESP_CTX_cleanup(TS_RESP_CTX *ctx);
79 static int TS_RESP_check_request(TS_RESP_CTX *ctx);
80 static ASN1_OBJECT *TS_RESP_get_policy(TS_RESP_CTX *ctx);
81 static TS_TST_INFO *TS_RESP_create_tst_info(TS_RESP_CTX *ctx,
82     ASN1_OBJECT *policy);
83 static int TS_RESP_process_extensions(TS_RESP_CTX *ctx);
84 static int TS_RESP_sign(TS_RESP_CTX *ctx);
85 
86 static ESS_SIGNING_CERT *ESS_SIGNING_CERT_new_init(X509 *signcert,
87     STACK_OF(X509) *certs);
88 static ESS_CERT_ID *ESS_CERT_ID_new_init(X509 *cert, int issuer_needed);
89 static int TS_TST_INFO_content_new(PKCS7 *p7);
90 static int ESS_add_signing_cert(PKCS7_SIGNER_INFO *si, ESS_SIGNING_CERT *sc);
91 
92 static ASN1_GENERALIZEDTIME *TS_RESP_set_genTime_with_precision(
93     ASN1_GENERALIZEDTIME *, time_t, long, unsigned);
94 
95 /* Default callbacks for response generation. */
96 
97 static ASN1_INTEGER *
98 def_serial_cb(struct TS_resp_ctx *ctx, void *data)
99 {
100 	ASN1_INTEGER *serial = ASN1_INTEGER_new();
101 
102 	if (!serial)
103 		goto err;
104 	if (!ASN1_INTEGER_set(serial, 1))
105 		goto err;
106 	return serial;
107 
108 err:
109 	TSerror(ERR_R_MALLOC_FAILURE);
110 	TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
111 	    "Error during serial number generation.");
112 	return NULL;
113 }
114 
115 /* Use the gettimeofday function call. */
116 static int
117 def_time_cb(struct TS_resp_ctx *ctx, void *data, time_t *sec, long *usec)
118 {
119 	struct timeval tv;
120 
121 	if (gettimeofday(&tv, NULL) != 0) {
122 		TSerror(TS_R_TIME_SYSCALL_ERROR);
123 		TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
124 		    "Time is not available.");
125 		TS_RESP_CTX_add_failure_info(ctx, TS_INFO_TIME_NOT_AVAILABLE);
126 		return 0;
127 	}
128 	/* Return time to caller. */
129 	*sec = tv.tv_sec;
130 	*usec = tv.tv_usec;
131 
132 	return 1;
133 }
134 
135 static int
136 def_extension_cb(struct TS_resp_ctx *ctx, X509_EXTENSION *ext, void *data)
137 {
138 	/* No extensions are processed here. */
139 	TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
140 	    "Unsupported extension.");
141 	TS_RESP_CTX_add_failure_info(ctx, TS_INFO_UNACCEPTED_EXTENSION);
142 	return 0;
143 }
144 
145 /* TS_RESP_CTX management functions. */
146 
147 TS_RESP_CTX *
148 TS_RESP_CTX_new(void)
149 {
150 	TS_RESP_CTX *ctx;
151 
152 	if (!(ctx = calloc(1, sizeof(TS_RESP_CTX)))) {
153 		TSerror(ERR_R_MALLOC_FAILURE);
154 		return NULL;
155 	}
156 
157 	/* Setting default callbacks. */
158 	ctx->serial_cb = def_serial_cb;
159 	ctx->time_cb = def_time_cb;
160 	ctx->extension_cb = def_extension_cb;
161 
162 	return ctx;
163 }
164 
165 void
166 TS_RESP_CTX_free(TS_RESP_CTX *ctx)
167 {
168 	if (!ctx)
169 		return;
170 
171 	X509_free(ctx->signer_cert);
172 	EVP_PKEY_free(ctx->signer_key);
173 	sk_X509_pop_free(ctx->certs, X509_free);
174 	sk_ASN1_OBJECT_pop_free(ctx->policies, ASN1_OBJECT_free);
175 	ASN1_OBJECT_free(ctx->default_policy);
176 	sk_EVP_MD_free(ctx->mds);	/* No EVP_MD_free method exists. */
177 	ASN1_INTEGER_free(ctx->seconds);
178 	ASN1_INTEGER_free(ctx->millis);
179 	ASN1_INTEGER_free(ctx->micros);
180 	free(ctx);
181 }
182 
183 int
184 TS_RESP_CTX_set_signer_cert(TS_RESP_CTX *ctx, X509 *signer)
185 {
186 	if (X509_check_purpose(signer, X509_PURPOSE_TIMESTAMP_SIGN, 0) != 1) {
187 		TSerror(TS_R_INVALID_SIGNER_CERTIFICATE_PURPOSE);
188 		return 0;
189 	}
190 	X509_free(ctx->signer_cert);
191 	ctx->signer_cert = signer;
192 	CRYPTO_add(&ctx->signer_cert->references, +1, CRYPTO_LOCK_X509);
193 	return 1;
194 }
195 
196 int
197 TS_RESP_CTX_set_signer_key(TS_RESP_CTX *ctx, EVP_PKEY *key)
198 {
199 	EVP_PKEY_free(ctx->signer_key);
200 	ctx->signer_key = key;
201 	CRYPTO_add(&ctx->signer_key->references, +1, CRYPTO_LOCK_EVP_PKEY);
202 
203 	return 1;
204 }
205 
206 int
207 TS_RESP_CTX_set_def_policy(TS_RESP_CTX *ctx, const ASN1_OBJECT *def_policy)
208 {
209 	if (ctx->default_policy)
210 		ASN1_OBJECT_free(ctx->default_policy);
211 	if (!(ctx->default_policy = OBJ_dup(def_policy)))
212 		goto err;
213 	return 1;
214 
215 err:
216 	TSerror(ERR_R_MALLOC_FAILURE);
217 	return 0;
218 }
219 
220 int
221 TS_RESP_CTX_set_certs(TS_RESP_CTX *ctx, STACK_OF(X509) *certs)
222 {
223 	int i;
224 
225 	if (ctx->certs) {
226 		sk_X509_pop_free(ctx->certs, X509_free);
227 		ctx->certs = NULL;
228 	}
229 	if (!certs)
230 		return 1;
231 	if (!(ctx->certs = sk_X509_dup(certs))) {
232 		TSerror(ERR_R_MALLOC_FAILURE);
233 		return 0;
234 	}
235 	for (i = 0; i < sk_X509_num(ctx->certs); ++i) {
236 		X509 *cert = sk_X509_value(ctx->certs, i);
237 		CRYPTO_add(&cert->references, +1, CRYPTO_LOCK_X509);
238 	}
239 
240 	return 1;
241 }
242 
243 int
244 TS_RESP_CTX_add_policy(TS_RESP_CTX *ctx, const ASN1_OBJECT *policy)
245 {
246 	ASN1_OBJECT *copy = NULL;
247 
248 	/* Create new policy stack if necessary. */
249 	if (!ctx->policies && !(ctx->policies = sk_ASN1_OBJECT_new_null()))
250 		goto err;
251 	if (!(copy = OBJ_dup(policy)))
252 		goto err;
253 	if (!sk_ASN1_OBJECT_push(ctx->policies, copy))
254 		goto err;
255 
256 	return 1;
257 
258 err:
259 	TSerror(ERR_R_MALLOC_FAILURE);
260 	ASN1_OBJECT_free(copy);
261 	return 0;
262 }
263 
264 int
265 TS_RESP_CTX_add_md(TS_RESP_CTX *ctx, const EVP_MD *md)
266 {
267 	/* Create new md stack if necessary. */
268 	if (!ctx->mds && !(ctx->mds = sk_EVP_MD_new_null()))
269 		goto err;
270 	/* Add the shared md, no copy needed. */
271 	if (!sk_EVP_MD_push(ctx->mds, (EVP_MD *)md))
272 		goto err;
273 
274 	return 1;
275 
276 err:
277 	TSerror(ERR_R_MALLOC_FAILURE);
278 	return 0;
279 }
280 
281 #define TS_RESP_CTX_accuracy_free(ctx)		\
282 	ASN1_INTEGER_free(ctx->seconds);	\
283 	ctx->seconds = NULL;			\
284 	ASN1_INTEGER_free(ctx->millis);		\
285 	ctx->millis = NULL;			\
286 	ASN1_INTEGER_free(ctx->micros);		\
287 	ctx->micros = NULL;
288 
289 int
290 TS_RESP_CTX_set_accuracy(TS_RESP_CTX *ctx, int secs, int millis, int micros)
291 {
292 	TS_RESP_CTX_accuracy_free(ctx);
293 	if (secs && (!(ctx->seconds = ASN1_INTEGER_new()) ||
294 	    !ASN1_INTEGER_set(ctx->seconds, secs)))
295 		goto err;
296 	if (millis && (!(ctx->millis = ASN1_INTEGER_new()) ||
297 	    !ASN1_INTEGER_set(ctx->millis, millis)))
298 		goto err;
299 	if (micros && (!(ctx->micros = ASN1_INTEGER_new()) ||
300 	    !ASN1_INTEGER_set(ctx->micros, micros)))
301 		goto err;
302 
303 	return 1;
304 
305 err:
306 	TS_RESP_CTX_accuracy_free(ctx);
307 	TSerror(ERR_R_MALLOC_FAILURE);
308 	return 0;
309 }
310 
311 void
312 TS_RESP_CTX_add_flags(TS_RESP_CTX *ctx, int flags)
313 {
314 	ctx->flags |= flags;
315 }
316 
317 void
318 TS_RESP_CTX_set_serial_cb(TS_RESP_CTX *ctx, TS_serial_cb cb, void *data)
319 {
320 	ctx->serial_cb = cb;
321 	ctx->serial_cb_data = data;
322 }
323 
324 void
325 TS_RESP_CTX_set_extension_cb(TS_RESP_CTX *ctx, TS_extension_cb cb, void *data)
326 {
327 	ctx->extension_cb = cb;
328 	ctx->extension_cb_data = data;
329 }
330 
331 int
332 TS_RESP_CTX_set_status_info(TS_RESP_CTX *ctx, int status, const char *text)
333 {
334 	TS_STATUS_INFO *si = NULL;
335 	ASN1_UTF8STRING *utf8_text = NULL;
336 	int ret = 0;
337 
338 	if (!(si = TS_STATUS_INFO_new()))
339 		goto err;
340 	if (!ASN1_INTEGER_set(si->status, status))
341 		goto err;
342 	if (text) {
343 		if (!(utf8_text = ASN1_UTF8STRING_new()) ||
344 		    !ASN1_STRING_set(utf8_text, text, strlen(text)))
345 			goto err;
346 		if (!si->text && !(si->text = sk_ASN1_UTF8STRING_new_null()))
347 			goto err;
348 		if (!sk_ASN1_UTF8STRING_push(si->text, utf8_text))
349 			goto err;
350 		utf8_text = NULL;	/* Ownership is lost. */
351 	}
352 	if (!TS_RESP_set_status_info(ctx->response, si))
353 		goto err;
354 	ret = 1;
355 
356 err:
357 	if (!ret)
358 		TSerror(ERR_R_MALLOC_FAILURE);
359 	TS_STATUS_INFO_free(si);
360 	ASN1_UTF8STRING_free(utf8_text);
361 	return ret;
362 }
363 
364 int
365 TS_RESP_CTX_set_status_info_cond(TS_RESP_CTX *ctx, int status, const char *text)
366 {
367 	int ret = 1;
368 	TS_STATUS_INFO *si = TS_RESP_get_status_info(ctx->response);
369 
370 	if (ASN1_INTEGER_get(si->status) == TS_STATUS_GRANTED) {
371 		/* Status has not been set, set it now. */
372 		ret = TS_RESP_CTX_set_status_info(ctx, status, text);
373 	}
374 	return ret;
375 }
376 
377 int
378 TS_RESP_CTX_add_failure_info(TS_RESP_CTX *ctx, int failure)
379 {
380 	TS_STATUS_INFO *si = TS_RESP_get_status_info(ctx->response);
381 
382 	if (!si->failure_info && !(si->failure_info = ASN1_BIT_STRING_new()))
383 		goto err;
384 	if (!ASN1_BIT_STRING_set_bit(si->failure_info, failure, 1))
385 		goto err;
386 	return 1;
387 
388 err:
389 	TSerror(ERR_R_MALLOC_FAILURE);
390 	return 0;
391 }
392 
393 TS_REQ *
394 TS_RESP_CTX_get_request(TS_RESP_CTX *ctx)
395 {
396 	return ctx->request;
397 }
398 
399 TS_TST_INFO *
400 TS_RESP_CTX_get_tst_info(TS_RESP_CTX *ctx)
401 {
402 	return ctx->tst_info;
403 }
404 
405 int
406 TS_RESP_CTX_set_clock_precision_digits(TS_RESP_CTX *ctx, unsigned precision)
407 {
408 	if (precision > TS_MAX_CLOCK_PRECISION_DIGITS)
409 		return 0;
410 	ctx->clock_precision_digits = precision;
411 	return 1;
412 }
413 
414 /* Main entry method of the response generation. */
415 TS_RESP *
416 TS_RESP_create_response(TS_RESP_CTX *ctx, BIO *req_bio)
417 {
418 	ASN1_OBJECT *policy;
419 	TS_RESP *response;
420 	int result = 0;
421 
422 	TS_RESP_CTX_init(ctx);
423 
424 	/* Creating the response object. */
425 	if (!(ctx->response = TS_RESP_new())) {
426 		TSerror(ERR_R_MALLOC_FAILURE);
427 		goto end;
428 	}
429 
430 	/* Parsing DER request. */
431 	if (!(ctx->request = d2i_TS_REQ_bio(req_bio, NULL))) {
432 		TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
433 		    "Bad request format or "
434 		    "system error.");
435 		TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_DATA_FORMAT);
436 		goto end;
437 	}
438 
439 	/* Setting default status info. */
440 	if (!TS_RESP_CTX_set_status_info(ctx, TS_STATUS_GRANTED, NULL))
441 		goto end;
442 
443 	/* Checking the request format. */
444 	if (!TS_RESP_check_request(ctx))
445 		goto end;
446 
447 	/* Checking acceptable policies. */
448 	if (!(policy = TS_RESP_get_policy(ctx)))
449 		goto end;
450 
451 	/* Creating the TS_TST_INFO object. */
452 	if (!(ctx->tst_info = TS_RESP_create_tst_info(ctx, policy)))
453 		goto end;
454 
455 	/* Processing extensions. */
456 	if (!TS_RESP_process_extensions(ctx))
457 		goto end;
458 
459 	/* Generating the signature. */
460 	if (!TS_RESP_sign(ctx))
461 		goto end;
462 
463 	/* Everything was successful. */
464 	result = 1;
465 
466 end:
467 	if (!result) {
468 		TSerror(TS_R_RESPONSE_SETUP_ERROR);
469 		if (ctx->response != NULL) {
470 			if (TS_RESP_CTX_set_status_info_cond(ctx,
471 			    TS_STATUS_REJECTION, "Error during response "
472 			    "generation.") == 0) {
473 				TS_RESP_free(ctx->response);
474 				ctx->response = NULL;
475 			}
476 		}
477 	}
478 	response = ctx->response;
479 	ctx->response = NULL;	/* Ownership will be returned to caller. */
480 	TS_RESP_CTX_cleanup(ctx);
481 	return response;
482 }
483 
484 /* Initializes the variable part of the context. */
485 static void
486 TS_RESP_CTX_init(TS_RESP_CTX *ctx)
487 {
488 	ctx->request = NULL;
489 	ctx->response = NULL;
490 	ctx->tst_info = NULL;
491 }
492 
493 /* Cleans up the variable part of the context. */
494 static void
495 TS_RESP_CTX_cleanup(TS_RESP_CTX *ctx)
496 {
497 	TS_REQ_free(ctx->request);
498 	ctx->request = NULL;
499 	TS_RESP_free(ctx->response);
500 	ctx->response = NULL;
501 	TS_TST_INFO_free(ctx->tst_info);
502 	ctx->tst_info = NULL;
503 }
504 
505 /* Checks the format and content of the request. */
506 static int
507 TS_RESP_check_request(TS_RESP_CTX *ctx)
508 {
509 	TS_REQ *request = ctx->request;
510 	TS_MSG_IMPRINT *msg_imprint;
511 	X509_ALGOR *md_alg;
512 	int md_alg_id;
513 	const ASN1_OCTET_STRING *digest;
514 	EVP_MD *md = NULL;
515 	int i;
516 
517 	/* Checking request version. */
518 	if (TS_REQ_get_version(request) != 1) {
519 		TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
520 		    "Bad request version.");
521 		TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_REQUEST);
522 		return 0;
523 	}
524 
525 	/* Checking message digest algorithm. */
526 	msg_imprint = TS_REQ_get_msg_imprint(request);
527 	md_alg = TS_MSG_IMPRINT_get_algo(msg_imprint);
528 	md_alg_id = OBJ_obj2nid(md_alg->algorithm);
529 	for (i = 0; !md && i < sk_EVP_MD_num(ctx->mds); ++i) {
530 		EVP_MD *current_md = sk_EVP_MD_value(ctx->mds, i);
531 		if (md_alg_id == EVP_MD_type(current_md))
532 			md = current_md;
533 	}
534 	if (!md) {
535 		TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
536 		    "Message digest algorithm is "
537 		    "not supported.");
538 		TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_ALG);
539 		return 0;
540 	}
541 
542 	/* No message digest takes parameter. */
543 	if (md_alg->parameter &&
544 	    ASN1_TYPE_get(md_alg->parameter) != V_ASN1_NULL) {
545 		TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
546 		    "Superfluous message digest "
547 		    "parameter.");
548 		TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_ALG);
549 		return 0;
550 	}
551 	/* Checking message digest size. */
552 	digest = TS_MSG_IMPRINT_get_msg(msg_imprint);
553 	if (digest->length != EVP_MD_size(md)) {
554 		TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
555 		    "Bad message digest.");
556 		TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_DATA_FORMAT);
557 		return 0;
558 	}
559 
560 	return 1;
561 }
562 
563 /* Returns the TSA policy based on the requested and acceptable policies. */
564 static ASN1_OBJECT *
565 TS_RESP_get_policy(TS_RESP_CTX *ctx)
566 {
567 	ASN1_OBJECT *requested = TS_REQ_get_policy_id(ctx->request);
568 	ASN1_OBJECT *policy = NULL;
569 	int i;
570 
571 	if (ctx->default_policy == NULL) {
572 		TSerror(TS_R_INVALID_NULL_POINTER);
573 		return NULL;
574 	}
575 	/* Return the default policy if none is requested or the default is
576 	   requested. */
577 	if (!requested || !OBJ_cmp(requested, ctx->default_policy))
578 		policy = ctx->default_policy;
579 
580 	/* Check if the policy is acceptable. */
581 	for (i = 0; !policy && i < sk_ASN1_OBJECT_num(ctx->policies); ++i) {
582 		ASN1_OBJECT *current = sk_ASN1_OBJECT_value(ctx->policies, i);
583 		if (!OBJ_cmp(requested, current))
584 			policy = current;
585 	}
586 	if (!policy) {
587 		TSerror(TS_R_UNACCEPTABLE_POLICY);
588 		TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
589 		    "Requested policy is not "
590 		    "supported.");
591 		TS_RESP_CTX_add_failure_info(ctx, TS_INFO_UNACCEPTED_POLICY);
592 	}
593 	return policy;
594 }
595 
596 /* Creates the TS_TST_INFO object based on the settings of the context. */
597 static TS_TST_INFO *
598 TS_RESP_create_tst_info(TS_RESP_CTX *ctx, ASN1_OBJECT *policy)
599 {
600 	int result = 0;
601 	TS_TST_INFO *tst_info = NULL;
602 	ASN1_INTEGER *serial = NULL;
603 	ASN1_GENERALIZEDTIME *asn1_time = NULL;
604 	time_t sec;
605 	long usec;
606 	TS_ACCURACY *accuracy = NULL;
607 	const ASN1_INTEGER *nonce;
608 	GENERAL_NAME *tsa_name = NULL;
609 
610 	if (!(tst_info = TS_TST_INFO_new()))
611 		goto end;
612 	if (!TS_TST_INFO_set_version(tst_info, 1))
613 		goto end;
614 	if (!TS_TST_INFO_set_policy_id(tst_info, policy))
615 		goto end;
616 	if (!TS_TST_INFO_set_msg_imprint(tst_info, ctx->request->msg_imprint))
617 		goto end;
618 	if (!(serial = (*ctx->serial_cb)(ctx, ctx->serial_cb_data)) ||
619 	    !TS_TST_INFO_set_serial(tst_info, serial))
620 		goto end;
621 	if (!(*ctx->time_cb)(ctx, ctx->time_cb_data, &sec, &usec) ||
622 	    !(asn1_time = TS_RESP_set_genTime_with_precision(NULL, sec, usec,
623 	    ctx->clock_precision_digits)) ||
624 	    !TS_TST_INFO_set_time(tst_info, asn1_time))
625 		goto end;
626 
627 	/* Setting accuracy if needed. */
628 	if ((ctx->seconds || ctx->millis || ctx->micros) &&
629 	    !(accuracy = TS_ACCURACY_new()))
630 		goto end;
631 
632 	if (ctx->seconds && !TS_ACCURACY_set_seconds(accuracy, ctx->seconds))
633 		goto end;
634 	if (ctx->millis && !TS_ACCURACY_set_millis(accuracy, ctx->millis))
635 		goto end;
636 	if (ctx->micros && !TS_ACCURACY_set_micros(accuracy, ctx->micros))
637 		goto end;
638 	if (accuracy && !TS_TST_INFO_set_accuracy(tst_info, accuracy))
639 		goto end;
640 
641 	/* Setting ordering. */
642 	if ((ctx->flags & TS_ORDERING) &&
643 	    !TS_TST_INFO_set_ordering(tst_info, 1))
644 		goto end;
645 
646 	/* Setting nonce if needed. */
647 	if ((nonce = TS_REQ_get_nonce(ctx->request)) != NULL &&
648 	    !TS_TST_INFO_set_nonce(tst_info, nonce))
649 		goto end;
650 
651 	/* Setting TSA name to subject of signer certificate. */
652 	if (ctx->flags & TS_TSA_NAME) {
653 		if (!(tsa_name = GENERAL_NAME_new()))
654 			goto end;
655 		tsa_name->type = GEN_DIRNAME;
656 		tsa_name->d.dirn =
657 		    X509_NAME_dup(ctx->signer_cert->cert_info->subject);
658 		if (!tsa_name->d.dirn)
659 			goto end;
660 		if (!TS_TST_INFO_set_tsa(tst_info, tsa_name))
661 			goto end;
662 	}
663 
664 	result = 1;
665 
666 end:
667 	if (!result) {
668 		TS_TST_INFO_free(tst_info);
669 		tst_info = NULL;
670 		TSerror(TS_R_TST_INFO_SETUP_ERROR);
671 		TS_RESP_CTX_set_status_info_cond(ctx, TS_STATUS_REJECTION,
672 		    "Error during TSTInfo "
673 		    "generation.");
674 	}
675 	GENERAL_NAME_free(tsa_name);
676 	TS_ACCURACY_free(accuracy);
677 	ASN1_GENERALIZEDTIME_free(asn1_time);
678 	ASN1_INTEGER_free(serial);
679 
680 	return tst_info;
681 }
682 
683 /* Processing the extensions of the request. */
684 static int
685 TS_RESP_process_extensions(TS_RESP_CTX *ctx)
686 {
687 	STACK_OF(X509_EXTENSION) *exts = TS_REQ_get_exts(ctx->request);
688 	int i;
689 	int ok = 1;
690 
691 	for (i = 0; ok && i < sk_X509_EXTENSION_num(exts); ++i) {
692 		X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
693 		/* XXXXX The last argument was previously
694 		   (void *)ctx->extension_cb, but ISO C doesn't permit
695 		   converting a function pointer to void *.  For lack of
696 		   better information, I'm placing a NULL there instead.
697 		   The callback can pick its own address out from the ctx
698 		   anyway...
699 		*/
700 		ok = (*ctx->extension_cb)(ctx, ext, NULL);
701 	}
702 
703 	return ok;
704 }
705 
706 /* Functions for signing the TS_TST_INFO structure of the context. */
707 static int
708 TS_RESP_sign(TS_RESP_CTX *ctx)
709 {
710 	int ret = 0;
711 	PKCS7 *p7 = NULL;
712 	PKCS7_SIGNER_INFO *si;
713 	STACK_OF(X509) *certs;	/* Certificates to include in sc. */
714 	ESS_SIGNING_CERT *sc = NULL;
715 	ASN1_OBJECT *oid;
716 	BIO *p7bio = NULL;
717 	int i;
718 
719 	/* Check if signcert and pkey match. */
720 	if (!X509_check_private_key(ctx->signer_cert, ctx->signer_key)) {
721 		TSerror(TS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
722 		goto err;
723 	}
724 
725 	/* Create a new PKCS7 signed object. */
726 	if (!(p7 = PKCS7_new())) {
727 		TSerror(ERR_R_MALLOC_FAILURE);
728 		goto err;
729 	}
730 	if (!PKCS7_set_type(p7, NID_pkcs7_signed))
731 		goto err;
732 
733 	/* Force SignedData version to be 3 instead of the default 1. */
734 	if (!ASN1_INTEGER_set(p7->d.sign->version, 3))
735 		goto err;
736 
737 	/* Add signer certificate and optional certificate chain. */
738 	if (TS_REQ_get_cert_req(ctx->request)) {
739 		PKCS7_add_certificate(p7, ctx->signer_cert);
740 		if (ctx->certs) {
741 			for (i = 0; i < sk_X509_num(ctx->certs); ++i) {
742 				X509 *cert = sk_X509_value(ctx->certs, i);
743 				PKCS7_add_certificate(p7, cert);
744 			}
745 		}
746 	}
747 
748 	/* Add a new signer info. */
749 	if (!(si = PKCS7_add_signature(p7, ctx->signer_cert,
750 	    ctx->signer_key, EVP_sha1()))) {
751 		TSerror(TS_R_PKCS7_ADD_SIGNATURE_ERROR);
752 		goto err;
753 	}
754 
755 	/* Add content type signed attribute to the signer info. */
756 	oid = OBJ_nid2obj(NID_id_smime_ct_TSTInfo);
757 	if (!PKCS7_add_signed_attribute(si, NID_pkcs9_contentType,
758 	    V_ASN1_OBJECT, oid)) {
759 		TSerror(TS_R_PKCS7_ADD_SIGNED_ATTR_ERROR);
760 		goto err;
761 	}
762 
763 	/* Create the ESS SigningCertificate attribute which contains
764 	   the signer certificate id and optionally the certificate chain. */
765 	certs = ctx->flags & TS_ESS_CERT_ID_CHAIN ? ctx->certs : NULL;
766 	if (!(sc = ESS_SIGNING_CERT_new_init(ctx->signer_cert, certs)))
767 		goto err;
768 
769 	/* Add SigningCertificate signed attribute to the signer info. */
770 	if (!ESS_add_signing_cert(si, sc)) {
771 		TSerror(TS_R_ESS_ADD_SIGNING_CERT_ERROR);
772 		goto err;
773 	}
774 
775 	/* Add a new empty NID_id_smime_ct_TSTInfo encapsulated content. */
776 	if (!TS_TST_INFO_content_new(p7))
777 		goto err;
778 
779 	/* Add the DER encoded tst_info to the PKCS7 structure. */
780 	if (!(p7bio = PKCS7_dataInit(p7, NULL))) {
781 		TSerror(ERR_R_MALLOC_FAILURE);
782 		goto err;
783 	}
784 
785 	/* Convert tst_info to DER. */
786 	if (!i2d_TS_TST_INFO_bio(p7bio, ctx->tst_info)) {
787 		TSerror(TS_R_TS_DATASIGN);
788 		goto err;
789 	}
790 
791 	/* Create the signature and add it to the signer info. */
792 	if (!PKCS7_dataFinal(p7, p7bio)) {
793 		TSerror(TS_R_TS_DATASIGN);
794 		goto err;
795 	}
796 
797 	/* Set new PKCS7 and TST_INFO objects. */
798 	TS_RESP_set_tst_info(ctx->response, p7, ctx->tst_info);
799 	p7 = NULL;		/* Ownership is lost. */
800 	ctx->tst_info = NULL;	/* Ownership is lost. */
801 
802 	ret = 1;
803 
804 err:
805 	if (!ret)
806 		TS_RESP_CTX_set_status_info_cond(ctx, TS_STATUS_REJECTION,
807 	    "Error during signature "
808 	    "generation.");
809 	BIO_free_all(p7bio);
810 	ESS_SIGNING_CERT_free(sc);
811 	PKCS7_free(p7);
812 	return ret;
813 }
814 
815 static ESS_SIGNING_CERT *
816 ESS_SIGNING_CERT_new_init(X509 *signcert, STACK_OF(X509) *certs)
817 {
818 	ESS_CERT_ID *cid;
819 	ESS_SIGNING_CERT *sc = NULL;
820 	int i;
821 
822 	/* Creating the ESS_CERT_ID stack. */
823 	if (!(sc = ESS_SIGNING_CERT_new()))
824 		goto err;
825 	if (!sc->cert_ids && !(sc->cert_ids = sk_ESS_CERT_ID_new_null()))
826 		goto err;
827 
828 	/* Adding the signing certificate id. */
829 	if (!(cid = ESS_CERT_ID_new_init(signcert, 0)) ||
830 	    !sk_ESS_CERT_ID_push(sc->cert_ids, cid))
831 		goto err;
832 	/* Adding the certificate chain ids. */
833 	for (i = 0; i < sk_X509_num(certs); ++i) {
834 		X509 *cert = sk_X509_value(certs, i);
835 		if (!(cid = ESS_CERT_ID_new_init(cert, 1)) ||
836 		    !sk_ESS_CERT_ID_push(sc->cert_ids, cid))
837 			goto err;
838 	}
839 
840 	return sc;
841 
842 err:
843 	ESS_SIGNING_CERT_free(sc);
844 	TSerror(ERR_R_MALLOC_FAILURE);
845 	return NULL;
846 }
847 
848 static ESS_CERT_ID *
849 ESS_CERT_ID_new_init(X509 *cert, int issuer_needed)
850 {
851 	ESS_CERT_ID *cid = NULL;
852 	GENERAL_NAME *name = NULL;
853 	unsigned char cert_hash[TS_HASH_LEN];
854 
855 	/* Recompute SHA1 hash of certificate if necessary (side effect). */
856 	X509_check_purpose(cert, -1, 0);
857 
858 	if (!(cid = ESS_CERT_ID_new()))
859 		goto err;
860 
861 	if (!X509_digest(cert, TS_HASH_EVP, cert_hash, NULL))
862 		goto err;
863 
864 	if (!ASN1_OCTET_STRING_set(cid->hash, cert_hash, sizeof(cert_hash)))
865 		goto err;
866 
867 	/* Setting the issuer/serial if requested. */
868 	if (issuer_needed) {
869 		/* Creating issuer/serial structure. */
870 		if (!cid->issuer_serial &&
871 		    !(cid->issuer_serial = ESS_ISSUER_SERIAL_new()))
872 			goto err;
873 		/* Creating general name from the certificate issuer. */
874 		if (!(name = GENERAL_NAME_new()))
875 			goto err;
876 		name->type = GEN_DIRNAME;
877 		if (!(name->d.dirn = X509_NAME_dup(cert->cert_info->issuer)))
878 			goto err;
879 		if (!sk_GENERAL_NAME_push(cid->issuer_serial->issuer, name))
880 			goto err;
881 		name = NULL;	/* Ownership is lost. */
882 		/* Setting the serial number. */
883 		ASN1_INTEGER_free(cid->issuer_serial->serial);
884 		if (!(cid->issuer_serial->serial =
885 		    ASN1_INTEGER_dup(cert->cert_info->serialNumber)))
886 			goto err;
887 	}
888 
889 	return cid;
890 
891 err:
892 	GENERAL_NAME_free(name);
893 	ESS_CERT_ID_free(cid);
894 	TSerror(ERR_R_MALLOC_FAILURE);
895 	return NULL;
896 }
897 
898 static int
899 TS_TST_INFO_content_new(PKCS7 *p7)
900 {
901 	PKCS7 *ret = NULL;
902 	ASN1_OCTET_STRING *octet_string = NULL;
903 
904 	/* Create new encapsulated NID_id_smime_ct_TSTInfo content. */
905 	if (!(ret = PKCS7_new()))
906 		goto err;
907 	if (!(ret->d.other = ASN1_TYPE_new()))
908 		goto err;
909 	ret->type = OBJ_nid2obj(NID_id_smime_ct_TSTInfo);
910 	if (!(octet_string = ASN1_OCTET_STRING_new()))
911 		goto err;
912 	ASN1_TYPE_set(ret->d.other, V_ASN1_OCTET_STRING, octet_string);
913 	octet_string = NULL;
914 
915 	/* Add encapsulated content to signed PKCS7 structure. */
916 	if (!PKCS7_set_content(p7, ret))
917 		goto err;
918 
919 	return 1;
920 
921 err:
922 	ASN1_OCTET_STRING_free(octet_string);
923 	PKCS7_free(ret);
924 	return 0;
925 }
926 
927 static int
928 ESS_add_signing_cert(PKCS7_SIGNER_INFO *si, ESS_SIGNING_CERT *sc)
929 {
930 	ASN1_STRING *seq = NULL;
931 	unsigned char *p, *pp = NULL;
932 	int len;
933 
934 	len = i2d_ESS_SIGNING_CERT(sc, NULL);
935 	if (!(pp = malloc(len))) {
936 		TSerror(ERR_R_MALLOC_FAILURE);
937 		goto err;
938 	}
939 	p = pp;
940 	i2d_ESS_SIGNING_CERT(sc, &p);
941 	if (!(seq = ASN1_STRING_new()) || !ASN1_STRING_set(seq, pp, len)) {
942 		TSerror(ERR_R_MALLOC_FAILURE);
943 		goto err;
944 	}
945 	free(pp);
946 	pp = NULL;
947 	return PKCS7_add_signed_attribute(si,
948 	    NID_id_smime_aa_signingCertificate, V_ASN1_SEQUENCE, seq);
949 
950 err:
951 	ASN1_STRING_free(seq);
952 	free(pp);
953 
954 	return 0;
955 }
956 
957 
958 static ASN1_GENERALIZEDTIME *
959 TS_RESP_set_genTime_with_precision(ASN1_GENERALIZEDTIME *asn1_time,
960     time_t sec, long usec, unsigned precision)
961 {
962 	struct tm *tm = NULL;
963 	char genTime_str[17 + TS_MAX_CLOCK_PRECISION_DIGITS];
964 	char usecstr[TS_MAX_CLOCK_PRECISION_DIGITS + 2];
965 	char *p;
966 	int rv;
967 
968 	if (precision > TS_MAX_CLOCK_PRECISION_DIGITS)
969 		goto err;
970 
971 	if (!(tm = gmtime(&sec)))
972 		goto err;
973 
974 	/*
975 	 * Put "genTime_str" in GeneralizedTime format.  We work around the
976 	 * restrictions imposed by rfc3280 (i.e. "GeneralizedTime values MUST
977 	 * NOT include fractional seconds") and OpenSSL related functions to
978 	 * meet the rfc3161 requirement: "GeneralizedTime syntax can include
979 	 * fraction-of-second details".
980 	 */
981 	if (precision > 0) {
982 		/* To make things a bit harder, X.690 | ISO/IEC 8825-1 provides
983 		   the following restrictions for a DER-encoding, which OpenSSL
984 		   (specifically ASN1_GENERALIZEDTIME_check() function) doesn't
985 		   support:
986 		   "The encoding MUST terminate with a "Z" (which means "Zulu"
987 		   time). The decimal point element, if present, MUST be the
988 		   point option ".". The fractional-seconds elements,
989 		   if present, MUST omit all trailing 0's;
990 		   if the elements correspond to 0, they MUST be wholly
991 		   omitted, and the decimal point element also MUST be
992 		   omitted." */
993 		(void) snprintf(usecstr, sizeof(usecstr), ".%06ld", usec);
994 		/* truncate and trim trailing 0 */
995 		usecstr[precision + 1] = '\0';
996 		p = usecstr + strlen(usecstr) - 1;
997 		while (p > usecstr && *p == '0')
998 			*p-- = '\0';
999 		/* if we've reached the beginning, delete the . too */
1000 		if (p == usecstr)
1001 			*p = '\0';
1002 
1003 	} else {
1004 		/* empty */
1005 		usecstr[0] = '\0';
1006 	}
1007 	rv = snprintf(genTime_str, sizeof(genTime_str),
1008 	    "%04d%02d%02d%02d%02d%02d%sZ",
1009 	    tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1010 	    tm->tm_hour, tm->tm_min, tm->tm_sec, usecstr);
1011 	if (rv < 0 || rv >= sizeof(genTime_str))
1012 		goto err;
1013 
1014 	/* Now call OpenSSL to check and set our genTime value */
1015 	if (!asn1_time && !(asn1_time = ASN1_GENERALIZEDTIME_new()))
1016 		goto err;
1017 	if (!ASN1_GENERALIZEDTIME_set_string(asn1_time, genTime_str)) {
1018 		ASN1_GENERALIZEDTIME_free(asn1_time);
1019 		goto err;
1020 	}
1021 
1022 	return asn1_time;
1023 
1024 err:
1025 	TSerror(TS_R_COULD_NOT_SET_TIME);
1026 	return NULL;
1027 }
1028