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