1 /* $OpenBSD: ts_rsp_verify.c,v 1.28 2022/07/24 08:16:47 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 <stdio.h>
60 #include <string.h>
61 
62 #include <openssl/err.h>
63 #include <openssl/objects.h>
64 #include <openssl/pkcs7.h>
65 #include <openssl/ts.h>
66 
67 #include "evp_locl.h"
68 #include "ts_local.h"
69 #include "x509_lcl.h"
70 
71 /* Private function declarations. */
72 
73 static int TS_verify_cert(X509_STORE *store, STACK_OF(X509) *untrusted,
74     X509 *signer, STACK_OF(X509) **chain);
75 static int TS_check_signing_certs(PKCS7_SIGNER_INFO *si, STACK_OF(X509) *chain);
76 static ESS_SIGNING_CERT *ESS_get_signing_cert(PKCS7_SIGNER_INFO *si);
77 static int TS_find_cert(STACK_OF(ESS_CERT_ID) *cert_ids, X509 *cert);
78 static ESS_SIGNING_CERT_V2 *ESS_get_signing_cert_v2(PKCS7_SIGNER_INFO *si);
79 static int TS_find_cert_v2(STACK_OF(ESS_CERT_ID_V2) *cert_ids, X509 *cert);
80 static int TS_issuer_serial_cmp(ESS_ISSUER_SERIAL *is, X509 *cert);
81 static int int_TS_RESP_verify_token(TS_VERIFY_CTX *ctx,
82     PKCS7 *token, TS_TST_INFO *tst_info);
83 static int TS_check_status_info(TS_RESP *response);
84 static char *TS_get_status_text(STACK_OF(ASN1_UTF8STRING) *text);
85 static int TS_check_policy(ASN1_OBJECT *req_oid, TS_TST_INFO *tst_info);
86 static int TS_compute_imprint(BIO *data, TS_TST_INFO *tst_info,
87     X509_ALGOR **md_alg,
88     unsigned char **imprint, unsigned *imprint_len);
89 static int TS_check_imprints(X509_ALGOR *algor_a,
90     unsigned char *imprint_a, unsigned len_a,
91     TS_TST_INFO *tst_info);
92 static int TS_check_nonces(const ASN1_INTEGER *a, TS_TST_INFO *tst_info);
93 static int TS_check_signer_name(GENERAL_NAME *tsa_name, X509 *signer);
94 static int TS_find_name(STACK_OF(GENERAL_NAME) *gen_names, GENERAL_NAME *name);
95 
96 /*
97  * Local mapping between response codes and descriptions.
98  * Don't forget to change TS_STATUS_BUF_SIZE when modifying
99  * the elements of this array.
100  */
101 static const char *TS_status_text[] = {
102 	"granted",
103 	"grantedWithMods",
104 	"rejection",
105 	"waiting",
106 	"revocationWarning",
107 	"revocationNotification"
108 };
109 
110 #define TS_STATUS_TEXT_SIZE	(sizeof(TS_status_text)/sizeof(*TS_status_text))
111 
112 /*
113  * This must be greater or equal to the sum of the strings in TS_status_text
114  * plus the number of its elements.
115  */
116 #define TS_STATUS_BUF_SIZE	256
117 
118 static struct {
119 	int code;
120 	const char *text;
121 } TS_failure_info[] = {
122 	{ TS_INFO_BAD_ALG, "badAlg" },
123 	{ TS_INFO_BAD_REQUEST, "badRequest" },
124 	{ TS_INFO_BAD_DATA_FORMAT, "badDataFormat" },
125 	{ TS_INFO_TIME_NOT_AVAILABLE, "timeNotAvailable" },
126 	{ TS_INFO_UNACCEPTED_POLICY, "unacceptedPolicy" },
127 	{ TS_INFO_UNACCEPTED_EXTENSION, "unacceptedExtension" },
128 	{ TS_INFO_ADD_INFO_NOT_AVAILABLE, "addInfoNotAvailable" },
129 	{ TS_INFO_SYSTEM_FAILURE, "systemFailure" }
130 };
131 
132 #define TS_FAILURE_INFO_SIZE	(sizeof(TS_failure_info) / \
133 				sizeof(*TS_failure_info))
134 
135 /* Functions for verifying a signed TS_TST_INFO structure. */
136 
137 /*
138  * This function carries out the following tasks:
139  *	- Checks if there is one and only one signer.
140  *	- Search for the signing certificate in 'certs' and in the response.
141  *	- Check the extended key usage and key usage fields of the signer
142  *	certificate (done by the path validation).
143  *	- Build and validate the certificate path.
144  *	- Check if the certificate path meets the requirements of the
145  *	SigningCertificate ESS signed attribute.
146  *	- Verify the signature value.
147  *	- Returns the signer certificate in 'signer', if 'signer' is not NULL.
148  */
149 int
150 TS_RESP_verify_signature(PKCS7 *token, STACK_OF(X509) *certs,
151     X509_STORE *store, X509 **signer_out)
152 {
153 	STACK_OF(PKCS7_SIGNER_INFO) *sinfos = NULL;
154 	PKCS7_SIGNER_INFO *si;
155 	STACK_OF(X509) *signers = NULL;
156 	X509	*signer;
157 	STACK_OF(X509) *chain = NULL;
158 	char	buf[4096];
159 	int	i, j = 0, ret = 0;
160 	BIO	*p7bio = NULL;
161 
162 	/* Some sanity checks first. */
163 	if (!token) {
164 		TSerror(TS_R_INVALID_NULL_POINTER);
165 		goto err;
166 	}
167 
168 	/* Check for the correct content type */
169 	if (!PKCS7_type_is_signed(token)) {
170 		TSerror(TS_R_WRONG_CONTENT_TYPE);
171 		goto err;
172 	}
173 
174 	/* Check if there is one and only one signer. */
175 	sinfos = PKCS7_get_signer_info(token);
176 	if (!sinfos || sk_PKCS7_SIGNER_INFO_num(sinfos) != 1) {
177 		TSerror(TS_R_THERE_MUST_BE_ONE_SIGNER);
178 		goto err;
179 	}
180 	si = sk_PKCS7_SIGNER_INFO_value(sinfos, 0);
181 
182 	/* Check for no content: no data to verify signature. */
183 	if (PKCS7_get_detached(token)) {
184 		TSerror(TS_R_NO_CONTENT);
185 		goto err;
186 	}
187 
188 	/* Get hold of the signer certificate, search only internal
189 	   certificates if it was requested. */
190 	signers = PKCS7_get0_signers(token, certs, 0);
191 	if (!signers || sk_X509_num(signers) != 1)
192 		goto err;
193 	signer = sk_X509_value(signers, 0);
194 
195 	/* Now verify the certificate. */
196 	if (!TS_verify_cert(store, certs, signer, &chain))
197 		goto err;
198 
199 	/* Check if the signer certificate is consistent with the
200 	   ESS extension. */
201 	if (!TS_check_signing_certs(si, chain))
202 		goto err;
203 
204 	/* Creating the message digest. */
205 	p7bio = PKCS7_dataInit(token, NULL);
206 
207 	/* We now have to 'read' from p7bio to calculate digests etc. */
208 	while ((i = BIO_read(p7bio, buf, sizeof(buf))) > 0)
209 		;
210 
211 	/* Verifying the signature. */
212 	j = PKCS7_signatureVerify(p7bio, token, si, signer);
213 	if (j <= 0) {
214 		TSerror(TS_R_SIGNATURE_FAILURE);
215 		goto err;
216 	}
217 
218 	/* Return the signer certificate if needed. */
219 	if (signer_out) {
220 		*signer_out = signer;
221 		CRYPTO_add(&signer->references, 1, CRYPTO_LOCK_X509);
222 	}
223 
224 	ret = 1;
225 
226 err:
227 	BIO_free_all(p7bio);
228 	sk_X509_pop_free(chain, X509_free);
229 	sk_X509_free(signers);
230 
231 	return ret;
232 }
233 
234 /*
235  * The certificate chain is returned in chain. Caller is responsible for
236  * freeing the vector.
237  */
238 static int
239 TS_verify_cert(X509_STORE *store, STACK_OF(X509) *untrusted, X509 *signer,
240     STACK_OF(X509) **chain)
241 {
242 	X509_STORE_CTX cert_ctx;
243 	int i;
244 	int ret = 0;
245 
246 	/* chain is an out argument. */
247 	*chain = NULL;
248 	if (X509_STORE_CTX_init(&cert_ctx, store, signer, untrusted) == 0) {
249 		TSerror(ERR_R_X509_LIB);
250 		goto err;
251 	}
252 	if (X509_STORE_CTX_set_purpose(&cert_ctx,
253 	    X509_PURPOSE_TIMESTAMP_SIGN) == 0)
254 		goto err;
255 	i = X509_verify_cert(&cert_ctx);
256 	if (i <= 0) {
257 		int j = X509_STORE_CTX_get_error(&cert_ctx);
258 
259 		TSerror(TS_R_CERTIFICATE_VERIFY_ERROR);
260 		ERR_asprintf_error_data("Verify error:%s",
261 		    X509_verify_cert_error_string(j));
262 		goto err;
263 	} else {
264 		/* Get a copy of the certificate chain. */
265 		*chain = X509_STORE_CTX_get1_chain(&cert_ctx);
266 		ret = 1;
267 	}
268 
269 err:
270 	X509_STORE_CTX_cleanup(&cert_ctx);
271 
272 	return ret;
273 }
274 
275 static int
276 TS_check_signing_certs(PKCS7_SIGNER_INFO *si, STACK_OF(X509) *chain)
277 {
278 	ESS_SIGNING_CERT *ss = NULL;
279 	STACK_OF(ESS_CERT_ID) *cert_ids;
280 	ESS_SIGNING_CERT_V2 *ssv2 = NULL;
281 	STACK_OF(ESS_CERT_ID_V2) *cert_ids_v2;
282 	X509 *cert;
283 	int i = 0;
284 	int ret = 0;
285 
286 	if ((ss = ESS_get_signing_cert(si)) != NULL) {
287 		cert_ids = ss->cert_ids;
288 		/* The signer certificate must be the first in cert_ids. */
289 		cert = sk_X509_value(chain, 0);
290 
291 		if (TS_find_cert(cert_ids, cert) != 0)
292 			goto err;
293 
294 		/*
295 		 * Check the other certificates of the chain if there are more
296 		 * than one certificate ids in cert_ids.
297 		 */
298 		if (sk_ESS_CERT_ID_num(cert_ids) > 1) {
299 			/* All the certificates of the chain must be in cert_ids. */
300 			for (i = 1; i < sk_X509_num(chain); i++) {
301 				cert = sk_X509_value(chain, i);
302 
303 				if (TS_find_cert(cert_ids, cert) < 0)
304 					goto err;
305 			}
306 		}
307 	}
308 
309 	if ((ssv2 = ESS_get_signing_cert_v2(si)) != NULL) {
310 		cert_ids_v2 = ssv2->cert_ids;
311 		/* The signer certificate must be the first in cert_ids_v2. */
312 		cert = sk_X509_value(chain, 0);
313 
314 		if (TS_find_cert_v2(cert_ids_v2, cert) != 0)
315 			goto err;
316 
317 		/*
318 		 * Check the other certificates of the chain if there are more
319 		 * than one certificate ids in cert_ids_v2.
320 		 */
321 		if (sk_ESS_CERT_ID_V2_num(cert_ids_v2) > 1) {
322 			/* All the certificates of the chain must be in cert_ids_v2. */
323 			for (i = 1; i < sk_X509_num(chain); i++) {
324 				cert = sk_X509_value(chain, i);
325 
326 				if (TS_find_cert_v2(cert_ids_v2, cert) < 0)
327 					goto err;
328 			}
329 		}
330 	}
331 
332 	ret = 1;
333 
334 err:
335 	if (!ret)
336 		TSerror(TS_R_ESS_SIGNING_CERTIFICATE_ERROR);
337 	ESS_SIGNING_CERT_free(ss);
338 	ESS_SIGNING_CERT_V2_free(ssv2);
339 	return ret;
340 }
341 
342 static ESS_SIGNING_CERT *
343 ESS_get_signing_cert(PKCS7_SIGNER_INFO *si)
344 {
345 	ASN1_TYPE *attr;
346 	const unsigned char *p;
347 
348 	attr = PKCS7_get_signed_attribute(si,
349 	    NID_id_smime_aa_signingCertificate);
350 	if (!attr)
351 		return NULL;
352 	if (attr->type != V_ASN1_SEQUENCE)
353 		return NULL;
354 	p = attr->value.sequence->data;
355 	return d2i_ESS_SIGNING_CERT(NULL, &p, attr->value.sequence->length);
356 }
357 
358 static ESS_SIGNING_CERT_V2 *
359 ESS_get_signing_cert_v2(PKCS7_SIGNER_INFO *si)
360 {
361 	ASN1_TYPE *attr;
362 	const unsigned char *p;
363 
364 	attr = PKCS7_get_signed_attribute(si, NID_id_smime_aa_signingCertificateV2);
365 	if (attr == NULL)
366 		return NULL;
367 	p = attr->value.sequence->data;
368 	return d2i_ESS_SIGNING_CERT_V2(NULL, &p, attr->value.sequence->length);
369 }
370 
371 /* Returns < 0 if certificate is not found, certificate index otherwise. */
372 static int
373 TS_find_cert(STACK_OF(ESS_CERT_ID) *cert_ids, X509 *cert)
374 {
375 	int i;
376 	unsigned char cert_hash[TS_HASH_LEN];
377 
378 	if (!cert_ids || !cert)
379 		return -1;
380 
381 	if (!X509_digest(cert, TS_HASH_EVP, cert_hash, NULL))
382 		return -1;
383 
384 	/* Recompute SHA1 hash of certificate if necessary (side effect). */
385 	if (X509_check_purpose(cert, -1, 0) == -1)
386 		return -1;
387 
388 	/* Look for cert in the cert_ids vector. */
389 	for (i = 0; i < sk_ESS_CERT_ID_num(cert_ids); ++i) {
390 		ESS_CERT_ID *cid = sk_ESS_CERT_ID_value(cert_ids, i);
391 
392 		/* Check the SHA-1 hash first. */
393 		if (cid->hash->length == TS_HASH_LEN && !memcmp(cid->hash->data,
394 		    cert_hash, TS_HASH_LEN)) {
395 			/* Check the issuer/serial as well if specified. */
396 			ESS_ISSUER_SERIAL *is = cid->issuer_serial;
397 
398 			if (is == NULL || TS_issuer_serial_cmp(is, cert) == 0)
399 				return i;
400 		}
401 	}
402 
403 	return -1;
404 }
405 
406 /* Returns < 0 if certificate is not found, certificate index otherwise. */
407 static int
408 TS_find_cert_v2(STACK_OF(ESS_CERT_ID_V2) *cert_ids, X509 *cert)
409 {
410 	int i;
411 	unsigned char cert_digest[EVP_MAX_MD_SIZE];
412 	unsigned int len;
413 
414 	/* Look for cert in the cert_ids vector. */
415 	for (i = 0; i < sk_ESS_CERT_ID_V2_num(cert_ids); ++i) {
416 		ESS_CERT_ID_V2 *cid = sk_ESS_CERT_ID_V2_value(cert_ids, i);
417 		const EVP_MD *md = EVP_sha256();
418 
419 		if (cid->hash_alg != NULL)
420 			md = EVP_get_digestbyobj(cid->hash_alg->algorithm);
421 		if (md == NULL)
422 			return -1;
423 
424 		if (!X509_digest(cert, md, cert_digest, &len))
425 			return -1;
426 
427 		if ((unsigned int)cid->hash->length != len)
428 			return -1;
429 
430 		if (memcmp(cid->hash->data, cert_digest, cid->hash->length) == 0) {
431 			ESS_ISSUER_SERIAL *is = cid->issuer_serial;
432 
433 			if (is == NULL || TS_issuer_serial_cmp(is, cert) == 0)
434 				return i;
435 		}
436 	}
437 
438 	return -1;
439 }
440 
441 static int
442 TS_issuer_serial_cmp(ESS_ISSUER_SERIAL *is, X509 *cert)
443 {
444 	GENERAL_NAME *issuer;
445 
446 	if (is == NULL || cert == NULL || sk_GENERAL_NAME_num(is->issuer) != 1)
447 		return -1;
448 
449 	/* Check the issuer first. It must be a directory name. */
450 	issuer = sk_GENERAL_NAME_value(is->issuer, 0);
451 	if (issuer->type != GEN_DIRNAME ||
452 	    X509_NAME_cmp(issuer->d.dirn, X509_get_issuer_name(cert)))
453 		return -1;
454 
455 	/* Check the serial number, too. */
456 	if (ASN1_INTEGER_cmp(is->serial, X509_get_serialNumber(cert)))
457 		return -1;
458 
459 	return 0;
460 }
461 
462 /*
463  * Verifies whether 'response' contains a valid response with regards
464  * to the settings of the context:
465  *	- Gives an error message if the TS_TST_INFO is not present.
466  *	- Calls _TS_RESP_verify_token to verify the token content.
467  */
468 int
469 TS_RESP_verify_response(TS_VERIFY_CTX *ctx, TS_RESP *response)
470 {
471 	PKCS7 *token = TS_RESP_get_token(response);
472 	TS_TST_INFO *tst_info = TS_RESP_get_tst_info(response);
473 	int ret = 0;
474 
475 	/* Check if we have a successful TS_TST_INFO object in place. */
476 	if (!TS_check_status_info(response))
477 		goto err;
478 
479 	/* Check the contents of the time stamp token. */
480 	if (!int_TS_RESP_verify_token(ctx, token, tst_info))
481 		goto err;
482 
483 	ret = 1;
484 
485 err:
486 	return ret;
487 }
488 
489 /*
490  * Tries to extract a TS_TST_INFO structure from the PKCS7 token and
491  * calls the internal int_TS_RESP_verify_token function for verifying it.
492  */
493 int
494 TS_RESP_verify_token(TS_VERIFY_CTX *ctx, PKCS7 *token)
495 {
496 	TS_TST_INFO *tst_info = PKCS7_to_TS_TST_INFO(token);
497 	int ret = 0;
498 
499 	if (tst_info) {
500 		ret = int_TS_RESP_verify_token(ctx, token, tst_info);
501 		TS_TST_INFO_free(tst_info);
502 	}
503 	return ret;
504 }
505 
506 /*
507  * Verifies whether the 'token' contains a valid time stamp token
508  * with regards to the settings of the context. Only those checks are
509  * carried out that are specified in the context:
510  *	- Verifies the signature of the TS_TST_INFO.
511  *	- Checks the version number of the response.
512  *	- Check if the requested and returned policies math.
513  *	- Check if the message imprints are the same.
514  *	- Check if the nonces are the same.
515  *	- Check if the TSA name matches the signer.
516  *	- Check if the TSA name is the expected TSA.
517  */
518 static int
519 int_TS_RESP_verify_token(TS_VERIFY_CTX *ctx, PKCS7 *token,
520     TS_TST_INFO *tst_info)
521 {
522 	X509 *signer = NULL;
523 	GENERAL_NAME *tsa_name = TS_TST_INFO_get_tsa(tst_info);
524 	X509_ALGOR *md_alg = NULL;
525 	unsigned char *imprint = NULL;
526 	unsigned imprint_len = 0;
527 	int ret = 0;
528 
529 	/* Verify the signature. */
530 	if ((ctx->flags & TS_VFY_SIGNATURE) &&
531 	    !TS_RESP_verify_signature(token, ctx->certs, ctx->store, &signer))
532 		goto err;
533 
534 	/* Check version number of response. */
535 	if ((ctx->flags & TS_VFY_VERSION) &&
536 	    TS_TST_INFO_get_version(tst_info) != 1) {
537 		TSerror(TS_R_UNSUPPORTED_VERSION);
538 		goto err;
539 	}
540 
541 	/* Check policies. */
542 	if ((ctx->flags & TS_VFY_POLICY) &&
543 	    !TS_check_policy(ctx->policy, tst_info))
544 		goto err;
545 
546 	/* Check message imprints. */
547 	if ((ctx->flags & TS_VFY_IMPRINT) &&
548 	    !TS_check_imprints(ctx->md_alg, ctx->imprint, ctx->imprint_len,
549 		tst_info))
550 		goto err;
551 
552 	/* Compute and check message imprints. */
553 	if ((ctx->flags & TS_VFY_DATA) &&
554 	    (!TS_compute_imprint(ctx->data, tst_info,
555 	    &md_alg, &imprint, &imprint_len) ||
556 	    !TS_check_imprints(md_alg, imprint, imprint_len, tst_info)))
557 		goto err;
558 
559 	/* Check nonces. */
560 	if ((ctx->flags & TS_VFY_NONCE) &&
561 	    !TS_check_nonces(ctx->nonce, tst_info))
562 		goto err;
563 
564 	/* Check whether TSA name and signer certificate match. */
565 	if ((ctx->flags & TS_VFY_SIGNER) &&
566 	    tsa_name && !TS_check_signer_name(tsa_name, signer)) {
567 		TSerror(TS_R_TSA_NAME_MISMATCH);
568 		goto err;
569 	}
570 
571 	/* Check whether the TSA is the expected one. */
572 	if ((ctx->flags & TS_VFY_TSA_NAME) &&
573 	    !TS_check_signer_name(ctx->tsa_name, signer)) {
574 		TSerror(TS_R_TSA_UNTRUSTED);
575 		goto err;
576 	}
577 
578 	ret = 1;
579 
580 err:
581 	X509_free(signer);
582 	X509_ALGOR_free(md_alg);
583 	free(imprint);
584 	return ret;
585 }
586 
587 static int
588 TS_check_status_info(TS_RESP *response)
589 {
590 	TS_STATUS_INFO *info = TS_RESP_get_status_info(response);
591 	long status = ASN1_INTEGER_get(info->status);
592 	const char *status_text = NULL;
593 	char *embedded_status_text = NULL;
594 	char failure_text[TS_STATUS_BUF_SIZE] = "";
595 
596 	/* Check if everything went fine. */
597 	if (status == 0 || status == 1)
598 		return 1;
599 
600 	/* There was an error, get the description in status_text. */
601 	if (0 <= status && status < (long)TS_STATUS_TEXT_SIZE)
602 		status_text = TS_status_text[status];
603 	else
604 		status_text = "unknown code";
605 
606 	/* Set the embedded_status_text to the returned description. */
607 	if (sk_ASN1_UTF8STRING_num(info->text) > 0 &&
608 	    !(embedded_status_text = TS_get_status_text(info->text)))
609 		return 0;
610 
611 	/* Filling in failure_text with the failure information. */
612 	if (info->failure_info) {
613 		int i;
614 		int first = 1;
615 		for (i = 0; i < (int)TS_FAILURE_INFO_SIZE; ++i) {
616 			if (ASN1_BIT_STRING_get_bit(info->failure_info,
617 			    TS_failure_info[i].code)) {
618 				if (!first)
619 					strlcat(failure_text, ",",
620 					    TS_STATUS_BUF_SIZE);
621 				else
622 					first = 0;
623 				strlcat(failure_text, TS_failure_info[i].text,
624 				    TS_STATUS_BUF_SIZE);
625 			}
626 		}
627 	}
628 	if (failure_text[0] == '\0')
629 		strlcpy(failure_text, "unspecified", TS_STATUS_BUF_SIZE);
630 
631 	/* Making up the error string. */
632 	TSerror(TS_R_NO_TIME_STAMP_TOKEN);
633 	ERR_asprintf_error_data
634 	    ("status code: %s, status text: %s, failure codes: %s",
635 	    status_text,
636 	    embedded_status_text ? embedded_status_text : "unspecified",
637 	    failure_text);
638 	free(embedded_status_text);
639 
640 	return 0;
641 }
642 
643 static char *
644 TS_get_status_text(STACK_OF(ASN1_UTF8STRING) *text)
645 {
646 	int i;
647 	unsigned int length = 0;
648 	char *result = NULL;
649 
650 	/* Determine length first. */
651 	for (i = 0; i < sk_ASN1_UTF8STRING_num(text); ++i) {
652 		ASN1_UTF8STRING *current = sk_ASN1_UTF8STRING_value(text, i);
653 		length += ASN1_STRING_length(current);
654 		length += 1;	/* separator character */
655 	}
656 	/* Allocate memory (closing '\0' included). */
657 	if (!(result = malloc(length))) {
658 		TSerror(ERR_R_MALLOC_FAILURE);
659 		return NULL;
660 	}
661 	/* Concatenate the descriptions. */
662 	result[0] = '\0';
663 	for (i = 0; i < sk_ASN1_UTF8STRING_num(text); ++i) {
664 		ASN1_UTF8STRING *current = sk_ASN1_UTF8STRING_value(text, i);
665 		if (i > 0)
666 			strlcat(result, "/", length);
667 		strlcat(result, (const char *)ASN1_STRING_data(current), length);
668 	}
669 	return result;
670 }
671 
672 static int
673 TS_check_policy(ASN1_OBJECT *req_oid, TS_TST_INFO *tst_info)
674 {
675 	ASN1_OBJECT *resp_oid = TS_TST_INFO_get_policy_id(tst_info);
676 
677 	if (OBJ_cmp(req_oid, resp_oid) != 0) {
678 		TSerror(TS_R_POLICY_MISMATCH);
679 		return 0;
680 	}
681 
682 	return 1;
683 }
684 
685 static int
686 TS_compute_imprint(BIO *data, TS_TST_INFO *tst_info, X509_ALGOR **out_md_alg,
687     unsigned char **out_imprint, unsigned int *out_imprint_len)
688 {
689 	TS_MSG_IMPRINT *msg_imprint;
690 	X509_ALGOR *md_alg_resp;
691 	X509_ALGOR *md_alg = NULL;
692 	unsigned char *imprint = NULL;
693 	unsigned int imprint_len = 0;
694 	const EVP_MD *md;
695 	EVP_MD_CTX md_ctx;
696 	unsigned char buffer[4096];
697 	int length;
698 
699 	*out_md_alg = NULL;
700 	*out_imprint = NULL;
701 	*out_imprint_len = 0;
702 
703 	/* Retrieve the MD algorithm of the response. */
704 	msg_imprint = TS_TST_INFO_get_msg_imprint(tst_info);
705 	md_alg_resp = TS_MSG_IMPRINT_get_algo(msg_imprint);
706 	if ((md_alg = X509_ALGOR_dup(md_alg_resp)) == NULL)
707 		goto err;
708 
709 	/* Getting the MD object. */
710 	if ((md = EVP_get_digestbyobj((md_alg)->algorithm)) == NULL) {
711 		TSerror(TS_R_UNSUPPORTED_MD_ALGORITHM);
712 		goto err;
713 	}
714 
715 	/* Compute message digest. */
716 	if ((length = EVP_MD_size(md)) < 0)
717 		goto err;
718 	imprint_len = length;
719 	if ((imprint = malloc(imprint_len)) == NULL) {
720 		TSerror(ERR_R_MALLOC_FAILURE);
721 		goto err;
722 	}
723 
724 	if (!EVP_DigestInit(&md_ctx, md))
725 		goto err;
726 	while ((length = BIO_read(data, buffer, sizeof(buffer))) > 0) {
727 		if (!EVP_DigestUpdate(&md_ctx, buffer, length))
728 			goto err;
729 	}
730 	if (!EVP_DigestFinal(&md_ctx, imprint, NULL))
731 		goto err;
732 
733 	*out_md_alg = md_alg;
734 	md_alg = NULL;
735 	*out_imprint = imprint;
736 	imprint = NULL;
737 	*out_imprint_len = imprint_len;
738 
739 	return 1;
740 
741 err:
742 	X509_ALGOR_free(md_alg);
743 	free(imprint);
744 	return 0;
745 }
746 
747 static int
748 TS_check_imprints(X509_ALGOR *algor_a, unsigned char *imprint_a, unsigned len_a,
749     TS_TST_INFO *tst_info)
750 {
751 	TS_MSG_IMPRINT *b = TS_TST_INFO_get_msg_imprint(tst_info);
752 	X509_ALGOR *algor_b = TS_MSG_IMPRINT_get_algo(b);
753 	int ret = 0;
754 
755 	/* algor_a is optional. */
756 	if (algor_a) {
757 		/* Compare algorithm OIDs. */
758 		if (OBJ_cmp(algor_a->algorithm, algor_b->algorithm))
759 			goto err;
760 
761 		/* The parameter must be NULL in both. */
762 		if ((algor_a->parameter &&
763 		    ASN1_TYPE_get(algor_a->parameter) != V_ASN1_NULL) ||
764 		    (algor_b->parameter &&
765 		    ASN1_TYPE_get(algor_b->parameter) != V_ASN1_NULL))
766 			goto err;
767 	}
768 
769 	/* Compare octet strings. */
770 	ret = len_a == (unsigned) ASN1_STRING_length(b->hashed_msg) &&
771 	    memcmp(imprint_a, ASN1_STRING_data(b->hashed_msg), len_a) == 0;
772 
773 err:
774 	if (!ret)
775 		TSerror(TS_R_MESSAGE_IMPRINT_MISMATCH);
776 	return ret;
777 }
778 
779 static int
780 TS_check_nonces(const ASN1_INTEGER *a, TS_TST_INFO *tst_info)
781 {
782 	const ASN1_INTEGER *b = TS_TST_INFO_get_nonce(tst_info);
783 
784 	/* Error if nonce is missing. */
785 	if (!b) {
786 		TSerror(TS_R_NONCE_NOT_RETURNED);
787 		return 0;
788 	}
789 
790 	/* No error if a nonce is returned without being requested. */
791 	if (ASN1_INTEGER_cmp(a, b) != 0) {
792 		TSerror(TS_R_NONCE_MISMATCH);
793 		return 0;
794 	}
795 
796 	return 1;
797 }
798 
799 /* Check if the specified TSA name matches either the subject
800    or one of the subject alternative names of the TSA certificate. */
801 static int
802 TS_check_signer_name(GENERAL_NAME *tsa_name, X509 *signer)
803 {
804 	STACK_OF(GENERAL_NAME) *gen_names = NULL;
805 	int idx = -1;
806 	int found = 0;
807 
808 	if (signer == NULL)
809 		return 0;
810 
811 	/* Check the subject name first. */
812 	if (tsa_name->type == GEN_DIRNAME &&
813 	    X509_name_cmp(tsa_name->d.dirn, X509_get_subject_name(signer)) == 0)
814 		return 1;
815 
816 	/* Check all the alternative names. */
817 	gen_names = X509_get_ext_d2i(signer, NID_subject_alt_name,
818 	    NULL, &idx);
819 	while (gen_names != NULL &&
820 	    !(found = (TS_find_name(gen_names, tsa_name) >= 0))) {
821 		/* Get the next subject alternative name,
822 		   although there should be no more than one. */
823 		GENERAL_NAMES_free(gen_names);
824 		gen_names = X509_get_ext_d2i(signer, NID_subject_alt_name,
825 		    NULL, &idx);
826 	}
827 	if (gen_names)
828 		GENERAL_NAMES_free(gen_names);
829 
830 	return found;
831 }
832 
833 /* Returns 1 if name is in gen_names, 0 otherwise. */
834 static int
835 TS_find_name(STACK_OF(GENERAL_NAME) *gen_names, GENERAL_NAME *name)
836 {
837 	int i, found;
838 	for (i = 0, found = 0; !found && i < sk_GENERAL_NAME_num(gen_names);
839 	    ++i) {
840 		GENERAL_NAME *current = sk_GENERAL_NAME_value(gen_names, i);
841 		found = GENERAL_NAME_cmp(current, name) == 0;
842 	}
843 	return found ? i - 1 : -1;
844 }
845