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