xref: /freebsd/crypto/openssl/crypto/ts/ts_rsp_sign.c (revision 4f52dfbb)
1 /* crypto/ts/ts_resp_sign.c */
2 /*
3  * Written by Zoltan Glozik (zglozik@stones.com) for the OpenSSL project
4  * 2002.
5  */
6 /* ====================================================================
7  * Copyright (c) 2006-2018 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    licensing@OpenSSL.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This product includes cryptographic software written by Eric Young
55  * (eay@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  *
58  */
59 
60 #include "cryptlib.h"
61 #include "o_time.h"
62 
63 #if defined(OPENSSL_SYS_UNIX)
64 # include <sys/time.h>
65 #endif
66 
67 #include <openssl/objects.h>
68 #include <openssl/ts.h>
69 #include <openssl/pkcs7.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 *, long *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
93 *TS_RESP_set_genTime_with_precision(ASN1_GENERALIZEDTIME *, long, long,
94                                     unsigned);
95 
96 /* Default callbacks for response generation. */
97 
98 static ASN1_INTEGER *def_serial_cb(struct TS_resp_ctx *ctx, void *data)
99 {
100     ASN1_INTEGER *serial = ASN1_INTEGER_new();
101     if (!serial)
102         goto err;
103     if (!ASN1_INTEGER_set(serial, 1))
104         goto err;
105     return serial;
106  err:
107     TSerr(TS_F_DEF_SERIAL_CB, ERR_R_MALLOC_FAILURE);
108     TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
109                                 "Error during serial number generation.");
110     return NULL;
111 }
112 
113 #if defined(OPENSSL_SYS_UNIX)
114 
115 /* Use the gettimeofday function call. */
116 static int def_time_cb(struct TS_resp_ctx *ctx, void *data,
117                        long *sec, long *usec)
118 {
119     struct timeval tv;
120     if (gettimeofday(&tv, NULL) != 0) {
121         TSerr(TS_F_DEF_TIME_CB, TS_R_TIME_SYSCALL_ERROR);
122         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
123                                     "Time is not available.");
124         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_TIME_NOT_AVAILABLE);
125         return 0;
126     }
127     /* Return time to caller. */
128     *sec = tv.tv_sec;
129     *usec = tv.tv_usec;
130 
131     return 1;
132 }
133 
134 #else
135 
136 /* Use the time function call that provides only seconds precision. */
137 static int def_time_cb(struct TS_resp_ctx *ctx, void *data,
138                        long *sec, long *usec)
139 {
140     time_t t;
141     if (time(&t) == (time_t)-1) {
142         TSerr(TS_F_DEF_TIME_CB, TS_R_TIME_SYSCALL_ERROR);
143         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
144                                     "Time is not available.");
145         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_TIME_NOT_AVAILABLE);
146         return 0;
147     }
148     /* Return time to caller, only second precision. */
149     *sec = (long)t;
150     *usec = 0;
151 
152     return 1;
153 }
154 
155 #endif
156 
157 static int def_extension_cb(struct TS_resp_ctx *ctx, X509_EXTENSION *ext,
158                             void *data)
159 {
160     /* No extensions are processed here. */
161     TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
162                                 "Unsupported extension.");
163     TS_RESP_CTX_add_failure_info(ctx, TS_INFO_UNACCEPTED_EXTENSION);
164     return 0;
165 }
166 
167 /* TS_RESP_CTX management functions. */
168 
169 TS_RESP_CTX *TS_RESP_CTX_new()
170 {
171     TS_RESP_CTX *ctx;
172 
173     if (!(ctx = (TS_RESP_CTX *)OPENSSL_malloc(sizeof(TS_RESP_CTX)))) {
174         TSerr(TS_F_TS_RESP_CTX_NEW, ERR_R_MALLOC_FAILURE);
175         return NULL;
176     }
177     memset(ctx, 0, sizeof(TS_RESP_CTX));
178 
179     /* Setting default callbacks. */
180     ctx->serial_cb = def_serial_cb;
181     ctx->time_cb = def_time_cb;
182     ctx->extension_cb = def_extension_cb;
183 
184     return ctx;
185 }
186 
187 void TS_RESP_CTX_free(TS_RESP_CTX *ctx)
188 {
189     if (!ctx)
190         return;
191 
192     X509_free(ctx->signer_cert);
193     EVP_PKEY_free(ctx->signer_key);
194     sk_X509_pop_free(ctx->certs, X509_free);
195     sk_ASN1_OBJECT_pop_free(ctx->policies, ASN1_OBJECT_free);
196     ASN1_OBJECT_free(ctx->default_policy);
197     sk_EVP_MD_free(ctx->mds);   /* No EVP_MD_free method exists. */
198     ASN1_INTEGER_free(ctx->seconds);
199     ASN1_INTEGER_free(ctx->millis);
200     ASN1_INTEGER_free(ctx->micros);
201     OPENSSL_free(ctx);
202 }
203 
204 int TS_RESP_CTX_set_signer_cert(TS_RESP_CTX *ctx, X509 *signer)
205 {
206     if (X509_check_purpose(signer, X509_PURPOSE_TIMESTAMP_SIGN, 0) != 1) {
207         TSerr(TS_F_TS_RESP_CTX_SET_SIGNER_CERT,
208               TS_R_INVALID_SIGNER_CERTIFICATE_PURPOSE);
209         return 0;
210     }
211     if (ctx->signer_cert)
212         X509_free(ctx->signer_cert);
213     ctx->signer_cert = signer;
214     CRYPTO_add(&ctx->signer_cert->references, +1, CRYPTO_LOCK_X509);
215     return 1;
216 }
217 
218 int TS_RESP_CTX_set_signer_key(TS_RESP_CTX *ctx, EVP_PKEY *key)
219 {
220     if (ctx->signer_key)
221         EVP_PKEY_free(ctx->signer_key);
222     ctx->signer_key = key;
223     CRYPTO_add(&ctx->signer_key->references, +1, CRYPTO_LOCK_EVP_PKEY);
224 
225     return 1;
226 }
227 
228 int TS_RESP_CTX_set_def_policy(TS_RESP_CTX *ctx, ASN1_OBJECT *def_policy)
229 {
230     if (ctx->default_policy)
231         ASN1_OBJECT_free(ctx->default_policy);
232     if (!(ctx->default_policy = OBJ_dup(def_policy)))
233         goto err;
234     return 1;
235  err:
236     TSerr(TS_F_TS_RESP_CTX_SET_DEF_POLICY, ERR_R_MALLOC_FAILURE);
237     return 0;
238 }
239 
240 int TS_RESP_CTX_set_certs(TS_RESP_CTX *ctx, STACK_OF(X509) *certs)
241 {
242 
243     if (ctx->certs) {
244         sk_X509_pop_free(ctx->certs, X509_free);
245         ctx->certs = NULL;
246     }
247     if (!certs)
248         return 1;
249     if (!(ctx->certs = X509_chain_up_ref(certs))) {
250         TSerr(TS_F_TS_RESP_CTX_SET_CERTS, ERR_R_MALLOC_FAILURE);
251         return 0;
252     }
253 
254     return 1;
255 }
256 
257 int TS_RESP_CTX_add_policy(TS_RESP_CTX *ctx, ASN1_OBJECT *policy)
258 {
259     ASN1_OBJECT *copy = NULL;
260 
261     /* Create new policy stack if necessary. */
262     if (!ctx->policies && !(ctx->policies = sk_ASN1_OBJECT_new_null()))
263         goto err;
264     if (!(copy = OBJ_dup(policy)))
265         goto err;
266     if (!sk_ASN1_OBJECT_push(ctx->policies, copy))
267         goto err;
268 
269     return 1;
270  err:
271     TSerr(TS_F_TS_RESP_CTX_ADD_POLICY, ERR_R_MALLOC_FAILURE);
272     ASN1_OBJECT_free(copy);
273     return 0;
274 }
275 
276 int TS_RESP_CTX_add_md(TS_RESP_CTX *ctx, const EVP_MD *md)
277 {
278     /* Create new md stack if necessary. */
279     if (!ctx->mds && !(ctx->mds = sk_EVP_MD_new_null()))
280         goto err;
281     /* Add the shared md, no copy needed. */
282     if (!sk_EVP_MD_push(ctx->mds, (EVP_MD *)md))
283         goto err;
284 
285     return 1;
286  err:
287     TSerr(TS_F_TS_RESP_CTX_ADD_MD, ERR_R_MALLOC_FAILURE);
288     return 0;
289 }
290 
291 #define TS_RESP_CTX_accuracy_free(ctx)          \
292         ASN1_INTEGER_free(ctx->seconds);        \
293         ctx->seconds = NULL;                    \
294         ASN1_INTEGER_free(ctx->millis);         \
295         ctx->millis = NULL;                     \
296         ASN1_INTEGER_free(ctx->micros);         \
297         ctx->micros = NULL;
298 
299 int TS_RESP_CTX_set_accuracy(TS_RESP_CTX *ctx,
300                              int secs, int millis, int micros)
301 {
302 
303     TS_RESP_CTX_accuracy_free(ctx);
304     if (secs && (!(ctx->seconds = ASN1_INTEGER_new())
305                  || !ASN1_INTEGER_set(ctx->seconds, secs)))
306         goto err;
307     if (millis && (!(ctx->millis = ASN1_INTEGER_new())
308                    || !ASN1_INTEGER_set(ctx->millis, millis)))
309         goto err;
310     if (micros && (!(ctx->micros = ASN1_INTEGER_new())
311                    || !ASN1_INTEGER_set(ctx->micros, micros)))
312         goto err;
313 
314     return 1;
315  err:
316     TS_RESP_CTX_accuracy_free(ctx);
317     TSerr(TS_F_TS_RESP_CTX_SET_ACCURACY, ERR_R_MALLOC_FAILURE);
318     return 0;
319 }
320 
321 void TS_RESP_CTX_add_flags(TS_RESP_CTX *ctx, int flags)
322 {
323     ctx->flags |= flags;
324 }
325 
326 void 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 TS_RESP_CTX_set_time_cb(TS_RESP_CTX *ctx, TS_time_cb cb, void *data)
333 {
334     ctx->time_cb = cb;
335     ctx->time_cb_data = data;
336 }
337 
338 void TS_RESP_CTX_set_extension_cb(TS_RESP_CTX *ctx,
339                                   TS_extension_cb cb, void *data)
340 {
341     ctx->extension_cb = cb;
342     ctx->extension_cb_data = data;
343 }
344 
345 int TS_RESP_CTX_set_status_info(TS_RESP_CTX *ctx,
346                                 int status, const char *text)
347 {
348     TS_STATUS_INFO *si = NULL;
349     ASN1_UTF8STRING *utf8_text = NULL;
350     int ret = 0;
351 
352     if (!(si = TS_STATUS_INFO_new()))
353         goto err;
354     if (!ASN1_INTEGER_set(si->status, status))
355         goto err;
356     if (text) {
357         if (!(utf8_text = ASN1_UTF8STRING_new())
358             || !ASN1_STRING_set(utf8_text, text, strlen(text)))
359             goto err;
360         if (!si->text && !(si->text = sk_ASN1_UTF8STRING_new_null()))
361             goto err;
362         if (!sk_ASN1_UTF8STRING_push(si->text, utf8_text))
363             goto err;
364         utf8_text = NULL;       /* Ownership is lost. */
365     }
366     if (!TS_RESP_set_status_info(ctx->response, si))
367         goto err;
368     ret = 1;
369  err:
370     if (!ret)
371         TSerr(TS_F_TS_RESP_CTX_SET_STATUS_INFO, ERR_R_MALLOC_FAILURE);
372     TS_STATUS_INFO_free(si);
373     ASN1_UTF8STRING_free(utf8_text);
374     return ret;
375 }
376 
377 int TS_RESP_CTX_set_status_info_cond(TS_RESP_CTX *ctx,
378                                      int status, const char *text)
379 {
380     int ret = 1;
381     TS_STATUS_INFO *si = TS_RESP_get_status_info(ctx->response);
382 
383     if (ASN1_INTEGER_get(si->status) == TS_STATUS_GRANTED) {
384         /* Status has not been set, set it now. */
385         ret = TS_RESP_CTX_set_status_info(ctx, status, text);
386     }
387     return ret;
388 }
389 
390 int TS_RESP_CTX_add_failure_info(TS_RESP_CTX *ctx, int failure)
391 {
392     TS_STATUS_INFO *si = TS_RESP_get_status_info(ctx->response);
393     if (!si->failure_info && !(si->failure_info = ASN1_BIT_STRING_new()))
394         goto err;
395     if (!ASN1_BIT_STRING_set_bit(si->failure_info, failure, 1))
396         goto err;
397     return 1;
398  err:
399     TSerr(TS_F_TS_RESP_CTX_ADD_FAILURE_INFO, ERR_R_MALLOC_FAILURE);
400     return 0;
401 }
402 
403 TS_REQ *TS_RESP_CTX_get_request(TS_RESP_CTX *ctx)
404 {
405     return ctx->request;
406 }
407 
408 TS_TST_INFO *TS_RESP_CTX_get_tst_info(TS_RESP_CTX *ctx)
409 {
410     return ctx->tst_info;
411 }
412 
413 int TS_RESP_CTX_set_clock_precision_digits(TS_RESP_CTX *ctx,
414                                            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 *TS_RESP_create_response(TS_RESP_CTX *ctx, BIO *req_bio)
424 {
425     ASN1_OBJECT *policy;
426     TS_RESP *response;
427     int result = 0;
428 
429     TS_RESP_CTX_init(ctx);
430 
431     /* Creating the response object. */
432     if (!(ctx->response = TS_RESP_new())) {
433         TSerr(TS_F_TS_RESP_CREATE_RESPONSE, ERR_R_MALLOC_FAILURE);
434         goto end;
435     }
436 
437     /* Parsing DER request. */
438     if (!(ctx->request = d2i_TS_REQ_bio(req_bio, NULL))) {
439         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
440                                     "Bad request format or " "system error.");
441         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_DATA_FORMAT);
442         goto end;
443     }
444 
445     /* Setting default status info. */
446     if (!TS_RESP_CTX_set_status_info(ctx, TS_STATUS_GRANTED, NULL))
447         goto end;
448 
449     /* Checking the request format. */
450     if (!TS_RESP_check_request(ctx))
451         goto end;
452 
453     /* Checking acceptable policies. */
454     if (!(policy = TS_RESP_get_policy(ctx)))
455         goto end;
456 
457     /* Creating the TS_TST_INFO object. */
458     if (!(ctx->tst_info = TS_RESP_create_tst_info(ctx, policy)))
459         goto end;
460 
461     /* Processing extensions. */
462     if (!TS_RESP_process_extensions(ctx))
463         goto end;
464 
465     /* Generating the signature. */
466     if (!TS_RESP_sign(ctx))
467         goto end;
468 
469     /* Everything was successful. */
470     result = 1;
471  end:
472     if (!result) {
473         TSerr(TS_F_TS_RESP_CREATE_RESPONSE, TS_R_RESPONSE_SETUP_ERROR);
474         if (ctx->response != NULL) {
475             if (TS_RESP_CTX_set_status_info_cond(ctx,
476                                                  TS_STATUS_REJECTION,
477                                                  "Error during response "
478                                                  "generation.") == 0) {
479                 TS_RESP_free(ctx->response);
480                 ctx->response = NULL;
481             }
482         }
483     }
484     response = ctx->response;
485     ctx->response = NULL;       /* Ownership will be returned to caller. */
486     TS_RESP_CTX_cleanup(ctx);
487     return response;
488 }
489 
490 /* Initializes the variable part of the context. */
491 static void TS_RESP_CTX_init(TS_RESP_CTX *ctx)
492 {
493     ctx->request = NULL;
494     ctx->response = NULL;
495     ctx->tst_info = NULL;
496 }
497 
498 /* Cleans up the variable part of the context. */
499 static void TS_RESP_CTX_cleanup(TS_RESP_CTX *ctx)
500 {
501     TS_REQ_free(ctx->request);
502     ctx->request = NULL;
503     TS_RESP_free(ctx->response);
504     ctx->response = NULL;
505     TS_TST_INFO_free(ctx->tst_info);
506     ctx->tst_info = NULL;
507 }
508 
509 /* Checks the format and content of the request. */
510 static int TS_RESP_check_request(TS_RESP_CTX *ctx)
511 {
512     TS_REQ *request = ctx->request;
513     TS_MSG_IMPRINT *msg_imprint;
514     X509_ALGOR *md_alg;
515     int md_alg_id;
516     const ASN1_OCTET_STRING *digest;
517     EVP_MD *md = NULL;
518     int i;
519 
520     /* Checking request version. */
521     if (TS_REQ_get_version(request) != 1) {
522         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
523                                     "Bad request version.");
524         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_REQUEST);
525         return 0;
526     }
527 
528     /* Checking message digest algorithm. */
529     msg_imprint = TS_REQ_get_msg_imprint(request);
530     md_alg = TS_MSG_IMPRINT_get_algo(msg_imprint);
531     md_alg_id = OBJ_obj2nid(md_alg->algorithm);
532     for (i = 0; !md && i < sk_EVP_MD_num(ctx->mds); ++i) {
533         EVP_MD *current_md = sk_EVP_MD_value(ctx->mds, i);
534         if (md_alg_id == EVP_MD_type(current_md))
535             md = current_md;
536     }
537     if (!md) {
538         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
539                                     "Message digest algorithm is "
540                                     "not supported.");
541         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_ALG);
542         return 0;
543     }
544 
545     /* No message digest takes parameter. */
546     if (md_alg->parameter && ASN1_TYPE_get(md_alg->parameter) != V_ASN1_NULL) {
547         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
548                                     "Superfluous message digest "
549                                     "parameter.");
550         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_ALG);
551         return 0;
552     }
553     /* Checking message digest size. */
554     digest = TS_MSG_IMPRINT_get_msg(msg_imprint);
555     if (digest->length != EVP_MD_size(md)) {
556         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
557                                     "Bad message digest.");
558         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_DATA_FORMAT);
559         return 0;
560     }
561 
562     return 1;
563 }
564 
565 /* Returns the TSA policy based on the requested and acceptable policies. */
566 static ASN1_OBJECT *TS_RESP_get_policy(TS_RESP_CTX *ctx)
567 {
568     ASN1_OBJECT *requested = TS_REQ_get_policy_id(ctx->request);
569     ASN1_OBJECT *policy = NULL;
570     int i;
571 
572     if (ctx->default_policy == NULL) {
573         TSerr(TS_F_TS_RESP_GET_POLICY, TS_R_INVALID_NULL_POINTER);
574         return NULL;
575     }
576     /*
577      * Return the default policy if none is requested or the default is
578      * requested.
579      */
580     if (!requested || !OBJ_cmp(requested, ctx->default_policy))
581         policy = ctx->default_policy;
582 
583     /* Check if the policy is acceptable. */
584     for (i = 0; !policy && i < sk_ASN1_OBJECT_num(ctx->policies); ++i) {
585         ASN1_OBJECT *current = sk_ASN1_OBJECT_value(ctx->policies, i);
586         if (!OBJ_cmp(requested, current))
587             policy = current;
588     }
589     if (!policy) {
590         TSerr(TS_F_TS_RESP_GET_POLICY, TS_R_UNACCEPTABLE_POLICY);
591         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
592                                     "Requested policy is not " "supported.");
593         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_UNACCEPTED_POLICY);
594     }
595     return policy;
596 }
597 
598 /* Creates the TS_TST_INFO object based on the settings of the context. */
599 static TS_TST_INFO *TS_RESP_create_tst_info(TS_RESP_CTX *ctx,
600                                             ASN1_OBJECT *policy)
601 {
602     int result = 0;
603     TS_TST_INFO *tst_info = NULL;
604     ASN1_INTEGER *serial = NULL;
605     ASN1_GENERALIZEDTIME *asn1_time = NULL;
606     long sec, usec;
607     TS_ACCURACY *accuracy = NULL;
608     const ASN1_INTEGER *nonce;
609     GENERAL_NAME *tsa_name = NULL;
610 
611     if (!(tst_info = TS_TST_INFO_new()))
612         goto end;
613     if (!TS_TST_INFO_set_version(tst_info, 1))
614         goto end;
615     if (!TS_TST_INFO_set_policy_id(tst_info, policy))
616         goto end;
617     if (!TS_TST_INFO_set_msg_imprint(tst_info, ctx->request->msg_imprint))
618         goto end;
619     if (!(serial = (*ctx->serial_cb) (ctx, ctx->serial_cb_data))
620         || !TS_TST_INFO_set_serial(tst_info, serial))
621         goto end;
622     if (!(*ctx->time_cb) (ctx, ctx->time_cb_data, &sec, &usec)
623         || !(asn1_time = TS_RESP_set_genTime_with_precision(NULL,
624                                                             sec, usec,
625                                                             ctx->clock_precision_digits))
626         || !TS_TST_INFO_set_time(tst_info, asn1_time))
627         goto end;
628 
629     /* Setting accuracy if needed. */
630     if ((ctx->seconds || ctx->millis || ctx->micros)
631         && !(accuracy = TS_ACCURACY_new()))
632         goto end;
633 
634     if (ctx->seconds && !TS_ACCURACY_set_seconds(accuracy, ctx->seconds))
635         goto end;
636     if (ctx->millis && !TS_ACCURACY_set_millis(accuracy, ctx->millis))
637         goto end;
638     if (ctx->micros && !TS_ACCURACY_set_micros(accuracy, ctx->micros))
639         goto end;
640     if (accuracy && !TS_TST_INFO_set_accuracy(tst_info, accuracy))
641         goto end;
642 
643     /* Setting ordering. */
644     if ((ctx->flags & TS_ORDERING)
645         && !TS_TST_INFO_set_ordering(tst_info, 1))
646         goto end;
647 
648     /* Setting nonce if needed. */
649     if ((nonce = TS_REQ_get_nonce(ctx->request)) != NULL
650         && !TS_TST_INFO_set_nonce(tst_info, nonce))
651         goto end;
652 
653     /* Setting TSA name to subject of signer certificate. */
654     if (ctx->flags & TS_TSA_NAME) {
655         if (!(tsa_name = GENERAL_NAME_new()))
656             goto end;
657         tsa_name->type = GEN_DIRNAME;
658         tsa_name->d.dirn =
659             X509_NAME_dup(ctx->signer_cert->cert_info->subject);
660         if (!tsa_name->d.dirn)
661             goto end;
662         if (!TS_TST_INFO_set_tsa(tst_info, tsa_name))
663             goto end;
664     }
665 
666     result = 1;
667  end:
668     if (!result) {
669         TS_TST_INFO_free(tst_info);
670         tst_info = NULL;
671         TSerr(TS_F_TS_RESP_CREATE_TST_INFO, TS_R_TST_INFO_SETUP_ERROR);
672         TS_RESP_CTX_set_status_info_cond(ctx, TS_STATUS_REJECTION,
673                                          "Error during TSTInfo "
674                                          "generation.");
675     }
676     GENERAL_NAME_free(tsa_name);
677     TS_ACCURACY_free(accuracy);
678     ASN1_GENERALIZEDTIME_free(asn1_time);
679     ASN1_INTEGER_free(serial);
680 
681     return tst_info;
682 }
683 
684 /* Processing the extensions of the request. */
685 static int 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         /*
694          * XXXXX The last argument was previously (void *)ctx->extension_cb,
695          * but ISO C doesn't permit converting a function pointer to void *.
696          * For lack of better information, I'm placing a NULL there instead.
697          * The callback can pick its own address out from the ctx anyway...
698          */
699         ok = (*ctx->extension_cb) (ctx, ext, NULL);
700     }
701 
702     return ok;
703 }
704 
705 /* Functions for signing the TS_TST_INFO structure of the context. */
706 static int 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, TS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
720         goto err;
721     }
722 
723     /* Create a new PKCS7 signed object. */
724     if (!(p7 = PKCS7_new())) {
725         TSerr(TS_F_TS_RESP_SIGN, ERR_R_MALLOC_FAILURE);
726         goto err;
727     }
728     if (!PKCS7_set_type(p7, NID_pkcs7_signed))
729         goto err;
730 
731     /* Force SignedData version to be 3 instead of the default 1. */
732     if (!ASN1_INTEGER_set(p7->d.sign->version, 3))
733         goto err;
734 
735     /* Add signer certificate and optional certificate chain. */
736     if (TS_REQ_get_cert_req(ctx->request)) {
737         PKCS7_add_certificate(p7, ctx->signer_cert);
738         if (ctx->certs) {
739             for (i = 0; i < sk_X509_num(ctx->certs); ++i) {
740                 X509 *cert = sk_X509_value(ctx->certs, i);
741                 PKCS7_add_certificate(p7, cert);
742             }
743         }
744     }
745 
746     /* Add a new signer info. */
747     if (!(si = PKCS7_add_signature(p7, ctx->signer_cert,
748                                    ctx->signer_key, EVP_sha1()))) {
749         TSerr(TS_F_TS_RESP_SIGN, TS_R_PKCS7_ADD_SIGNATURE_ERROR);
750         goto err;
751     }
752 
753     /* Add content type signed attribute to the signer info. */
754     oid = OBJ_nid2obj(NID_id_smime_ct_TSTInfo);
755     if (!PKCS7_add_signed_attribute(si, NID_pkcs9_contentType,
756                                     V_ASN1_OBJECT, oid)) {
757         TSerr(TS_F_TS_RESP_SIGN, TS_R_PKCS7_ADD_SIGNED_ATTR_ERROR);
758         goto err;
759     }
760 
761     /*
762      * Create the ESS SigningCertificate attribute which contains the signer
763      * certificate id and optionally the certificate chain.
764      */
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         TSerr(TS_F_TS_RESP_SIGN, 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         TSerr(TS_F_TS_RESP_SIGN, 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         TSerr(TS_F_TS_RESP_SIGN, 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         TSerr(TS_F_TS_RESP_SIGN, 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  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 *ESS_SIGNING_CERT_new_init(X509 *signcert,
815                                                    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  err:
841     ESS_SIGNING_CERT_free(sc);
842     TSerr(TS_F_ESS_SIGNING_CERT_NEW_INIT, ERR_R_MALLOC_FAILURE);
843     return NULL;
844 }
845 
846 static ESS_CERT_ID *ESS_CERT_ID_new_init(X509 *cert, int issuer_needed)
847 {
848     ESS_CERT_ID *cid = NULL;
849     GENERAL_NAME *name = NULL;
850 
851     /* Recompute SHA1 hash of certificate if necessary (side effect). */
852     X509_check_purpose(cert, -1, 0);
853 
854     if (!(cid = ESS_CERT_ID_new()))
855         goto err;
856     if (!ASN1_OCTET_STRING_set(cid->hash, cert->sha1_hash,
857                                sizeof(cert->sha1_hash)))
858         goto err;
859 
860     /* Setting the issuer/serial if requested. */
861     if (issuer_needed) {
862         /* Creating issuer/serial structure. */
863         if (!cid->issuer_serial
864             && !(cid->issuer_serial = ESS_ISSUER_SERIAL_new()))
865             goto err;
866         /* Creating general name from the certificate issuer. */
867         if (!(name = GENERAL_NAME_new()))
868             goto err;
869         name->type = GEN_DIRNAME;
870         if (!(name->d.dirn = X509_NAME_dup(cert->cert_info->issuer)))
871             goto err;
872         if (!sk_GENERAL_NAME_push(cid->issuer_serial->issuer, name))
873             goto err;
874         name = NULL;            /* Ownership is lost. */
875         /* Setting the serial number. */
876         ASN1_INTEGER_free(cid->issuer_serial->serial);
877         if (!(cid->issuer_serial->serial =
878               ASN1_INTEGER_dup(cert->cert_info->serialNumber)))
879             goto err;
880     }
881 
882     return cid;
883  err:
884     GENERAL_NAME_free(name);
885     ESS_CERT_ID_free(cid);
886     TSerr(TS_F_ESS_CERT_ID_NEW_INIT, ERR_R_MALLOC_FAILURE);
887     return NULL;
888 }
889 
890 static int TS_TST_INFO_content_new(PKCS7 *p7)
891 {
892     PKCS7 *ret = NULL;
893     ASN1_OCTET_STRING *octet_string = NULL;
894 
895     /* Create new encapsulated NID_id_smime_ct_TSTInfo content. */
896     if (!(ret = PKCS7_new()))
897         goto err;
898     if (!(ret->d.other = ASN1_TYPE_new()))
899         goto err;
900     ret->type = OBJ_nid2obj(NID_id_smime_ct_TSTInfo);
901     if (!(octet_string = ASN1_OCTET_STRING_new()))
902         goto err;
903     ASN1_TYPE_set(ret->d.other, V_ASN1_OCTET_STRING, octet_string);
904     octet_string = NULL;
905 
906     /* Add encapsulated content to signed PKCS7 structure. */
907     if (!PKCS7_set_content(p7, ret))
908         goto err;
909 
910     return 1;
911  err:
912     ASN1_OCTET_STRING_free(octet_string);
913     PKCS7_free(ret);
914     return 0;
915 }
916 
917 static int ESS_add_signing_cert(PKCS7_SIGNER_INFO *si, ESS_SIGNING_CERT *sc)
918 {
919     ASN1_STRING *seq = NULL;
920     unsigned char *p, *pp = NULL;
921     int len;
922 
923     len = i2d_ESS_SIGNING_CERT(sc, NULL);
924     if (!(pp = (unsigned char *)OPENSSL_malloc(len))) {
925         TSerr(TS_F_ESS_ADD_SIGNING_CERT, ERR_R_MALLOC_FAILURE);
926         goto err;
927     }
928     p = pp;
929     i2d_ESS_SIGNING_CERT(sc, &p);
930     if (!(seq = ASN1_STRING_new()) || !ASN1_STRING_set(seq, pp, len)) {
931         TSerr(TS_F_ESS_ADD_SIGNING_CERT, ERR_R_MALLOC_FAILURE);
932         goto err;
933     }
934     OPENSSL_free(pp);
935     pp = NULL;
936     return PKCS7_add_signed_attribute(si,
937                                       NID_id_smime_aa_signingCertificate,
938                                       V_ASN1_SEQUENCE, seq);
939  err:
940     ASN1_STRING_free(seq);
941     OPENSSL_free(pp);
942 
943     return 0;
944 }
945 
946 static ASN1_GENERALIZEDTIME
947 *TS_RESP_set_genTime_with_precision(ASN1_GENERALIZEDTIME *asn1_time,
948                                     long sec, long usec, unsigned precision)
949 {
950     time_t time_sec = (time_t)sec;
951     struct tm *tm = NULL;
952     struct tm result = {0};
953     char genTime_str[17 + TS_MAX_CLOCK_PRECISION_DIGITS];
954     char *p = genTime_str;
955     char *p_end = genTime_str + sizeof(genTime_str);
956 
957     if (precision > TS_MAX_CLOCK_PRECISION_DIGITS)
958         goto err;
959 
960     if (!(tm = OPENSSL_gmtime(&time_sec, &result)))
961         goto err;
962 
963     /*
964      * Put "genTime_str" in GeneralizedTime format.  We work around the
965      * restrictions imposed by rfc3280 (i.e. "GeneralizedTime values MUST
966      * NOT include fractional seconds") and OpenSSL related functions to
967      * meet the rfc3161 requirement: "GeneralizedTime syntax can include
968      * fraction-of-second details".
969      */
970     p += BIO_snprintf(p, p_end - p,
971                       "%04d%02d%02d%02d%02d%02d",
972                       tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
973                       tm->tm_hour, tm->tm_min, tm->tm_sec);
974     if (precision > 0) {
975         /* Add fraction of seconds (leave space for dot and null). */
976         BIO_snprintf(p, 2 + precision, ".%06ld", usec);
977         /*
978          * We cannot use the snprintf return value, because it might have
979          * been truncated.
980          */
981         p += strlen(p);
982 
983         /*
984          * To make things a bit harder, X.690 | ISO/IEC 8825-1 provides the
985          * following restrictions for a DER-encoding, which OpenSSL
986          * (specifically ASN1_GENERALIZEDTIME_check() function) doesn't
987          * support: "The encoding MUST terminate with a "Z" (which means
988          * "Zulu" time). The decimal point element, if present, MUST be the
989          * point option ".". The fractional-seconds elements, if present,
990          * MUST omit all trailing 0's; if the elements correspond to 0, they
991          * MUST be wholly omitted, and the decimal point element also MUST be
992          * omitted."
993          */
994         /*
995          * Remove trailing zeros. The dot guarantees the exit condition of
996          * this loop even if all the digits are zero.
997          */
998         while (*--p == '0')
999             /*
1000              * empty
1001              */ ;
1002         /* p points to either the dot or the last non-zero digit. */
1003         if (*p != '.')
1004             ++p;
1005     }
1006     /* Add the trailing Z and the terminating null. */
1007     *p++ = 'Z';
1008     *p++ = '\0';
1009 
1010     /* Now call OpenSSL to check and set our genTime value */
1011     if (!asn1_time && !(asn1_time = M_ASN1_GENERALIZEDTIME_new()))
1012         goto err;
1013     if (!ASN1_GENERALIZEDTIME_set_string(asn1_time, genTime_str)) {
1014         ASN1_GENERALIZEDTIME_free(asn1_time);
1015         goto err;
1016     }
1017 
1018     return asn1_time;
1019  err:
1020     TSerr(TS_F_TS_RESP_SET_GENTIME_WITH_PRECISION, TS_R_COULD_NOT_SET_TIME);
1021     return NULL;
1022 }
1023