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