f7fb762d5bf1e7e0a84ae55d15944d5c60d4e1c2
[openssl.git] / crypto / ts / ts_rsp_sign.c
1 /* crypto/ts/ts_resp_sign.c */
2 /*
3  * Written by Zoltan Glozik (zglozik@stones.com) for the OpenSSL project
4  * 2002.
5  */
6 /* ====================================================================
7  * Copyright (c) 2006 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    licensing@OpenSSL.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This product includes cryptographic software written by Eric Young
55  * (eay@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  *
58  */
59
60 #include "internal/cryptlib.h"
61
62 #if defined(OPENSSL_SYS_UNIX)
63 # include <sys/time.h>
64 #endif
65
66 #include <openssl/objects.h>
67 #include <openssl/ts.h>
68 #include <openssl/pkcs7.h>
69 #include "ts_lcl.h"
70
71 /* Private function declarations. */
72
73 static ASN1_INTEGER *def_serial_cb(struct TS_resp_ctx *, void *);
74 static int def_time_cb(struct TS_resp_ctx *, void *, long *sec, long *usec);
75 static int def_extension_cb(struct TS_resp_ctx *, X509_EXTENSION *, void *);
76
77 static void ts_RESP_CTX_init(TS_RESP_CTX *ctx);
78 static void ts_RESP_CTX_cleanup(TS_RESP_CTX *ctx);
79 static int ts_RESP_check_request(TS_RESP_CTX *ctx);
80 static ASN1_OBJECT *ts_RESP_get_policy(TS_RESP_CTX *ctx);
81 static TS_TST_INFO *ts_RESP_create_tst_info(TS_RESP_CTX *ctx,
82                                             ASN1_OBJECT *policy);
83 static int ts_RESP_process_extensions(TS_RESP_CTX *ctx);
84 static int ts_RESP_sign(TS_RESP_CTX *ctx);
85
86 static ESS_SIGNING_CERT *ess_SIGNING_CERT_new_init(X509 *signcert,
87                                                    STACK_OF(X509) *certs);
88 static ESS_CERT_ID *ess_CERT_ID_new_init(X509 *cert, int issuer_needed);
89 static int ts_TST_INFO_content_new(PKCS7 *p7);
90 static int ESS_add_signing_cert(PKCS7_SIGNER_INFO *si, ESS_SIGNING_CERT *sc);
91
92 static ASN1_GENERALIZEDTIME
93 *TS_RESP_set_genTime_with_precision(ASN1_GENERALIZEDTIME *, long, long,
94                                     unsigned);
95
96 /* Default callbacks for response generation. */
97
98 static ASN1_INTEGER *def_serial_cb(struct TS_resp_ctx *ctx, void *data)
99 {
100     ASN1_INTEGER *serial = ASN1_INTEGER_new();
101     if (!serial)
102         goto err;
103     if (!ASN1_INTEGER_set(serial, 1))
104         goto err;
105     return serial;
106  err:
107     TSerr(TS_F_DEF_SERIAL_CB, ERR_R_MALLOC_FAILURE);
108     TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
109                                 "Error during serial number generation.");
110     return NULL;
111 }
112
113 #if defined(OPENSSL_SYS_UNIX)
114
115 /* Use the gettimeofday function call. */
116 static int def_time_cb(struct TS_resp_ctx *ctx, void *data,
117                        long *sec, long *usec)
118 {
119     struct timeval tv;
120     if (gettimeofday(&tv, NULL) != 0) {
121         TSerr(TS_F_DEF_TIME_CB, TS_R_TIME_SYSCALL_ERROR);
122         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
123                                     "Time is not available.");
124         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_TIME_NOT_AVAILABLE);
125         return 0;
126     }
127     /* Return time to caller. */
128     *sec = tv.tv_sec;
129     *usec = tv.tv_usec;
130
131     return 1;
132 }
133
134 #else
135
136 /* Use the time function call that provides only seconds precision. */
137 static int def_time_cb(struct TS_resp_ctx *ctx, void *data,
138                        long *sec, long *usec)
139 {
140     time_t t;
141     if (time(&t) == (time_t)-1) {
142         TSerr(TS_F_DEF_TIME_CB, TS_R_TIME_SYSCALL_ERROR);
143         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
144                                     "Time is not available.");
145         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_TIME_NOT_AVAILABLE);
146         return 0;
147     }
148     /* Return time to caller, only second precision. */
149     *sec = (long)t;
150     *usec = 0;
151
152     return 1;
153 }
154
155 #endif
156
157 static int def_extension_cb(struct TS_resp_ctx *ctx, X509_EXTENSION *ext,
158                             void *data)
159 {
160     /* No extensions are processed here. */
161     TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
162                                 "Unsupported extension.");
163     TS_RESP_CTX_add_failure_info(ctx, TS_INFO_UNACCEPTED_EXTENSION);
164     return 0;
165 }
166
167 /* TS_RESP_CTX management functions. */
168
169 TS_RESP_CTX *TS_RESP_CTX_new()
170 {
171     TS_RESP_CTX *ctx;
172
173     if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL) {
174         TSerr(TS_F_TS_RESP_CTX_NEW, ERR_R_MALLOC_FAILURE);
175         return NULL;
176     }
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     X509_free(ctx->signer_cert);
211     ctx->signer_cert = signer;
212     X509_up_ref(ctx->signer_cert);
213     return 1;
214 }
215
216 int TS_RESP_CTX_set_signer_key(TS_RESP_CTX *ctx, EVP_PKEY *key)
217 {
218     EVP_PKEY_free(ctx->signer_key);
219     ctx->signer_key = key;
220     CRYPTO_add(&ctx->signer_key->references, +1, CRYPTO_LOCK_EVP_PKEY);
221
222     return 1;
223 }
224
225 int TS_RESP_CTX_set_def_policy(TS_RESP_CTX *ctx, ASN1_OBJECT *def_policy)
226 {
227     ASN1_OBJECT_free(ctx->default_policy);
228     if ((ctx->default_policy = OBJ_dup(def_policy)) == NULL)
229         goto err;
230     return 1;
231  err:
232     TSerr(TS_F_TS_RESP_CTX_SET_DEF_POLICY, ERR_R_MALLOC_FAILURE);
233     return 0;
234 }
235
236 int TS_RESP_CTX_set_certs(TS_RESP_CTX *ctx, STACK_OF(X509) *certs)
237 {
238
239     sk_X509_pop_free(ctx->certs, X509_free);
240     ctx->certs = NULL;
241     if (!certs)
242         return 1;
243     if ((ctx->certs = X509_chain_up_ref(certs)) == NULL) {
244         TSerr(TS_F_TS_RESP_CTX_SET_CERTS, ERR_R_MALLOC_FAILURE);
245         return 0;
246     }
247
248     return 1;
249 }
250
251 int TS_RESP_CTX_add_policy(TS_RESP_CTX *ctx, ASN1_OBJECT *policy)
252 {
253     ASN1_OBJECT *copy = NULL;
254
255     /* Create new policy stack if necessary. */
256     if (ctx->policies == NULL
257         && (ctx->policies = sk_ASN1_OBJECT_new_null()) == NULL)
258         goto err;
259     if ((copy = OBJ_dup(policy)) == NULL)
260         goto err;
261     if (!sk_ASN1_OBJECT_push(ctx->policies, copy))
262         goto err;
263
264     return 1;
265  err:
266     TSerr(TS_F_TS_RESP_CTX_ADD_POLICY, ERR_R_MALLOC_FAILURE);
267     ASN1_OBJECT_free(copy);
268     return 0;
269 }
270
271 int TS_RESP_CTX_add_md(TS_RESP_CTX *ctx, const EVP_MD *md)
272 {
273     /* Create new md stack if necessary. */
274     if (ctx->mds == NULL
275         && (ctx->mds = sk_EVP_MD_new_null()) == NULL)
276         goto err;
277     /* Add the shared md, no copy needed. */
278     if (!sk_EVP_MD_push(ctx->mds, (EVP_MD *)md))
279         goto err;
280
281     return 1;
282  err:
283     TSerr(TS_F_TS_RESP_CTX_ADD_MD, ERR_R_MALLOC_FAILURE);
284     return 0;
285 }
286
287 #define TS_RESP_CTX_accuracy_free(ctx)          \
288         ASN1_INTEGER_free(ctx->seconds);        \
289         ctx->seconds = NULL;                    \
290         ASN1_INTEGER_free(ctx->millis);         \
291         ctx->millis = NULL;                     \
292         ASN1_INTEGER_free(ctx->micros);         \
293         ctx->micros = NULL;
294
295 int TS_RESP_CTX_set_accuracy(TS_RESP_CTX *ctx,
296                              int secs, int millis, int micros)
297 {
298
299     TS_RESP_CTX_accuracy_free(ctx);
300     if (secs
301         && ((ctx->seconds = ASN1_INTEGER_new()) == NULL
302             || !ASN1_INTEGER_set(ctx->seconds, secs)))
303         goto err;
304     if (millis
305         && ((ctx->millis = ASN1_INTEGER_new()) == NULL
306             || !ASN1_INTEGER_set(ctx->millis, millis)))
307         goto err;
308     if (micros
309         && ((ctx->micros = ASN1_INTEGER_new()) == NULL
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()) == NULL)
352         goto err;
353     if (!ASN1_INTEGER_set(si->status, status))
354         goto err;
355     if (text) {
356         if ((utf8_text = ASN1_UTF8STRING_new()) == NULL
357             || !ASN1_STRING_set(utf8_text, text, strlen(text)))
358             goto err;
359         if (si->text == NULL
360             && (si->text = sk_ASN1_UTF8STRING_new_null()) == NULL)
361             goto err;
362         if (!sk_ASN1_UTF8STRING_push(si->text, utf8_text))
363             goto err;
364         utf8_text = NULL;       /* Ownership is lost. */
365     }
366     if (!TS_RESP_set_status_info(ctx->response, si))
367         goto err;
368     ret = 1;
369  err:
370     if (!ret)
371         TSerr(TS_F_TS_RESP_CTX_SET_STATUS_INFO, ERR_R_MALLOC_FAILURE);
372     TS_STATUS_INFO_free(si);
373     ASN1_UTF8STRING_free(utf8_text);
374     return ret;
375 }
376
377 int TS_RESP_CTX_set_status_info_cond(TS_RESP_CTX *ctx,
378                                      int status, const char *text)
379 {
380     int ret = 1;
381     TS_STATUS_INFO *si = ctx->response->status_info;
382
383     if (ASN1_INTEGER_get(si->status) == TS_STATUS_GRANTED) {
384         /* Status has not been set, set it now. */
385         ret = TS_RESP_CTX_set_status_info(ctx, status, text);
386     }
387     return ret;
388 }
389
390 int TS_RESP_CTX_add_failure_info(TS_RESP_CTX *ctx, int failure)
391 {
392     TS_STATUS_INFO *si = ctx->response->status_info;
393     if (si->failure_info == NULL
394         && (si->failure_info = ASN1_BIT_STRING_new()) == NULL)
395         goto err;
396     if (!ASN1_BIT_STRING_set_bit(si->failure_info, failure, 1))
397         goto err;
398     return 1;
399  err:
400     TSerr(TS_F_TS_RESP_CTX_ADD_FAILURE_INFO, ERR_R_MALLOC_FAILURE);
401     return 0;
402 }
403
404 TS_REQ *TS_RESP_CTX_get_request(TS_RESP_CTX *ctx)
405 {
406     return ctx->request;
407 }
408
409 TS_TST_INFO *TS_RESP_CTX_get_tst_info(TS_RESP_CTX *ctx)
410 {
411     return ctx->tst_info;
412 }
413
414 int TS_RESP_CTX_set_clock_precision_digits(TS_RESP_CTX *ctx,
415                                            unsigned precision)
416 {
417     if (precision > TS_MAX_CLOCK_PRECISION_DIGITS)
418         return 0;
419     ctx->clock_precision_digits = precision;
420     return 1;
421 }
422
423 /* Main entry method of the response generation. */
424 TS_RESP *TS_RESP_create_response(TS_RESP_CTX *ctx, BIO *req_bio)
425 {
426     ASN1_OBJECT *policy;
427     TS_RESP *response;
428     int result = 0;
429
430     ts_RESP_CTX_init(ctx);
431
432     /* Creating the response object. */
433     if ((ctx->response = TS_RESP_new()) == NULL) {
434         TSerr(TS_F_TS_RESP_CREATE_RESPONSE, ERR_R_MALLOC_FAILURE);
435         goto end;
436     }
437
438     /* Parsing DER request. */
439     if ((ctx->request = d2i_TS_REQ_bio(req_bio, NULL)) == NULL) {
440         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
441                                     "Bad request format or " "system error.");
442         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_DATA_FORMAT);
443         goto end;
444     }
445
446     /* Setting default status info. */
447     if (!TS_RESP_CTX_set_status_info(ctx, TS_STATUS_GRANTED, NULL))
448         goto end;
449
450     /* Checking the request format. */
451     if (!ts_RESP_check_request(ctx))
452         goto end;
453
454     /* Checking acceptable policies. */
455     if ((policy = ts_RESP_get_policy(ctx)) == NULL)
456         goto end;
457
458     /* Creating the TS_TST_INFO object. */
459     if ((ctx->tst_info = ts_RESP_create_tst_info(ctx, policy)) == NULL)
460         goto end;
461
462     /* Processing extensions. */
463     if (!ts_RESP_process_extensions(ctx))
464         goto end;
465
466     /* Generating the signature. */
467     if (!ts_RESP_sign(ctx))
468         goto end;
469
470     /* Everything was successful. */
471     result = 1;
472  end:
473     if (!result) {
474         TSerr(TS_F_TS_RESP_CREATE_RESPONSE, TS_R_RESPONSE_SETUP_ERROR);
475         if (ctx->response != NULL) {
476             if (TS_RESP_CTX_set_status_info_cond(ctx,
477                                                  TS_STATUS_REJECTION,
478                                                  "Error during response "
479                                                  "generation.") == 0) {
480                 TS_RESP_free(ctx->response);
481                 ctx->response = NULL;
482             }
483         }
484     }
485     response = ctx->response;
486     ctx->response = NULL;       /* Ownership will be returned to caller. */
487     ts_RESP_CTX_cleanup(ctx);
488     return response;
489 }
490
491 /* Initializes the variable part of the context. */
492 static void ts_RESP_CTX_init(TS_RESP_CTX *ctx)
493 {
494     ctx->request = NULL;
495     ctx->response = NULL;
496     ctx->tst_info = NULL;
497 }
498
499 /* Cleans up the variable part of the context. */
500 static void ts_RESP_CTX_cleanup(TS_RESP_CTX *ctx)
501 {
502     TS_REQ_free(ctx->request);
503     ctx->request = NULL;
504     TS_RESP_free(ctx->response);
505     ctx->response = NULL;
506     TS_TST_INFO_free(ctx->tst_info);
507     ctx->tst_info = NULL;
508 }
509
510 /* Checks the format and content of the request. */
511 static int ts_RESP_check_request(TS_RESP_CTX *ctx)
512 {
513     TS_REQ *request = ctx->request;
514     TS_MSG_IMPRINT *msg_imprint;
515     X509_ALGOR *md_alg;
516     int md_alg_id;
517     const ASN1_OCTET_STRING *digest;
518     EVP_MD *md = NULL;
519     int i;
520
521     /* Checking request version. */
522     if (TS_REQ_get_version(request) != 1) {
523         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
524                                     "Bad request version.");
525         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_REQUEST);
526         return 0;
527     }
528
529     /* Checking message digest algorithm. */
530     msg_imprint = request->msg_imprint;
531     md_alg = msg_imprint->hash_algo;
532     md_alg_id = OBJ_obj2nid(md_alg->algorithm);
533     for (i = 0; !md && i < sk_EVP_MD_num(ctx->mds); ++i) {
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         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
540                                     "Message digest algorithm is "
541                                     "not supported.");
542         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_ALG);
543         return 0;
544     }
545
546     /* No message digest takes parameter. */
547     if (md_alg->parameter && ASN1_TYPE_get(md_alg->parameter) != V_ASN1_NULL) {
548         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
549                                     "Superfluous message digest "
550                                     "parameter.");
551         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_ALG);
552         return 0;
553     }
554     /* Checking message digest size. */
555     digest = msg_imprint->hashed_msg;
556     if (digest->length != EVP_MD_size(md)) {
557         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
558                                     "Bad message digest.");
559         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_DATA_FORMAT);
560         return 0;
561     }
562
563     return 1;
564 }
565
566 /* Returns the TSA policy based on the requested and acceptable policies. */
567 static ASN1_OBJECT *ts_RESP_get_policy(TS_RESP_CTX *ctx)
568 {
569     ASN1_OBJECT *requested = ctx->request->policy_id;
570     ASN1_OBJECT *policy = NULL;
571     int i;
572
573     if (ctx->default_policy == NULL) {
574         TSerr(TS_F_TS_RESP_GET_POLICY, TS_R_INVALID_NULL_POINTER);
575         return NULL;
576     }
577     /*
578      * Return the default policy if none is requested or the default is
579      * requested.
580      */
581     if (!requested || !OBJ_cmp(requested, ctx->default_policy))
582         policy = ctx->default_policy;
583
584     /* Check if the policy is acceptable. */
585     for (i = 0; !policy && i < sk_ASN1_OBJECT_num(ctx->policies); ++i) {
586         ASN1_OBJECT *current = sk_ASN1_OBJECT_value(ctx->policies, i);
587         if (!OBJ_cmp(requested, current))
588             policy = current;
589     }
590     if (!policy) {
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 " "supported.");
594         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_UNACCEPTED_POLICY);
595     }
596     return policy;
597 }
598
599 /* Creates the TS_TST_INFO object based on the settings of the context. */
600 static TS_TST_INFO *ts_RESP_create_tst_info(TS_RESP_CTX *ctx,
601                                             ASN1_OBJECT *policy)
602 {
603     int result = 0;
604     TS_TST_INFO *tst_info = NULL;
605     ASN1_INTEGER *serial = NULL;
606     ASN1_GENERALIZEDTIME *asn1_time = NULL;
607     long sec, usec;
608     TS_ACCURACY *accuracy = NULL;
609     const ASN1_INTEGER *nonce;
610     GENERAL_NAME *tsa_name = NULL;
611
612     if ((tst_info = TS_TST_INFO_new()) == NULL)
613         goto end;
614     if (!TS_TST_INFO_set_version(tst_info, 1))
615         goto end;
616     if (!TS_TST_INFO_set_policy_id(tst_info, policy))
617         goto end;
618     if (!TS_TST_INFO_set_msg_imprint(tst_info, ctx->request->msg_imprint))
619         goto end;
620     if ((serial = ctx->serial_cb(ctx, ctx->serial_cb_data)) == NULL
621         || !TS_TST_INFO_set_serial(tst_info, serial))
622         goto end;
623     if (!ctx->time_cb(ctx, ctx->time_cb_data, &sec, &usec)
624         || (asn1_time =
625             TS_RESP_set_genTime_with_precision(NULL, sec, usec,
626                                         ctx->clock_precision_digits)) == NULL
627         || !TS_TST_INFO_set_time(tst_info, asn1_time))
628         goto end;
629
630     /* Setting accuracy if needed. */
631     if ((ctx->seconds || ctx->millis || ctx->micros)
632         && (accuracy = TS_ACCURACY_new()) == NULL)
633         goto end;
634
635     if (ctx->seconds && !TS_ACCURACY_set_seconds(accuracy, ctx->seconds))
636         goto end;
637     if (ctx->millis && !TS_ACCURACY_set_millis(accuracy, ctx->millis))
638         goto end;
639     if (ctx->micros && !TS_ACCURACY_set_micros(accuracy, ctx->micros))
640         goto end;
641     if (accuracy && !TS_TST_INFO_set_accuracy(tst_info, accuracy))
642         goto end;
643
644     /* Setting ordering. */
645     if ((ctx->flags & TS_ORDERING)
646         && !TS_TST_INFO_set_ordering(tst_info, 1))
647         goto end;
648
649     /* Setting nonce if needed. */
650     if ((nonce = ctx->request->nonce) != NULL
651         && !TS_TST_INFO_set_nonce(tst_info, nonce))
652         goto end;
653
654     /* Setting TSA name to subject of signer certificate. */
655     if (ctx->flags & TS_TSA_NAME) {
656         if ((tsa_name = GENERAL_NAME_new()) == NULL)
657             goto end;
658         tsa_name->type = GEN_DIRNAME;
659         tsa_name->d.dirn =
660             X509_NAME_dup(X509_get_subject_name(ctx->signer_cert));
661         if (!tsa_name->d.dirn)
662             goto end;
663         if (!TS_TST_INFO_set_tsa(tst_info, tsa_name))
664             goto end;
665     }
666
667     result = 1;
668  end:
669     if (!result) {
670         TS_TST_INFO_free(tst_info);
671         tst_info = NULL;
672         TSerr(TS_F_TS_RESP_CREATE_TST_INFO, TS_R_TST_INFO_SETUP_ERROR);
673         TS_RESP_CTX_set_status_info_cond(ctx, TS_STATUS_REJECTION,
674                                          "Error during TSTInfo "
675                                          "generation.");
676     }
677     GENERAL_NAME_free(tsa_name);
678     TS_ACCURACY_free(accuracy);
679     ASN1_GENERALIZEDTIME_free(asn1_time);
680     ASN1_INTEGER_free(serial);
681
682     return tst_info;
683 }
684
685 /* Processing the extensions of the request. */
686 static int ts_RESP_process_extensions(TS_RESP_CTX *ctx)
687 {
688     STACK_OF(X509_EXTENSION) *exts = ctx->request->extensions;
689     int i;
690     int ok = 1;
691
692     for (i = 0; ok && i < sk_X509_EXTENSION_num(exts); ++i) {
693         X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
694         /*
695          * XXXXX The last argument was previously (void *)ctx->extension_cb,
696          * but ISO C doesn't permit converting a function pointer to void *.
697          * For lack of better information, I'm placing a NULL there instead.
698          * The callback can pick its own address out from the ctx anyway...
699          */
700         ok = (*ctx->extension_cb) (ctx, ext, NULL);
701     }
702
703     return ok;
704 }
705
706 /* Functions for signing the TS_TST_INFO structure of the context. */
707 static int ts_RESP_sign(TS_RESP_CTX *ctx)
708 {
709     int ret = 0;
710     PKCS7 *p7 = NULL;
711     PKCS7_SIGNER_INFO *si;
712     STACK_OF(X509) *certs;      /* Certificates to include in sc. */
713     ESS_SIGNING_CERT *sc = NULL;
714     ASN1_OBJECT *oid;
715     BIO *p7bio = NULL;
716     int i;
717
718     /* Check if signcert and pkey match. */
719     if (!X509_check_private_key(ctx->signer_cert, ctx->signer_key)) {
720         TSerr(TS_F_TS_RESP_SIGN, TS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
721         goto err;
722     }
723
724     /* Create a new PKCS7 signed object. */
725     if ((p7 = PKCS7_new()) == NULL) {
726         TSerr(TS_F_TS_RESP_SIGN, ERR_R_MALLOC_FAILURE);
727         goto err;
728     }
729     if (!PKCS7_set_type(p7, NID_pkcs7_signed))
730         goto err;
731
732     /* Force SignedData version to be 3 instead of the default 1. */
733     if (!ASN1_INTEGER_set(p7->d.sign->version, 3))
734         goto err;
735
736     /* Add signer certificate and optional certificate chain. */
737     if (ctx->request->cert_req) {
738         PKCS7_add_certificate(p7, ctx->signer_cert);
739         if (ctx->certs) {
740             for (i = 0; i < sk_X509_num(ctx->certs); ++i) {
741                 X509 *cert = sk_X509_value(ctx->certs, i);
742                 PKCS7_add_certificate(p7, cert);
743             }
744         }
745     }
746
747     /* Add a new signer info. */
748     if ((si = PKCS7_add_signature(p7, ctx->signer_cert,
749                                   ctx->signer_key, EVP_sha1())) == NULL) {
750         TSerr(TS_F_TS_RESP_SIGN, TS_R_PKCS7_ADD_SIGNATURE_ERROR);
751         goto err;
752     }
753
754     /* Add content type signed attribute to the signer info. */
755     oid = OBJ_nid2obj(NID_id_smime_ct_TSTInfo);
756     if (!PKCS7_add_signed_attribute(si, NID_pkcs9_contentType,
757                                     V_ASN1_OBJECT, oid)) {
758         TSerr(TS_F_TS_RESP_SIGN, TS_R_PKCS7_ADD_SIGNED_ATTR_ERROR);
759         goto err;
760     }
761
762     /*
763      * Create the ESS SigningCertificate attribute which contains the signer
764      * certificate id and optionally the certificate chain.
765      */
766     certs = ctx->flags & TS_ESS_CERT_ID_CHAIN ? ctx->certs : NULL;
767     if ((sc = ess_SIGNING_CERT_new_init(ctx->signer_cert, certs)) == NULL)
768         goto err;
769
770     /* Add SigningCertificate signed attribute to the signer info. */
771     if (!ESS_add_signing_cert(si, sc)) {
772         TSerr(TS_F_TS_RESP_SIGN, TS_R_ESS_ADD_SIGNING_CERT_ERROR);
773         goto err;
774     }
775
776     /* Add a new empty NID_id_smime_ct_TSTInfo encapsulated content. */
777     if (!ts_TST_INFO_content_new(p7))
778         goto err;
779
780     /* Add the DER encoded tst_info to the PKCS7 structure. */
781     if ((p7bio = PKCS7_dataInit(p7, NULL)) == NULL) {
782         TSerr(TS_F_TS_RESP_SIGN, ERR_R_MALLOC_FAILURE);
783         goto err;
784     }
785
786     /* Convert tst_info to DER. */
787     if (!i2d_TS_TST_INFO_bio(p7bio, ctx->tst_info)) {
788         TSerr(TS_F_TS_RESP_SIGN, TS_R_TS_DATASIGN);
789         goto err;
790     }
791
792     /* Create the signature and add it to the signer info. */
793     if (!PKCS7_dataFinal(p7, p7bio)) {
794         TSerr(TS_F_TS_RESP_SIGN, TS_R_TS_DATASIGN);
795         goto err;
796     }
797
798     /* Set new PKCS7 and TST_INFO objects. */
799     TS_RESP_set_tst_info(ctx->response, p7, ctx->tst_info);
800     p7 = NULL;                  /* Ownership is lost. */
801     ctx->tst_info = NULL;       /* Ownership is lost. */
802
803     ret = 1;
804  err:
805     if (!ret)
806         TS_RESP_CTX_set_status_info_cond(ctx, TS_STATUS_REJECTION,
807                                          "Error during signature "
808                                          "generation.");
809     BIO_free_all(p7bio);
810     ESS_SIGNING_CERT_free(sc);
811     PKCS7_free(p7);
812     return ret;
813 }
814
815 static ESS_SIGNING_CERT *ess_SIGNING_CERT_new_init(X509 *signcert,
816                                                    STACK_OF(X509) *certs)
817 {
818     ESS_CERT_ID *cid;
819     ESS_SIGNING_CERT *sc = NULL;
820     int i;
821
822     /* Creating the ESS_CERT_ID stack. */
823     if ((sc = ESS_SIGNING_CERT_new()) == NULL)
824         goto err;
825     if (sc->cert_ids == NULL
826         && (sc->cert_ids = sk_ESS_CERT_ID_new_null()) == NULL)
827         goto err;
828
829     /* Adding the signing certificate id. */
830     if ((cid = ess_CERT_ID_new_init(signcert, 0)) == NULL
831         || !sk_ESS_CERT_ID_push(sc->cert_ids, cid))
832         goto err;
833     /* Adding the certificate chain ids. */
834     for (i = 0; i < sk_X509_num(certs); ++i) {
835         X509 *cert = sk_X509_value(certs, i);
836         if ((cid = ess_CERT_ID_new_init(cert, 1)) == NULL
837             || !sk_ESS_CERT_ID_push(sc->cert_ids, cid))
838             goto err;
839     }
840
841     return sc;
842  err:
843     ESS_SIGNING_CERT_free(sc);
844     TSerr(TS_F_ESS_SIGNING_CERT_NEW_INIT, ERR_R_MALLOC_FAILURE);
845     return NULL;
846 }
847
848 static ESS_CERT_ID *ess_CERT_ID_new_init(X509 *cert, int issuer_needed)
849 {
850     ESS_CERT_ID *cid = NULL;
851     GENERAL_NAME *name = NULL;
852
853     /* Recompute SHA1 hash of certificate if necessary (side effect). */
854     X509_check_purpose(cert, -1, 0);
855
856     if ((cid = ESS_CERT_ID_new()) == NULL)
857         goto err;
858     if (!ASN1_OCTET_STRING_set(cid->hash, cert->sha1_hash,
859                                sizeof(cert->sha1_hash)))
860         goto err;
861
862     /* Setting the issuer/serial if requested. */
863     if (issuer_needed) {
864         /* Creating issuer/serial structure. */
865         if (cid->issuer_serial == NULL
866             && (cid->issuer_serial = ESS_ISSUER_SERIAL_new()) == NULL)
867             goto err;
868         /* Creating general name from the certificate issuer. */
869         if ((name = GENERAL_NAME_new()) == NULL)
870             goto err;
871         name->type = GEN_DIRNAME;
872         if ((name->d.dirn = X509_NAME_dup(X509_get_issuer_name(cert))) == NULL)
873             goto err;
874         if (!sk_GENERAL_NAME_push(cid->issuer_serial->issuer, name))
875             goto err;
876         name = NULL;            /* Ownership is lost. */
877         /* Setting the serial number. */
878         ASN1_INTEGER_free(cid->issuer_serial->serial);
879         if (!(cid->issuer_serial->serial =
880               ASN1_INTEGER_dup(X509_get_serialNumber(cert))))
881             goto err;
882     }
883
884     return cid;
885  err:
886     GENERAL_NAME_free(name);
887     ESS_CERT_ID_free(cid);
888     TSerr(TS_F_ESS_CERT_ID_NEW_INIT, ERR_R_MALLOC_FAILURE);
889     return NULL;
890 }
891
892 static int ts_TST_INFO_content_new(PKCS7 *p7)
893 {
894     PKCS7 *ret = NULL;
895     ASN1_OCTET_STRING *octet_string = NULL;
896
897     /* Create new encapsulated NID_id_smime_ct_TSTInfo content. */
898     if ((ret = PKCS7_new()) == NULL)
899         goto err;
900     if ((ret->d.other = ASN1_TYPE_new()) == NULL)
901         goto err;
902     ret->type = OBJ_nid2obj(NID_id_smime_ct_TSTInfo);
903     if ((octet_string = ASN1_OCTET_STRING_new()) == NULL)
904         goto err;
905     ASN1_TYPE_set(ret->d.other, V_ASN1_OCTET_STRING, octet_string);
906     octet_string = NULL;
907
908     /* Add encapsulated content to signed PKCS7 structure. */
909     if (!PKCS7_set_content(p7, ret))
910         goto err;
911
912     return 1;
913  err:
914     ASN1_OCTET_STRING_free(octet_string);
915     PKCS7_free(ret);
916     return 0;
917 }
918
919 static int ESS_add_signing_cert(PKCS7_SIGNER_INFO *si, ESS_SIGNING_CERT *sc)
920 {
921     ASN1_STRING *seq = NULL;
922     unsigned char *p, *pp = NULL;
923     int len;
924
925     len = i2d_ESS_SIGNING_CERT(sc, NULL);
926     if ((pp = OPENSSL_malloc(len)) == NULL) {
927         TSerr(TS_F_ESS_ADD_SIGNING_CERT, ERR_R_MALLOC_FAILURE);
928         goto err;
929     }
930     p = pp;
931     i2d_ESS_SIGNING_CERT(sc, &p);
932     if ((seq = ASN1_STRING_new()) == NULL || !ASN1_STRING_set(seq, pp, len)) {
933         TSerr(TS_F_ESS_ADD_SIGNING_CERT, ERR_R_MALLOC_FAILURE);
934         goto err;
935     }
936     OPENSSL_free(pp);
937     pp = NULL;
938     return PKCS7_add_signed_attribute(si,
939                                       NID_id_smime_aa_signingCertificate,
940                                       V_ASN1_SEQUENCE, seq);
941  err:
942     ASN1_STRING_free(seq);
943     OPENSSL_free(pp);
944
945     return 0;
946 }
947
948 static ASN1_GENERALIZEDTIME
949 *TS_RESP_set_genTime_with_precision(ASN1_GENERALIZEDTIME *asn1_time,
950                                     long sec, long usec, unsigned precision)
951 {
952     time_t time_sec = (time_t)sec;
953     struct tm *tm = NULL;
954     char genTime_str[17 + TS_MAX_CLOCK_PRECISION_DIGITS];
955     char *p = genTime_str;
956     char *p_end = genTime_str + sizeof(genTime_str);
957
958     if (precision > TS_MAX_CLOCK_PRECISION_DIGITS)
959         goto err;
960
961     if ((tm = gmtime(&time_sec)) == NULL)
962         goto err;
963
964     /*
965      * Put "genTime_str" in GeneralizedTime format.  We work around the
966      * restrictions imposed by rfc3280 (i.e. "GeneralizedTime values MUST
967      * NOT include fractional seconds") and OpenSSL related functions to
968      * meet the rfc3161 requirement: "GeneralizedTime syntax can include
969      * fraction-of-second details".
970      */
971     p += BIO_snprintf(p, p_end - p,
972                       "%04d%02d%02d%02d%02d%02d",
973                       tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
974                       tm->tm_hour, tm->tm_min, tm->tm_sec);
975     if (precision > 0) {
976         /* Add fraction of seconds (leave space for dot and null). */
977         BIO_snprintf(p, 2 + precision, ".%06ld", usec);
978         /*
979          * We cannot use the snprintf return value, because it might have
980          * been truncated.
981          */
982         p += strlen(p);
983
984         /*
985          * To make things a bit harder, X.690 | ISO/IEC 8825-1 provides the
986          * following restrictions for a DER-encoding, which OpenSSL
987          * (specifically ASN1_GENERALIZEDTIME_check() function) doesn't
988          * support: "The encoding MUST terminate with a "Z" (which means
989          * "Zulu" time). The decimal point element, if present, MUST be the
990          * point option ".". The fractional-seconds elements, if present,
991          * MUST omit all trailing 0's; if the elements correspond to 0, they
992          * MUST be wholly omitted, and the decimal point element also MUST be
993          * omitted."
994          */
995         /*
996          * Remove trailing zeros. The dot guarantees the exit condition of
997          * this loop even if all the digits are zero.
998          */
999         while (*--p == '0')
1000             /*
1001              * empty
1002              */ ;
1003         /* p points to either the dot or the last non-zero digit. */
1004         if (*p != '.')
1005             ++p;
1006     }
1007     /* Add the trailing Z and the terminating null. */
1008     *p++ = 'Z';
1009     *p++ = '\0';
1010
1011     /* Now call OpenSSL to check and set our genTime value */
1012     if (asn1_time == NULL
1013         && (asn1_time = ASN1_GENERALIZEDTIME_new()) == NULL)
1014         goto err;
1015     if (!ASN1_GENERALIZEDTIME_set_string(asn1_time, genTime_str)) {
1016         ASN1_GENERALIZEDTIME_free(asn1_time);
1017         goto err;
1018     }
1019
1020     return asn1_time;
1021  err:
1022     TSerr(TS_F_TS_RESP_SET_GENTIME_WITH_PRECISION, TS_R_COULD_NOT_SET_TIME);
1023     return NULL;
1024 }