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