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