Remove /* foo.c */ comments
[openssl.git] / crypto / ts / ts_rsp_sign.c
1 /*
2  * Written by Zoltan Glozik (zglozik@stones.com) for the OpenSSL project
3  * 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 "internal/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 #include "ts_lcl.h"
69
70 static ASN1_INTEGER *def_serial_cb(struct TS_resp_ctx *, void *);
71 static int def_time_cb(struct TS_resp_ctx *, void *, long *sec, long *usec);
72 static int def_extension_cb(struct TS_resp_ctx *, X509_EXTENSION *, void *);
73
74 static void ts_RESP_CTX_init(TS_RESP_CTX *ctx);
75 static void ts_RESP_CTX_cleanup(TS_RESP_CTX *ctx);
76 static int ts_RESP_check_request(TS_RESP_CTX *ctx);
77 static ASN1_OBJECT *ts_RESP_get_policy(TS_RESP_CTX *ctx);
78 static TS_TST_INFO *ts_RESP_create_tst_info(TS_RESP_CTX *ctx,
79                                             ASN1_OBJECT *policy);
80 static int ts_RESP_process_extensions(TS_RESP_CTX *ctx);
81 static int ts_RESP_sign(TS_RESP_CTX *ctx);
82
83 static ESS_SIGNING_CERT *ess_SIGNING_CERT_new_init(X509 *signcert,
84                                                    STACK_OF(X509) *certs);
85 static ESS_CERT_ID *ess_CERT_ID_new_init(X509 *cert, int issuer_needed);
86 static int ts_TST_INFO_content_new(PKCS7 *p7);
87 static int ESS_add_signing_cert(PKCS7_SIGNER_INFO *si, ESS_SIGNING_CERT *sc);
88
89 static ASN1_GENERALIZEDTIME
90 *TS_RESP_set_genTime_with_precision(ASN1_GENERALIZEDTIME *, long, long,
91                                     unsigned);
92
93 /* Default callback for response generation. */
94 static ASN1_INTEGER *def_serial_cb(struct TS_resp_ctx *ctx, void *data)
95 {
96     ASN1_INTEGER *serial = ASN1_INTEGER_new();
97
98     if (serial == NULL)
99         goto err;
100     if (!ASN1_INTEGER_set(serial, 1))
101         goto err;
102     return serial;
103
104  err:
105     TSerr(TS_F_DEF_SERIAL_CB, ERR_R_MALLOC_FAILURE);
106     TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
107                                 "Error during serial number generation.");
108     return NULL;
109 }
110
111 #if defined(OPENSSL_SYS_UNIX)
112
113 static int def_time_cb(struct TS_resp_ctx *ctx, void *data,
114                        long *sec, long *usec)
115 {
116     struct timeval tv;
117     if (gettimeofday(&tv, NULL) != 0) {
118         TSerr(TS_F_DEF_TIME_CB, TS_R_TIME_SYSCALL_ERROR);
119         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
120                                     "Time is not available.");
121         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_TIME_NOT_AVAILABLE);
122         return 0;
123     }
124     *sec = tv.tv_sec;
125     *usec = tv.tv_usec;
126
127     return 1;
128 }
129
130 #else
131
132 static int def_time_cb(struct TS_resp_ctx *ctx, void *data,
133                        long *sec, long *usec)
134 {
135     time_t t;
136     if (time(&t) == (time_t)-1) {
137         TSerr(TS_F_DEF_TIME_CB, TS_R_TIME_SYSCALL_ERROR);
138         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
139                                     "Time is not available.");
140         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_TIME_NOT_AVAILABLE);
141         return 0;
142     }
143     *sec = (long)t;
144     *usec = 0;
145
146     return 1;
147 }
148
149 #endif
150
151 static int def_extension_cb(struct TS_resp_ctx *ctx, X509_EXTENSION *ext,
152                             void *data)
153 {
154     TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
155                                 "Unsupported extension.");
156     TS_RESP_CTX_add_failure_info(ctx, TS_INFO_UNACCEPTED_EXTENSION);
157     return 0;
158 }
159
160 /* TS_RESP_CTX management functions. */
161
162 TS_RESP_CTX *TS_RESP_CTX_new()
163 {
164     TS_RESP_CTX *ctx;
165
166     if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL) {
167         TSerr(TS_F_TS_RESP_CTX_NEW, ERR_R_MALLOC_FAILURE);
168         return NULL;
169     }
170
171     ctx->signer_md = EVP_sha256();
172
173     ctx->serial_cb = def_serial_cb;
174     ctx->time_cb = def_time_cb;
175     ctx->extension_cb = def_extension_cb;
176
177     return ctx;
178 }
179
180 void TS_RESP_CTX_free(TS_RESP_CTX *ctx)
181 {
182     if (!ctx)
183         return;
184
185     X509_free(ctx->signer_cert);
186     EVP_PKEY_free(ctx->signer_key);
187     sk_X509_pop_free(ctx->certs, X509_free);
188     sk_ASN1_OBJECT_pop_free(ctx->policies, ASN1_OBJECT_free);
189     ASN1_OBJECT_free(ctx->default_policy);
190     sk_EVP_MD_free(ctx->mds);   /* No EVP_MD_free method exists. */
191     ASN1_INTEGER_free(ctx->seconds);
192     ASN1_INTEGER_free(ctx->millis);
193     ASN1_INTEGER_free(ctx->micros);
194     OPENSSL_free(ctx);
195 }
196
197 int TS_RESP_CTX_set_signer_cert(TS_RESP_CTX *ctx, X509 *signer)
198 {
199     if (X509_check_purpose(signer, X509_PURPOSE_TIMESTAMP_SIGN, 0) != 1) {
200         TSerr(TS_F_TS_RESP_CTX_SET_SIGNER_CERT,
201               TS_R_INVALID_SIGNER_CERTIFICATE_PURPOSE);
202         return 0;
203     }
204     X509_free(ctx->signer_cert);
205     ctx->signer_cert = signer;
206     X509_up_ref(ctx->signer_cert);
207     return 1;
208 }
209
210 int TS_RESP_CTX_set_signer_key(TS_RESP_CTX *ctx, EVP_PKEY *key)
211 {
212     EVP_PKEY_free(ctx->signer_key);
213     ctx->signer_key = key;
214     EVP_PKEY_up_ref(ctx->signer_key);
215
216     return 1;
217 }
218
219 int TS_RESP_CTX_set_signer_digest(TS_RESP_CTX *ctx, const EVP_MD *md)
220 {
221     ctx->signer_md = md;
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     if (ctx->policies == NULL
256         && (ctx->policies = sk_ASN1_OBJECT_new_null()) == NULL)
257         goto err;
258     if ((copy = OBJ_dup(policy)) == NULL)
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     if (ctx->mds == NULL
273         && (ctx->mds = sk_EVP_MD_new_null()) == NULL)
274         goto err;
275     if (!sk_EVP_MD_push(ctx->mds, (EVP_MD *)md))
276         goto err;
277
278     return 1;
279  err:
280     TSerr(TS_F_TS_RESP_CTX_ADD_MD, ERR_R_MALLOC_FAILURE);
281     return 0;
282 }
283
284 #define TS_RESP_CTX_accuracy_free(ctx)          \
285         ASN1_INTEGER_free(ctx->seconds);        \
286         ctx->seconds = NULL;                    \
287         ASN1_INTEGER_free(ctx->millis);         \
288         ctx->millis = NULL;                     \
289         ASN1_INTEGER_free(ctx->micros);         \
290         ctx->micros = NULL;
291
292 int TS_RESP_CTX_set_accuracy(TS_RESP_CTX *ctx,
293                              int secs, int millis, int micros)
294 {
295
296     TS_RESP_CTX_accuracy_free(ctx);
297     if (secs
298         && ((ctx->seconds = ASN1_INTEGER_new()) == NULL
299             || !ASN1_INTEGER_set(ctx->seconds, secs)))
300         goto err;
301     if (millis
302         && ((ctx->millis = ASN1_INTEGER_new()) == NULL
303             || !ASN1_INTEGER_set(ctx->millis, millis)))
304         goto err;
305     if (micros
306         && ((ctx->micros = ASN1_INTEGER_new()) == NULL
307             || !ASN1_INTEGER_set(ctx->micros, micros)))
308         goto err;
309
310     return 1;
311  err:
312     TS_RESP_CTX_accuracy_free(ctx);
313     TSerr(TS_F_TS_RESP_CTX_SET_ACCURACY, ERR_R_MALLOC_FAILURE);
314     return 0;
315 }
316
317 void TS_RESP_CTX_add_flags(TS_RESP_CTX *ctx, int flags)
318 {
319     ctx->flags |= flags;
320 }
321
322 void TS_RESP_CTX_set_serial_cb(TS_RESP_CTX *ctx, TS_serial_cb cb, void *data)
323 {
324     ctx->serial_cb = cb;
325     ctx->serial_cb_data = data;
326 }
327
328 void TS_RESP_CTX_set_time_cb(TS_RESP_CTX *ctx, TS_time_cb cb, void *data)
329 {
330     ctx->time_cb = cb;
331     ctx->time_cb_data = data;
332 }
333
334 void TS_RESP_CTX_set_extension_cb(TS_RESP_CTX *ctx,
335                                   TS_extension_cb cb, void *data)
336 {
337     ctx->extension_cb = cb;
338     ctx->extension_cb_data = data;
339 }
340
341 int TS_RESP_CTX_set_status_info(TS_RESP_CTX *ctx,
342                                 int status, const char *text)
343 {
344     TS_STATUS_INFO *si = NULL;
345     ASN1_UTF8STRING *utf8_text = NULL;
346     int ret = 0;
347
348     if ((si = TS_STATUS_INFO_new()) == NULL)
349         goto err;
350     if (!ASN1_INTEGER_set(si->status, status))
351         goto err;
352     if (text) {
353         if ((utf8_text = ASN1_UTF8STRING_new()) == NULL
354             || !ASN1_STRING_set(utf8_text, text, strlen(text)))
355             goto err;
356         if (si->text == NULL
357             && (si->text = sk_ASN1_UTF8STRING_new_null()) == NULL)
358             goto err;
359         if (!sk_ASN1_UTF8STRING_push(si->text, utf8_text))
360             goto err;
361         utf8_text = NULL;       /* Ownership is lost. */
362     }
363     if (!TS_RESP_set_status_info(ctx->response, si))
364         goto err;
365     ret = 1;
366  err:
367     if (!ret)
368         TSerr(TS_F_TS_RESP_CTX_SET_STATUS_INFO, ERR_R_MALLOC_FAILURE);
369     TS_STATUS_INFO_free(si);
370     ASN1_UTF8STRING_free(utf8_text);
371     return ret;
372 }
373
374 int TS_RESP_CTX_set_status_info_cond(TS_RESP_CTX *ctx,
375                                      int status, const char *text)
376 {
377     int ret = 1;
378     TS_STATUS_INFO *si = ctx->response->status_info;
379
380     if (ASN1_INTEGER_get(si->status) == TS_STATUS_GRANTED) {
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 = ctx->response->status_info;
389     if (si->failure_info == NULL
390         && (si->failure_info = ASN1_BIT_STRING_new()) == NULL)
391         goto err;
392     if (!ASN1_BIT_STRING_set_bit(si->failure_info, failure, 1))
393         goto err;
394     return 1;
395  err:
396     TSerr(TS_F_TS_RESP_CTX_ADD_FAILURE_INFO, ERR_R_MALLOC_FAILURE);
397     return 0;
398 }
399
400 TS_REQ *TS_RESP_CTX_get_request(TS_RESP_CTX *ctx)
401 {
402     return ctx->request;
403 }
404
405 TS_TST_INFO *TS_RESP_CTX_get_tst_info(TS_RESP_CTX *ctx)
406 {
407     return ctx->tst_info;
408 }
409
410 int TS_RESP_CTX_set_clock_precision_digits(TS_RESP_CTX *ctx,
411                                            unsigned precision)
412 {
413     if (precision > TS_MAX_CLOCK_PRECISION_DIGITS)
414         return 0;
415     ctx->clock_precision_digits = precision;
416     return 1;
417 }
418
419 /* Main entry method of the response generation. */
420 TS_RESP *TS_RESP_create_response(TS_RESP_CTX *ctx, BIO *req_bio)
421 {
422     ASN1_OBJECT *policy;
423     TS_RESP *response;
424     int result = 0;
425
426     ts_RESP_CTX_init(ctx);
427
428     if ((ctx->response = TS_RESP_new()) == NULL) {
429         TSerr(TS_F_TS_RESP_CREATE_RESPONSE, ERR_R_MALLOC_FAILURE);
430         goto end;
431     }
432     if ((ctx->request = d2i_TS_REQ_bio(req_bio, NULL)) == 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     if (!TS_RESP_CTX_set_status_info(ctx, TS_STATUS_GRANTED, NULL))
439         goto end;
440     if (!ts_RESP_check_request(ctx))
441         goto end;
442     if ((policy = ts_RESP_get_policy(ctx)) == NULL)
443         goto end;
444     if ((ctx->tst_info = ts_RESP_create_tst_info(ctx, policy)) == NULL)
445         goto end;
446     if (!ts_RESP_process_extensions(ctx))
447         goto end;
448     if (!ts_RESP_sign(ctx))
449         goto end;
450     result = 1;
451
452  end:
453     if (!result) {
454         TSerr(TS_F_TS_RESP_CREATE_RESPONSE, TS_R_RESPONSE_SETUP_ERROR);
455         if (ctx->response != NULL) {
456             if (TS_RESP_CTX_set_status_info_cond(ctx,
457                                                  TS_STATUS_REJECTION,
458                                                  "Error during response "
459                                                  "generation.") == 0) {
460                 TS_RESP_free(ctx->response);
461                 ctx->response = NULL;
462             }
463         }
464     }
465     response = ctx->response;
466     ctx->response = NULL;       /* Ownership will be returned to caller. */
467     ts_RESP_CTX_cleanup(ctx);
468     return response;
469 }
470
471 /* Initializes the variable part of the context. */
472 static void ts_RESP_CTX_init(TS_RESP_CTX *ctx)
473 {
474     ctx->request = NULL;
475     ctx->response = NULL;
476     ctx->tst_info = NULL;
477 }
478
479 /* Cleans up the variable part of the context. */
480 static void ts_RESP_CTX_cleanup(TS_RESP_CTX *ctx)
481 {
482     TS_REQ_free(ctx->request);
483     ctx->request = NULL;
484     TS_RESP_free(ctx->response);
485     ctx->response = NULL;
486     TS_TST_INFO_free(ctx->tst_info);
487     ctx->tst_info = NULL;
488 }
489
490 /* Checks the format and content of the request. */
491 static int ts_RESP_check_request(TS_RESP_CTX *ctx)
492 {
493     TS_REQ *request = ctx->request;
494     TS_MSG_IMPRINT *msg_imprint;
495     X509_ALGOR *md_alg;
496     int md_alg_id;
497     const ASN1_OCTET_STRING *digest;
498     EVP_MD *md = NULL;
499     int i;
500
501     if (TS_REQ_get_version(request) != 1) {
502         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
503                                     "Bad request version.");
504         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_REQUEST);
505         return 0;
506     }
507
508     msg_imprint = request->msg_imprint;
509     md_alg = msg_imprint->hash_algo;
510     md_alg_id = OBJ_obj2nid(md_alg->algorithm);
511     for (i = 0; !md && i < sk_EVP_MD_num(ctx->mds); ++i) {
512         EVP_MD *current_md = sk_EVP_MD_value(ctx->mds, i);
513         if (md_alg_id == EVP_MD_type(current_md))
514             md = current_md;
515     }
516     if (!md) {
517         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
518                                     "Message digest algorithm is "
519                                     "not supported.");
520         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_ALG);
521         return 0;
522     }
523
524     if (md_alg->parameter && ASN1_TYPE_get(md_alg->parameter) != V_ASN1_NULL) {
525         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
526                                     "Superfluous message digest "
527                                     "parameter.");
528         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_ALG);
529         return 0;
530     }
531     digest = msg_imprint->hashed_msg;
532     if (digest->length != EVP_MD_size(md)) {
533         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
534                                     "Bad message digest.");
535         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_DATA_FORMAT);
536         return 0;
537     }
538
539     return 1;
540 }
541
542 /* Returns the TSA policy based on the requested and acceptable policies. */
543 static ASN1_OBJECT *ts_RESP_get_policy(TS_RESP_CTX *ctx)
544 {
545     ASN1_OBJECT *requested = ctx->request->policy_id;
546     ASN1_OBJECT *policy = NULL;
547     int i;
548
549     if (ctx->default_policy == NULL) {
550         TSerr(TS_F_TS_RESP_GET_POLICY, TS_R_INVALID_NULL_POINTER);
551         return NULL;
552     }
553     if (!requested || !OBJ_cmp(requested, ctx->default_policy))
554         policy = ctx->default_policy;
555
556     /* Check if the policy is acceptable. */
557     for (i = 0; !policy && i < sk_ASN1_OBJECT_num(ctx->policies); ++i) {
558         ASN1_OBJECT *current = sk_ASN1_OBJECT_value(ctx->policies, i);
559         if (!OBJ_cmp(requested, current))
560             policy = current;
561     }
562     if (!policy) {
563         TSerr(TS_F_TS_RESP_GET_POLICY, TS_R_UNACCEPTABLE_POLICY);
564         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
565                                     "Requested policy is not " "supported.");
566         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_UNACCEPTED_POLICY);
567     }
568     return policy;
569 }
570
571 /* Creates the TS_TST_INFO object based on the settings of the context. */
572 static TS_TST_INFO *ts_RESP_create_tst_info(TS_RESP_CTX *ctx,
573                                             ASN1_OBJECT *policy)
574 {
575     int result = 0;
576     TS_TST_INFO *tst_info = NULL;
577     ASN1_INTEGER *serial = NULL;
578     ASN1_GENERALIZEDTIME *asn1_time = NULL;
579     long sec, usec;
580     TS_ACCURACY *accuracy = NULL;
581     const ASN1_INTEGER *nonce;
582     GENERAL_NAME *tsa_name = NULL;
583
584     if ((tst_info = TS_TST_INFO_new()) == NULL)
585         goto end;
586     if (!TS_TST_INFO_set_version(tst_info, 1))
587         goto end;
588     if (!TS_TST_INFO_set_policy_id(tst_info, policy))
589         goto end;
590     if (!TS_TST_INFO_set_msg_imprint(tst_info, ctx->request->msg_imprint))
591         goto end;
592     if ((serial = ctx->serial_cb(ctx, ctx->serial_cb_data)) == NULL
593         || !TS_TST_INFO_set_serial(tst_info, serial))
594         goto end;
595     if (!ctx->time_cb(ctx, ctx->time_cb_data, &sec, &usec)
596         || (asn1_time =
597             TS_RESP_set_genTime_with_precision(NULL, sec, usec,
598                                         ctx->clock_precision_digits)) == NULL
599         || !TS_TST_INFO_set_time(tst_info, asn1_time))
600         goto end;
601
602     if ((ctx->seconds || ctx->millis || ctx->micros)
603         && (accuracy = TS_ACCURACY_new()) == NULL)
604         goto end;
605     if (ctx->seconds && !TS_ACCURACY_set_seconds(accuracy, ctx->seconds))
606         goto end;
607     if (ctx->millis && !TS_ACCURACY_set_millis(accuracy, ctx->millis))
608         goto end;
609     if (ctx->micros && !TS_ACCURACY_set_micros(accuracy, ctx->micros))
610         goto end;
611     if (accuracy && !TS_TST_INFO_set_accuracy(tst_info, accuracy))
612         goto end;
613
614     if ((ctx->flags & TS_ORDERING)
615         && !TS_TST_INFO_set_ordering(tst_info, 1))
616         goto end;
617
618     if ((nonce = ctx->request->nonce) != NULL
619         && !TS_TST_INFO_set_nonce(tst_info, nonce))
620         goto end;
621
622     if (ctx->flags & TS_TSA_NAME) {
623         if ((tsa_name = GENERAL_NAME_new()) == NULL)
624             goto end;
625         tsa_name->type = GEN_DIRNAME;
626         tsa_name->d.dirn =
627             X509_NAME_dup(X509_get_subject_name(ctx->signer_cert));
628         if (!tsa_name->d.dirn)
629             goto end;
630         if (!TS_TST_INFO_set_tsa(tst_info, tsa_name))
631             goto end;
632     }
633
634     result = 1;
635  end:
636     if (!result) {
637         TS_TST_INFO_free(tst_info);
638         tst_info = NULL;
639         TSerr(TS_F_TS_RESP_CREATE_TST_INFO, TS_R_TST_INFO_SETUP_ERROR);
640         TS_RESP_CTX_set_status_info_cond(ctx, TS_STATUS_REJECTION,
641                                          "Error during TSTInfo "
642                                          "generation.");
643     }
644     GENERAL_NAME_free(tsa_name);
645     TS_ACCURACY_free(accuracy);
646     ASN1_GENERALIZEDTIME_free(asn1_time);
647     ASN1_INTEGER_free(serial);
648
649     return tst_info;
650 }
651
652 /* Processing the extensions of the request. */
653 static int ts_RESP_process_extensions(TS_RESP_CTX *ctx)
654 {
655     STACK_OF(X509_EXTENSION) *exts = ctx->request->extensions;
656     int i;
657     int ok = 1;
658
659     for (i = 0; ok && i < sk_X509_EXTENSION_num(exts); ++i) {
660         X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
661         /*
662          * The last argument was previously (void *)ctx->extension_cb,
663          * but ISO C doesn't permit converting a function pointer to void *.
664          * For lack of better information, I'm placing a NULL there instead.
665          * The callback can pick its own address out from the ctx anyway...
666          */
667         ok = (*ctx->extension_cb) (ctx, ext, NULL);
668     }
669
670     return ok;
671 }
672
673 /* Functions for signing the TS_TST_INFO structure of the context. */
674 static int ts_RESP_sign(TS_RESP_CTX *ctx)
675 {
676     int ret = 0;
677     PKCS7 *p7 = NULL;
678     PKCS7_SIGNER_INFO *si;
679     STACK_OF(X509) *certs;      /* Certificates to include in sc. */
680     ESS_SIGNING_CERT *sc = NULL;
681     ASN1_OBJECT *oid;
682     BIO *p7bio = NULL;
683     int i;
684
685     if (!X509_check_private_key(ctx->signer_cert, ctx->signer_key)) {
686         TSerr(TS_F_TS_RESP_SIGN, TS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
687         goto err;
688     }
689
690     if ((p7 = PKCS7_new()) == NULL) {
691         TSerr(TS_F_TS_RESP_SIGN, ERR_R_MALLOC_FAILURE);
692         goto err;
693     }
694     if (!PKCS7_set_type(p7, NID_pkcs7_signed))
695         goto err;
696     if (!ASN1_INTEGER_set(p7->d.sign->version, 3))
697         goto err;
698
699     if (ctx->request->cert_req) {
700         PKCS7_add_certificate(p7, ctx->signer_cert);
701         if (ctx->certs) {
702             for (i = 0; i < sk_X509_num(ctx->certs); ++i) {
703                 X509 *cert = sk_X509_value(ctx->certs, i);
704                 PKCS7_add_certificate(p7, cert);
705             }
706         }
707     }
708
709     if ((si = PKCS7_add_signature(p7, ctx->signer_cert,
710                                   ctx->signer_key, ctx->signer_md)) == NULL) {
711         TSerr(TS_F_TS_RESP_SIGN, TS_R_PKCS7_ADD_SIGNATURE_ERROR);
712         goto err;
713     }
714
715     oid = OBJ_nid2obj(NID_id_smime_ct_TSTInfo);
716     if (!PKCS7_add_signed_attribute(si, NID_pkcs9_contentType,
717                                     V_ASN1_OBJECT, oid)) {
718         TSerr(TS_F_TS_RESP_SIGN, TS_R_PKCS7_ADD_SIGNED_ATTR_ERROR);
719         goto err;
720     }
721
722     certs = ctx->flags & TS_ESS_CERT_ID_CHAIN ? ctx->certs : NULL;
723     if ((sc = ess_SIGNING_CERT_new_init(ctx->signer_cert, certs)) == NULL)
724         goto err;
725     if (!ESS_add_signing_cert(si, sc)) {
726         TSerr(TS_F_TS_RESP_SIGN, TS_R_ESS_ADD_SIGNING_CERT_ERROR);
727         goto err;
728     }
729
730     if (!ts_TST_INFO_content_new(p7))
731         goto err;
732     if ((p7bio = PKCS7_dataInit(p7, NULL)) == NULL) {
733         TSerr(TS_F_TS_RESP_SIGN, ERR_R_MALLOC_FAILURE);
734         goto err;
735     }
736     if (!i2d_TS_TST_INFO_bio(p7bio, ctx->tst_info)) {
737         TSerr(TS_F_TS_RESP_SIGN, TS_R_TS_DATASIGN);
738         goto err;
739     }
740     if (!PKCS7_dataFinal(p7, p7bio)) {
741         TSerr(TS_F_TS_RESP_SIGN, TS_R_TS_DATASIGN);
742         goto err;
743     }
744     TS_RESP_set_tst_info(ctx->response, p7, ctx->tst_info);
745     p7 = NULL;                  /* Ownership is lost. */
746     ctx->tst_info = NULL;       /* Ownership is lost. */
747
748     ret = 1;
749  err:
750     if (!ret)
751         TS_RESP_CTX_set_status_info_cond(ctx, TS_STATUS_REJECTION,
752                                          "Error during signature "
753                                          "generation.");
754     BIO_free_all(p7bio);
755     ESS_SIGNING_CERT_free(sc);
756     PKCS7_free(p7);
757     return ret;
758 }
759
760 static ESS_SIGNING_CERT *ess_SIGNING_CERT_new_init(X509 *signcert,
761                                                    STACK_OF(X509) *certs)
762 {
763     ESS_CERT_ID *cid;
764     ESS_SIGNING_CERT *sc = NULL;
765     int i;
766
767     if ((sc = ESS_SIGNING_CERT_new()) == NULL)
768         goto err;
769     if (sc->cert_ids == NULL
770         && (sc->cert_ids = sk_ESS_CERT_ID_new_null()) == NULL)
771         goto err;
772
773     if ((cid = ess_CERT_ID_new_init(signcert, 0)) == NULL
774         || !sk_ESS_CERT_ID_push(sc->cert_ids, cid))
775         goto err;
776     for (i = 0; i < sk_X509_num(certs); ++i) {
777         X509 *cert = sk_X509_value(certs, i);
778         if ((cid = ess_CERT_ID_new_init(cert, 1)) == NULL
779             || !sk_ESS_CERT_ID_push(sc->cert_ids, cid))
780             goto err;
781     }
782
783     return sc;
784  err:
785     ESS_SIGNING_CERT_free(sc);
786     TSerr(TS_F_ESS_SIGNING_CERT_NEW_INIT, ERR_R_MALLOC_FAILURE);
787     return NULL;
788 }
789
790 static ESS_CERT_ID *ess_CERT_ID_new_init(X509 *cert, int issuer_needed)
791 {
792     ESS_CERT_ID *cid = NULL;
793     GENERAL_NAME *name = NULL;
794     unsigned char cert_sha1[SHA_DIGEST_LENGTH];
795
796     X509_check_purpose(cert, -1, 0);
797     if ((cid = ESS_CERT_ID_new()) == NULL)
798         goto err;
799     X509_digest(cert, EVP_sha1(), cert_sha1, NULL);
800     if (!ASN1_OCTET_STRING_set(cid->hash, cert_sha1, SHA_DIGEST_LENGTH))
801         goto err;
802
803     /* Setting the issuer/serial if requested. */
804     if (issuer_needed) {
805         if (cid->issuer_serial == NULL
806             && (cid->issuer_serial = ESS_ISSUER_SERIAL_new()) == NULL)
807             goto err;
808         if ((name = GENERAL_NAME_new()) == NULL)
809             goto err;
810         name->type = GEN_DIRNAME;
811         if ((name->d.dirn = X509_NAME_dup(X509_get_issuer_name(cert))) == NULL)
812             goto err;
813         if (!sk_GENERAL_NAME_push(cid->issuer_serial->issuer, name))
814             goto err;
815         name = NULL;            /* Ownership is lost. */
816         ASN1_INTEGER_free(cid->issuer_serial->serial);
817         if (!(cid->issuer_serial->serial =
818               ASN1_INTEGER_dup(X509_get_serialNumber(cert))))
819             goto err;
820     }
821
822     return cid;
823  err:
824     GENERAL_NAME_free(name);
825     ESS_CERT_ID_free(cid);
826     TSerr(TS_F_ESS_CERT_ID_NEW_INIT, ERR_R_MALLOC_FAILURE);
827     return NULL;
828 }
829
830 static int ts_TST_INFO_content_new(PKCS7 *p7)
831 {
832     PKCS7 *ret = NULL;
833     ASN1_OCTET_STRING *octet_string = NULL;
834
835     /* Create new encapsulated NID_id_smime_ct_TSTInfo content. */
836     if ((ret = PKCS7_new()) == NULL)
837         goto err;
838     if ((ret->d.other = ASN1_TYPE_new()) == NULL)
839         goto err;
840     ret->type = OBJ_nid2obj(NID_id_smime_ct_TSTInfo);
841     if ((octet_string = ASN1_OCTET_STRING_new()) == NULL)
842         goto err;
843     ASN1_TYPE_set(ret->d.other, V_ASN1_OCTET_STRING, octet_string);
844     octet_string = NULL;
845
846     /* Add encapsulated content to signed PKCS7 structure. */
847     if (!PKCS7_set_content(p7, ret))
848         goto err;
849
850     return 1;
851  err:
852     ASN1_OCTET_STRING_free(octet_string);
853     PKCS7_free(ret);
854     return 0;
855 }
856
857 static int ESS_add_signing_cert(PKCS7_SIGNER_INFO *si, ESS_SIGNING_CERT *sc)
858 {
859     ASN1_STRING *seq = NULL;
860     unsigned char *p, *pp = NULL;
861     int len;
862
863     len = i2d_ESS_SIGNING_CERT(sc, NULL);
864     if ((pp = OPENSSL_malloc(len)) == NULL) {
865         TSerr(TS_F_ESS_ADD_SIGNING_CERT, ERR_R_MALLOC_FAILURE);
866         goto err;
867     }
868     p = pp;
869     i2d_ESS_SIGNING_CERT(sc, &p);
870     if ((seq = ASN1_STRING_new()) == NULL || !ASN1_STRING_set(seq, pp, len)) {
871         TSerr(TS_F_ESS_ADD_SIGNING_CERT, ERR_R_MALLOC_FAILURE);
872         goto err;
873     }
874     OPENSSL_free(pp);
875     pp = NULL;
876     return PKCS7_add_signed_attribute(si,
877                                       NID_id_smime_aa_signingCertificate,
878                                       V_ASN1_SEQUENCE, seq);
879  err:
880     ASN1_STRING_free(seq);
881     OPENSSL_free(pp);
882
883     return 0;
884 }
885
886 static ASN1_GENERALIZEDTIME
887 *TS_RESP_set_genTime_with_precision(ASN1_GENERALIZEDTIME *asn1_time,
888                                     long sec, long usec, unsigned precision)
889 {
890     time_t time_sec = (time_t)sec;
891     struct tm *tm = NULL;
892     char genTime_str[17 + TS_MAX_CLOCK_PRECISION_DIGITS];
893     char *p = genTime_str;
894     char *p_end = genTime_str + sizeof(genTime_str);
895
896     if (precision > TS_MAX_CLOCK_PRECISION_DIGITS)
897         goto err;
898
899     if ((tm = gmtime(&time_sec)) == NULL)
900         goto err;
901
902     /*
903      * Put "genTime_str" in GeneralizedTime format.  We work around the
904      * restrictions imposed by rfc3280 (i.e. "GeneralizedTime values MUST
905      * NOT include fractional seconds") and OpenSSL related functions to
906      * meet the rfc3161 requirement: "GeneralizedTime syntax can include
907      * fraction-of-second details".
908      */
909     p += BIO_snprintf(p, p_end - p,
910                       "%04d%02d%02d%02d%02d%02d",
911                       tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
912                       tm->tm_hour, tm->tm_min, tm->tm_sec);
913     if (precision > 0) {
914         BIO_snprintf(p, 2 + precision, ".%06ld", usec);
915         p += strlen(p);
916
917         /*
918          * To make things a bit harder, X.690 | ISO/IEC 8825-1 provides the
919          * following restrictions for a DER-encoding, which OpenSSL
920          * (specifically ASN1_GENERALIZEDTIME_check() function) doesn't
921          * support: "The encoding MUST terminate with a "Z" (which means
922          * "Zulu" time). The decimal point element, if present, MUST be the
923          * point option ".". The fractional-seconds elements, if present,
924          * MUST omit all trailing 0's; if the elements correspond to 0, they
925          * MUST be wholly omitted, and the decimal point element also MUST be
926          * omitted."
927          */
928         /*
929          * Remove trailing zeros. The dot guarantees the exit condition of
930          * this loop even if all the digits are zero.
931          */
932         while (*--p == '0')
933              continue;
934         if (*p != '.')
935             ++p;
936     }
937     *p++ = 'Z';
938     *p++ = '\0';
939
940     if (asn1_time == NULL
941         && (asn1_time = ASN1_GENERALIZEDTIME_new()) == NULL)
942         goto err;
943     if (!ASN1_GENERALIZEDTIME_set_string(asn1_time, genTime_str)) {
944         ASN1_GENERALIZEDTIME_free(asn1_time);
945         goto err;
946     }
947     return asn1_time;
948
949  err:
950     TSerr(TS_F_TS_RESP_SET_GENTIME_WITH_PRECISION, TS_R_COULD_NOT_SET_TIME);
951     return NULL;
952 }