shorter filenames
[openssl.git] / crypto / ts / ts_rsp_sign.c
1 /* crypto/ts/ts_resp_sign.c */
2 /* Written by Zoltan Glozik (zglozik@stones.com) for the OpenSSL
3  * project 2002.
4  */
5 /* ====================================================================
6  * Copyright (c) 2006 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer. 
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58
59 #include "cryptlib.h"
60
61 #if defined(OPENSSL_SYS_UNIX)
62 #include <sys/time.h>
63 #endif
64
65 #include <openssl/objects.h>
66 #include <openssl/ts.h>
67 #include <openssl/pkcs7.h>
68
69 /* Private function declarations. */
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 *TS_RESP_set_genTime_with_precision(
91         ASN1_GENERALIZEDTIME *, long, long, unsigned);
92
93 /* Default callbacks for response generation. */
94
95 static ASN1_INTEGER *def_serial_cb(struct TS_resp_ctx *ctx, void *data)
96         {
97         ASN1_INTEGER *serial = ASN1_INTEGER_new();
98         if (!serial) goto err;
99         if (!ASN1_INTEGER_set(serial, 1)) goto err;
100         return serial;
101  err:
102         TSerr(TS_F_DEF_SERIAL_CB, ERR_R_MALLOC_FAILURE);
103         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
104                                     "Error during serial number generation.");
105         return NULL;
106         }
107
108 #if defined(OPENSSL_SYS_UNIX)
109
110 /* Use the gettimeofday function call. */
111 static int def_time_cb(struct TS_resp_ctx *ctx, void *data, 
112                        long *sec, long *usec)
113         {
114         struct timeval tv;
115         if (gettimeofday(&tv, NULL) != 0) 
116                 {
117                 TSerr(TS_F_DEF_TIME_CB, TS_R_TIME_SYSCALL_ERROR);
118                 TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
119                                             "Time is not available.");
120                 TS_RESP_CTX_add_failure_info(ctx, TS_INFO_TIME_NOT_AVAILABLE);
121                 return 0;
122                 }
123         /* Return time to caller. */
124         *sec = tv.tv_sec;
125         *usec = tv.tv_usec;
126
127         return 1;
128         }
129
130 #else
131
132 /* Use the time function call that provides only seconds precision. */
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                 {
139                 TSerr(TS_F_DEF_TIME_CB, TS_R_TIME_SYSCALL_ERROR);
140                 TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
141                                             "Time is not available.");
142                 TS_RESP_CTX_add_failure_info(ctx, TS_INFO_TIME_NOT_AVAILABLE);
143                 return 0;
144                 }
145         /* Return time to caller, only second precision. */
146         *sec = (long) t;
147         *usec = 0;
148
149         return 1;
150         }
151
152 #endif
153
154 static int def_extension_cb(struct TS_resp_ctx *ctx, X509_EXTENSION *ext,
155                             void *data)
156         {
157         /* No extensions are processed here. */
158         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
159                                     "Unsupported extension.");
160         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_UNACCEPTED_EXTENSION);
161         return 0;
162         }
163
164 /* TS_RESP_CTX management functions. */
165
166 TS_RESP_CTX *TS_RESP_CTX_new()
167         {
168         TS_RESP_CTX *ctx;
169
170         if (!(ctx = (TS_RESP_CTX *) OPENSSL_malloc(sizeof(TS_RESP_CTX))))
171                 {
172                 TSerr(TS_F_TS_RESP_CTX_NEW, ERR_R_MALLOC_FAILURE);
173                 return NULL;
174                 }
175         memset(ctx, 0, sizeof(TS_RESP_CTX));
176
177         /* Setting default callbacks. */
178         ctx->serial_cb = def_serial_cb;
179         ctx->time_cb = def_time_cb;
180         ctx->extension_cb = def_extension_cb;
181
182         return ctx;
183         }
184
185 void TS_RESP_CTX_free(TS_RESP_CTX *ctx)
186         {
187         if (!ctx) return;
188
189         X509_free(ctx->signer_cert);
190         EVP_PKEY_free(ctx->signer_key);
191         sk_X509_pop_free(ctx->certs, X509_free);
192         sk_ASN1_OBJECT_pop_free(ctx->policies, ASN1_OBJECT_free);
193         ASN1_OBJECT_free(ctx->default_policy);
194         sk_EVP_MD_free(ctx->mds);       /* No EVP_MD_free method exists. */
195         ASN1_INTEGER_free(ctx->seconds);
196         ASN1_INTEGER_free(ctx->millis);
197         ASN1_INTEGER_free(ctx->micros);
198         OPENSSL_free(ctx);
199         }
200
201 int TS_RESP_CTX_set_signer_cert(TS_RESP_CTX *ctx, X509 *signer)
202         {
203         if (X509_check_purpose(signer, X509_PURPOSE_TIMESTAMP_SIGN, 0) != 1)
204                 {
205                 TSerr(TS_F_TS_RESP_CTX_SET_SIGNER_CERT, 
206                       TS_R_INVALID_SIGNER_CERTIFICATE_PURPOSE);
207                 return 0;
208                 }
209         if (ctx->signer_cert) X509_free(ctx->signer_cert);
210         ctx->signer_cert = signer;
211         CRYPTO_add(&ctx->signer_cert->references, +1, CRYPTO_LOCK_X509);
212         return 1;
213         }
214
215 int TS_RESP_CTX_set_signer_key(TS_RESP_CTX *ctx, EVP_PKEY *key)
216         {
217         if (ctx->signer_key) EVP_PKEY_free(ctx->signer_key);
218         ctx->signer_key = key;
219         CRYPTO_add(&ctx->signer_key->references, +1, CRYPTO_LOCK_EVP_PKEY);
220
221         return 1;
222         }
223
224 int TS_RESP_CTX_set_def_policy(TS_RESP_CTX *ctx, ASN1_OBJECT *def_policy)
225         {
226         if (ctx->default_policy) ASN1_OBJECT_free(ctx->default_policy);
227         if (!(ctx->default_policy = OBJ_dup(def_policy))) goto err;
228         return 1;
229  err:
230         TSerr(TS_F_TS_RESP_CTX_SET_DEF_POLICY, ERR_R_MALLOC_FAILURE);
231         return 0;
232         }
233
234 int TS_RESP_CTX_set_certs(TS_RESP_CTX *ctx, STACK_OF(X509) *certs)
235         {
236         int i;
237
238         if (ctx->certs)
239                 {
240                 sk_X509_pop_free(ctx->certs, X509_free);
241                 ctx->certs = NULL;
242                 }
243         if (!certs) return 1;
244         if (!(ctx->certs = sk_X509_dup(certs))) 
245                 {
246                 TSerr(TS_F_TS_RESP_CTX_SET_CERTS, ERR_R_MALLOC_FAILURE);
247                 return 0;
248                 }
249         for (i = 0; i < sk_X509_num(ctx->certs); ++i)
250                 {
251                 X509 *cert = sk_X509_value(ctx->certs, i);
252                 CRYPTO_add(&cert->references, +1, CRYPTO_LOCK_X509);
253                 }
254
255         return 1;
256         }
257
258 int TS_RESP_CTX_add_policy(TS_RESP_CTX *ctx, ASN1_OBJECT *policy)
259         {
260         ASN1_OBJECT *copy = NULL;
261
262         /* Create new policy stack if necessary. */
263         if (!ctx->policies && !(ctx->policies = sk_ASN1_OBJECT_new_null())) 
264                 goto err;
265         if (!(copy = OBJ_dup(policy))) goto err;
266         if (!sk_ASN1_OBJECT_push(ctx->policies, copy)) 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, md)) 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())) goto err;
351         if (!ASN1_INTEGER_set(si->status, status)) goto err;
352         if (text)
353                 {
354                 if (!(utf8_text = ASN1_UTF8STRING_new())
355                     || !ASN1_STRING_set(utf8_text, text, strlen(text)))
356                         goto err;
357                 if (!si->text && !(si->text = sk_ASN1_UTF8STRING_new_null()))
358                         goto err;
359                 if (!sk_ASN1_UTF8STRING_push(si->text, utf8_text)) goto err;
360                 utf8_text = NULL;       /* Ownership is lost. */
361                 }
362         if (!TS_RESP_set_status_info(ctx->response, si)) goto err;
363         ret = 1;
364  err:
365         if (!ret)
366                 TSerr(TS_F_TS_RESP_CTX_SET_STATUS_INFO, ERR_R_MALLOC_FAILURE);
367         TS_STATUS_INFO_free(si);
368         ASN1_UTF8STRING_free(utf8_text);
369         return ret;
370         }
371
372 int TS_RESP_CTX_set_status_info_cond(TS_RESP_CTX *ctx, 
373                                      int status, const char *text)
374         {
375         int ret = 1;
376         TS_STATUS_INFO *si = TS_RESP_get_status_info(ctx->response);
377
378         if (ASN1_INTEGER_get(si->status) == TS_STATUS_GRANTED)
379                 {
380                 /* Status has not been set, set it now. */
381                 ret = TS_RESP_CTX_set_status_info(ctx, status, text);
382                 }
383         return ret;
384         }
385
386 int TS_RESP_CTX_add_failure_info(TS_RESP_CTX *ctx, int failure)
387         {
388         TS_STATUS_INFO *si = TS_RESP_get_status_info(ctx->response);
389         if (!si->failure_info && !(si->failure_info = ASN1_BIT_STRING_new()))
390                 goto err;
391         if (!ASN1_BIT_STRING_set_bit(si->failure_info, failure, 1))
392                 goto err;
393         return 1;
394  err:
395         TSerr(TS_F_TS_RESP_CTX_ADD_FAILURE_INFO, ERR_R_MALLOC_FAILURE);
396         return 0;
397         }
398
399 TS_REQ *TS_RESP_CTX_get_request(TS_RESP_CTX *ctx)
400         {
401         return ctx->request;
402         }
403
404 TS_TST_INFO *TS_RESP_CTX_get_tst_info(TS_RESP_CTX *ctx)
405         {
406         return ctx->tst_info;
407         }
408
409 int TS_RESP_CTX_set_clock_precision_digits(TS_RESP_CTX *ctx, unsigned precision)
410        {
411        if (precision > TS_MAX_CLOCK_PRECISION_DIGITS)
412                return 0;
413        ctx->clock_precision_digits = precision;
414        return 1;
415        }
416
417 /* Main entry method of the response generation. */
418 TS_RESP *TS_RESP_create_response(TS_RESP_CTX *ctx, BIO *req_bio)
419         {
420         ASN1_OBJECT *policy;
421         TS_RESP *response;
422         int result = 0;
423
424         TS_RESP_CTX_init(ctx);
425
426         /* Creating the response object. */
427         if (!(ctx->response = TS_RESP_new())) 
428                 {
429                 TSerr(TS_F_TS_RESP_CREATE_RESPONSE, ERR_R_MALLOC_FAILURE);
430                 goto end;
431                 }
432
433         /* Parsing DER request. */
434         if (!(ctx->request = d2i_TS_REQ_bio(req_bio, NULL)))
435                 {
436                 TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
437                                             "Bad request format or "
438                                             "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)) goto end;
449
450         /* Checking acceptable policies. */
451         if (!(policy = TS_RESP_get_policy(ctx))) goto end;
452
453         /* Creating the TS_TST_INFO object. */
454         if (!(ctx->tst_info = TS_RESP_create_tst_info(ctx, policy)))
455                 goto end;
456
457         /* Processing extensions. */
458         if (!TS_RESP_process_extensions(ctx)) goto end;
459
460         /* Generating the signature. */
461         if (!TS_RESP_sign(ctx)) goto end;
462
463         /* Everything was successful. */
464         result = 1;
465  end:
466         if (!result)
467                 {
468                 TSerr(TS_F_TS_RESP_CREATE_RESPONSE, TS_R_RESPONSE_SETUP_ERROR);
469                 TS_RESP_CTX_set_status_info_cond(ctx, TS_STATUS_REJECTION,
470                                                  "Error during response "
471                                                  "generation.");
472                 /* Check if the status info was set. */
473                 if (ctx->response
474                     && ASN1_INTEGER_get(
475                             TS_RESP_get_status_info(ctx->response)->status)
476                     == TS_STATUS_GRANTED)
477                         {
478                         /* Status info wasn't set, don't return a response. */
479                         TS_RESP_free(ctx->response);
480                         ctx->response = NULL;
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         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                 {
522                 TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
523                                             "Bad request version.");
524                 TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_REQUEST);
525                 return 0;
526                 }
527
528         /* Checking message digest algorithm. */
529         msg_imprint = TS_REQ_get_msg_imprint(request);
530         md_alg = TS_MSG_IMPRINT_get_algo(msg_imprint);
531         md_alg_id = OBJ_obj2nid(md_alg->algorithm);
532         for (i = 0; !md && i < sk_EVP_MD_num(ctx->mds); ++i)
533                 {
534                 EVP_MD *current_md = sk_EVP_MD_value(ctx->mds, i);
535                 if (md_alg_id == EVP_MD_type(current_md))
536                         md = current_md;
537                 }
538         if (!md)
539                 {
540                 TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
541                                             "Message digest algorithm is "
542                                             "not supported.");
543                 TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_ALG);
544                 return 0;
545                 }
546
547         /* No message digest takes parameter. */
548         if (md_alg->parameter 
549             && ASN1_TYPE_get(md_alg->parameter) != V_ASN1_NULL)
550                 {
551                 TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
552                                             "Superfluous message digest "
553                                             "parameter.");
554                 TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_ALG);
555                 return 0;
556                 }
557         /* Checking message digest size. */
558         digest = TS_MSG_IMPRINT_get_msg(msg_imprint);
559         if (digest->length != EVP_MD_size(md))
560                 {
561                 TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
562                                             "Bad message digest.");
563                 TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_DATA_FORMAT);
564                 return 0;
565                 }
566
567         return 1;
568         }
569
570 /* Returns the TSA policy based on the rqeuested and acceptable policies. */
571 static ASN1_OBJECT *TS_RESP_get_policy(TS_RESP_CTX *ctx)
572         {
573         ASN1_OBJECT *requested = TS_REQ_get_policy_id(ctx->request);
574         ASN1_OBJECT *policy = NULL;
575         int i;
576
577         /* Return the default policy if none is requested or the default is
578            requested. */
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                 {
585                 ASN1_OBJECT *current = sk_ASN1_OBJECT_value(ctx->policies, i);
586                 if (!OBJ_cmp(requested, current))
587                         policy = current;
588                 }
589         if (!policy)
590                 {
591                 TSerr(TS_F_TS_RESP_GET_POLICY, TS_R_UNACCEPTABLE_POLICY);
592                 TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
593                                             "Requested policy is not "
594                                             "supported.");
595                 TS_RESP_CTX_add_failure_info(ctx, TS_INFO_UNACCEPTED_POLICY);
596                 }
597         return policy;
598         }
599
600 /* Creates the TS_TST_INFO object based on the settings of the context. */
601 static TS_TST_INFO *TS_RESP_create_tst_info(TS_RESP_CTX *ctx,
602                                             ASN1_OBJECT *policy)
603         {
604         int result = 0;
605         TS_TST_INFO *tst_info = NULL;
606         ASN1_INTEGER *serial = NULL;
607         ASN1_GENERALIZEDTIME *asn1_time = NULL;
608         long sec, usec;
609         TS_ACCURACY *accuracy = NULL;
610         ASN1_INTEGER *nonce;
611         GENERAL_NAME *tsa_name = NULL;
612
613         if (!(tst_info = TS_TST_INFO_new())) goto end;
614         if (!TS_TST_INFO_set_version(tst_info, 1)) goto end;
615         if (!TS_TST_INFO_set_policy_id(tst_info, policy)) 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                 {
655                 if (!(tsa_name = GENERAL_NAME_new())) 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) goto end;
660                 if (!TS_TST_INFO_set_tsa(tst_info, tsa_name)) goto end;
661                 }
662
663         result = 1;
664  end:
665         if (!result)
666                 {
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                 {
691                 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
692                 ok = (*ctx->extension_cb)(ctx, ext, (void *)ctx->extension_cb);
693                 }
694
695         return ok;
696         }
697
698 /* Functions for signing the TS_TST_INFO structure of the context. */
699 static int TS_RESP_sign(TS_RESP_CTX *ctx)
700         {
701         int ret = 0;
702         PKCS7 *p7 = NULL;
703         PKCS7_SIGNER_INFO *si;
704         STACK_OF(X509) *certs;  /* Certificates to include in sc. */
705         ESS_SIGNING_CERT *sc = NULL;
706         ASN1_OBJECT *oid;
707         BIO *p7bio = NULL;
708         int i;
709
710         /* Check if signcert and pkey match. */
711         if (!X509_check_private_key(ctx->signer_cert, ctx->signer_key)) {
712                 TSerr(TS_F_TS_RESP_SIGN, 
713                       TS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
714                 goto err;
715         }
716
717         /* Create a new PKCS7 signed object. */
718         if (!(p7 = PKCS7_new())) {
719                 TSerr(TS_F_TS_RESP_SIGN, ERR_R_MALLOC_FAILURE);
720                 goto err;
721         }
722         if (!PKCS7_set_type(p7, NID_pkcs7_signed)) goto err;
723
724         /* Force SignedData version to be 3 instead of the default 1. */
725         if (!ASN1_INTEGER_set(p7->d.sign->version, 3)) goto err;
726
727         /* Add signer certificate and optional certificate chain. */
728         if (TS_REQ_get_cert_req(ctx->request))
729                 {
730                 PKCS7_add_certificate(p7, ctx->signer_cert);
731                 if (ctx->certs)
732                         {
733                         for(i = 0; i < sk_X509_num(ctx->certs); ++i) 
734                                 {
735                                 X509 *cert = sk_X509_value(ctx->certs, i);
736                                 PKCS7_add_certificate(p7, cert);
737                                 }
738                         }
739                 }
740
741         /* Add a new signer info. */
742         if (!(si = PKCS7_add_signature(p7, ctx->signer_cert, 
743                                        ctx->signer_key, EVP_sha1())))
744                 {
745                 TSerr(TS_F_TS_RESP_SIGN, TS_R_PKCS7_ADD_SIGNATURE_ERROR);
746                 goto err;
747                 }
748
749         /* Add content type signed attribute to the signer info. */
750         oid = OBJ_nid2obj(NID_id_smime_ct_TSTInfo);
751         if (!PKCS7_add_signed_attribute(si, NID_pkcs9_contentType,
752                                         V_ASN1_OBJECT, oid))
753                 {
754                 TSerr(TS_F_TS_RESP_SIGN, TS_R_PKCS7_ADD_SIGNED_ATTR_ERROR);
755                 goto err;
756                 }
757
758         /* Create the ESS SigningCertificate attribute which contains 
759            the signer certificate id and optionally the certificate chain. */
760         certs = ctx->flags & TS_ESS_CERT_ID_CHAIN ? ctx->certs : NULL;
761         if (!(sc = ESS_SIGNING_CERT_new_init(ctx->signer_cert, certs)))
762                 goto err;
763
764         /* Add SigningCertificate signed attribute to the signer info. */
765         if (!ESS_add_signing_cert(si, sc))
766                 {
767                 TSerr(TS_F_TS_RESP_SIGN, TS_R_ESS_ADD_SIGNING_CERT_ERROR);
768                 goto err;
769                 }       
770
771         /* Add a new empty NID_id_smime_ct_TSTInfo encapsulated content. */
772         if (!TS_TST_INFO_content_new(p7)) goto err;
773
774         /* Add the DER encoded tst_info to the PKCS7 structure. */
775         if (!(p7bio = PKCS7_dataInit(p7, NULL))) {
776                 TSerr(TS_F_TS_RESP_SIGN, ERR_R_MALLOC_FAILURE);
777                 goto err;
778         }
779
780         /* Convert tst_info to DER. */
781         if (!i2d_TS_TST_INFO_bio(p7bio, ctx->tst_info))
782                 {
783                 TSerr(TS_F_TS_RESP_SIGN, TS_R_TS_DATASIGN);
784                 goto err;
785                 }
786
787         /* Create the signature and add it to the signer info. */
788         if (!PKCS7_dataFinal(p7, p7bio))
789                 {
790                 TSerr(TS_F_TS_RESP_SIGN, TS_R_TS_DATASIGN);
791                 goto err;
792                 }
793
794         /* Set new PKCS7 and TST_INFO objects. */
795         TS_RESP_set_tst_info(ctx->response, p7, ctx->tst_info);
796         p7 = NULL;              /* Ownership is lost. */
797         ctx->tst_info = NULL;   /* Ownership is lost. */
798
799         ret = 1;
800  err:
801         if (!ret)
802                 TS_RESP_CTX_set_status_info_cond(ctx, TS_STATUS_REJECTION,
803                                                  "Error during signature "
804                                                  "generation.");
805         BIO_free_all(p7bio);
806         ESS_SIGNING_CERT_free(sc);
807         PKCS7_free(p7);
808         return ret;
809         }
810
811 static ESS_SIGNING_CERT *ESS_SIGNING_CERT_new_init(X509 *signcert, 
812                                                    STACK_OF(X509) *certs)
813         {
814         ESS_CERT_ID *cid;
815         ESS_SIGNING_CERT *sc = NULL;
816         int i;
817
818         /* Creating the ESS_CERT_ID stack. */
819         if (!(sc = ESS_SIGNING_CERT_new())) goto err;
820         if (!sc->cert_ids && !(sc->cert_ids = sk_ESS_CERT_ID_new_null()))
821                 goto err;
822
823         /* Adding the signing certificate id. */
824         if (!(cid = ESS_CERT_ID_new_init(signcert, 0))
825             || !sk_ESS_CERT_ID_push(sc->cert_ids, cid))
826                 goto err;
827         /* Adding the certificate chain ids. */
828         for (i = 0; i < sk_X509_num(certs); ++i)
829                 {
830                 X509 *cert = sk_X509_value(certs, i);
831                 if (!(cid = ESS_CERT_ID_new_init(cert, 1))
832                     || !sk_ESS_CERT_ID_push(sc->cert_ids, cid))
833                         goto err;
834                 }
835
836         return sc;
837 err:
838         ESS_SIGNING_CERT_free(sc);
839         TSerr(TS_F_ESS_SIGNING_CERT_NEW_INIT, ERR_R_MALLOC_FAILURE);
840         return NULL;
841         }
842
843 static ESS_CERT_ID *ESS_CERT_ID_new_init(X509 *cert, int issuer_needed)
844         {
845         ESS_CERT_ID *cid = NULL;
846         GENERAL_NAME *name = NULL;
847         
848         /* Recompute SHA1 hash of certificate if necessary (side effect). */
849         X509_check_purpose(cert, -1, 0);
850
851         if (!(cid = ESS_CERT_ID_new())) goto err;
852         if (!ASN1_OCTET_STRING_set(cid->hash, cert->sha1_hash,
853                                    sizeof(cert->sha1_hash)))
854                 goto err;
855
856         /* Setting the issuer/serial if requested. */
857         if (issuer_needed)
858                 {
859                 /* Creating issuer/serial structure. */
860                 if (!cid->issuer_serial
861                     && !(cid->issuer_serial = ESS_ISSUER_SERIAL_new()))
862                         goto err;
863                 /* Creating general name from the certificate issuer. */
864                 if (!(name = GENERAL_NAME_new())) goto err;
865                 name->type = GEN_DIRNAME;
866                 if (!(name->d.dirn = X509_NAME_dup(cert->cert_info->issuer))) 
867                         goto err;
868                 if (!sk_GENERAL_NAME_push(cid->issuer_serial->issuer, name)) 
869                         goto err;
870                 name = NULL;    /* Ownership is lost. */
871                 /* Setting the serial number. */
872                 ASN1_INTEGER_free(cid->issuer_serial->serial);
873                 if (!(cid->issuer_serial->serial = 
874                       ASN1_INTEGER_dup(cert->cert_info->serialNumber)))
875                         goto err;
876                 }
877
878         return cid;
879 err:
880         GENERAL_NAME_free(name);
881         ESS_CERT_ID_free(cid);
882         TSerr(TS_F_ESS_CERT_ID_NEW_INIT, ERR_R_MALLOC_FAILURE);
883         return NULL;
884         }
885
886 static int TS_TST_INFO_content_new(PKCS7 *p7)
887         {
888         PKCS7 *ret = NULL;
889         ASN1_OCTET_STRING *octet_string = NULL;
890
891         /* Create new encapsulated NID_id_smime_ct_TSTInfo content. */
892         if (!(ret = PKCS7_new())) goto err;
893         if (!(ret->d.other = ASN1_TYPE_new())) goto err;
894         ret->type = OBJ_nid2obj(NID_id_smime_ct_TSTInfo);
895         if (!(octet_string = ASN1_OCTET_STRING_new())) goto err;
896         ASN1_TYPE_set(ret->d.other, V_ASN1_OCTET_STRING, octet_string);
897         octet_string = NULL;
898
899         /* Add encapsulated content to signed PKCS7 structure. */
900         if (!PKCS7_set_content(p7, ret)) goto err;
901
902         return 1;
903  err:
904         ASN1_OCTET_STRING_free(octet_string);
905         PKCS7_free(ret);
906         return 0;
907         }
908
909 static int ESS_add_signing_cert(PKCS7_SIGNER_INFO *si, ESS_SIGNING_CERT *sc)
910         {
911         ASN1_STRING *seq = NULL;
912         unsigned char *p, *pp = NULL;
913         int len;
914
915         len = i2d_ESS_SIGNING_CERT(sc, NULL);
916         if (!(pp = (unsigned char *) OPENSSL_malloc(len)))
917                 {
918                 TSerr(TS_F_ESS_ADD_SIGNING_CERT, ERR_R_MALLOC_FAILURE);
919                 goto err;
920                 }
921         p = pp;
922         i2d_ESS_SIGNING_CERT(sc, &p);
923         if (!(seq = ASN1_STRING_new()) || !ASN1_STRING_set(seq, pp, len))
924                 {
925                 TSerr(TS_F_ESS_ADD_SIGNING_CERT, ERR_R_MALLOC_FAILURE);
926                 goto err;
927                 }
928         OPENSSL_free(pp); pp = NULL;
929         return PKCS7_add_signed_attribute(si, 
930                                           NID_id_smime_aa_signingCertificate,
931                                           V_ASN1_SEQUENCE, seq);
932  err:
933         ASN1_STRING_free(seq);
934         OPENSSL_free(pp);
935
936         return 0;
937         }
938
939
940 static ASN1_GENERALIZEDTIME *
941 TS_RESP_set_genTime_with_precision(ASN1_GENERALIZEDTIME *asn1_time, 
942                                    long sec, long usec, unsigned precision)
943         {
944         time_t time_sec = (time_t) sec;
945         struct tm *tm = NULL;   
946         char genTime_str[17 + TS_MAX_CLOCK_PRECISION_DIGITS];
947         char *p = genTime_str;
948         char *p_end = genTime_str + sizeof(genTime_str);
949
950         if (precision > TS_MAX_CLOCK_PRECISION_DIGITS)
951                 goto err;
952
953         
954         if (!(tm = gmtime(&time_sec)))
955                 goto err;
956
957         /* 
958          * Put "genTime_str" in GeneralizedTime format.  We work around the 
959          * restrictions imposed by rfc3280 (i.e. "GeneralizedTime values MUST 
960          * NOT include fractional seconds") and OpenSSL related functions to 
961          * meet the rfc3161 requirement: "GeneralizedTime syntax can include 
962          * fraction-of-second details". 
963          */                   
964         p += BIO_snprintf(p, p_end - p,
965                           "%04d%02d%02d%02d%02d%02d",
966                           tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, 
967                           tm->tm_hour, tm->tm_min, tm->tm_sec);
968         if (precision > 0)
969         {
970                 /* Add fraction of seconds (leave space for dot and null). */
971                 BIO_snprintf(p, 2 + precision, ".%ld", usec);
972                 /* We cannot use the snprintf return value, 
973                    because it might have been truncated. */
974                 p += strlen(p);
975
976                 /* To make things a bit harder, X.690 | ISO/IEC 8825-1 provides
977                    the following restrictions for a DER-encoding, which OpenSSL
978                    (specifically ASN1_GENERALIZEDTIME_check() function) doesn't 
979                    support:
980                    "The encoding MUST terminate with a "Z" (which means "Zulu" 
981                    time). The decimal point element, if present, MUST be the 
982                    point option ".". The fractional-seconds elements, 
983                    if present, MUST omit all trailing 0's; 
984                    if the elements correspond to 0, they MUST be wholly
985                    omitted, and the decimal point element also MUST be
986                    omitted." */
987                 /* Remove trailing zeros. The dot guarantees the exit
988                    condition of this loop even if all the digits are zero. */
989                 while (*--p == '0')
990                         /* empty */;
991                 /* p points to either the dot or the last non-zero digit. */
992                 if (*p != '.') ++p;
993                 }
994         /* Add the trailing Z and the terminating null. */
995         *p++ = 'Z';
996         *p++ = '\0';
997
998         /* Now call OpenSSL to check and set our genTime value */
999         if (!asn1_time && !(asn1_time = M_ASN1_GENERALIZEDTIME_new()))
1000                 goto err;
1001         if (!ASN1_GENERALIZEDTIME_set_string(asn1_time, genTime_str))
1002                 {
1003                 ASN1_GENERALIZEDTIME_free(asn1_time);
1004                 goto err;
1005                 }
1006
1007         return asn1_time;
1008  err:
1009         TSerr(TS_F_TS_RESP_SET_GENTIME_WITH_PRECISION, TS_R_COULD_NOT_SET_TIME);
1010         return NULL;
1011         }