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