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