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