Only implement secure malloc if _POSIX_VERSION allows
[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 == EVP_sha1()) {
682         if ((sc = ess_SIGNING_CERT_new_init(ctx->signer_cert, certs)) == NULL)
683             goto err;
684
685         if (!ess_add_signing_cert(si, sc)) {
686             TSerr(TS_F_TS_RESP_SIGN, TS_R_ESS_ADD_SIGNING_CERT_ERROR);
687             goto err;
688         }
689     } else {
690         sc2 = ess_signing_cert_v2_new_init(ctx->ess_cert_id_digest,
691                                            ctx->signer_cert, certs);
692         if (sc2 == NULL)
693             goto err;
694
695         if (!ess_add_signing_cert_v2(si, sc2)) {
696             TSerr(TS_F_TS_RESP_SIGN, TS_R_ESS_ADD_SIGNING_CERT_V2_ERROR);
697             goto err;
698         }
699     }
700
701     if (!ts_TST_INFO_content_new(p7))
702         goto err;
703     if ((p7bio = PKCS7_dataInit(p7, NULL)) == NULL) {
704         TSerr(TS_F_TS_RESP_SIGN, ERR_R_MALLOC_FAILURE);
705         goto err;
706     }
707     if (!i2d_TS_TST_INFO_bio(p7bio, ctx->tst_info)) {
708         TSerr(TS_F_TS_RESP_SIGN, TS_R_TS_DATASIGN);
709         goto err;
710     }
711     if (!PKCS7_dataFinal(p7, p7bio)) {
712         TSerr(TS_F_TS_RESP_SIGN, TS_R_TS_DATASIGN);
713         goto err;
714     }
715     TS_RESP_set_tst_info(ctx->response, p7, ctx->tst_info);
716     p7 = NULL;                  /* Ownership is lost. */
717     ctx->tst_info = NULL;       /* Ownership is lost. */
718
719     ret = 1;
720  err:
721     if (!ret)
722         TS_RESP_CTX_set_status_info_cond(ctx, TS_STATUS_REJECTION,
723                                          "Error during signature "
724                                          "generation.");
725     BIO_free_all(p7bio);
726     ESS_SIGNING_CERT_V2_free(sc2);
727     ESS_SIGNING_CERT_free(sc);
728     PKCS7_free(p7);
729     return ret;
730 }
731
732 static ESS_SIGNING_CERT *ess_SIGNING_CERT_new_init(X509 *signcert,
733                                                    STACK_OF(X509) *certs)
734 {
735     ESS_CERT_ID *cid;
736     ESS_SIGNING_CERT *sc = NULL;
737     int i;
738
739     if ((sc = ESS_SIGNING_CERT_new()) == NULL)
740         goto err;
741     if (sc->cert_ids == NULL
742         && (sc->cert_ids = sk_ESS_CERT_ID_new_null()) == NULL)
743         goto err;
744
745     if ((cid = ess_CERT_ID_new_init(signcert, 0)) == NULL
746         || !sk_ESS_CERT_ID_push(sc->cert_ids, cid))
747         goto err;
748     for (i = 0; i < sk_X509_num(certs); ++i) {
749         X509 *cert = sk_X509_value(certs, i);
750         if ((cid = ess_CERT_ID_new_init(cert, 1)) == NULL
751             || !sk_ESS_CERT_ID_push(sc->cert_ids, cid))
752             goto err;
753     }
754
755     return sc;
756  err:
757     ESS_SIGNING_CERT_free(sc);
758     TSerr(TS_F_ESS_SIGNING_CERT_NEW_INIT, ERR_R_MALLOC_FAILURE);
759     return NULL;
760 }
761
762 static ESS_CERT_ID *ess_CERT_ID_new_init(X509 *cert, int issuer_needed)
763 {
764     ESS_CERT_ID *cid = NULL;
765     GENERAL_NAME *name = NULL;
766     unsigned char cert_sha1[SHA_DIGEST_LENGTH];
767
768     /* Call for side-effect of computing hash and caching extensions */
769     X509_check_purpose(cert, -1, 0);
770     if ((cid = ESS_CERT_ID_new()) == NULL)
771         goto err;
772     X509_digest(cert, EVP_sha1(), cert_sha1, NULL);
773     if (!ASN1_OCTET_STRING_set(cid->hash, cert_sha1, SHA_DIGEST_LENGTH))
774         goto err;
775
776     /* Setting the issuer/serial if requested. */
777     if (issuer_needed) {
778         if (cid->issuer_serial == NULL
779             && (cid->issuer_serial = ESS_ISSUER_SERIAL_new()) == NULL)
780             goto err;
781         if ((name = GENERAL_NAME_new()) == NULL)
782             goto err;
783         name->type = GEN_DIRNAME;
784         if ((name->d.dirn = X509_NAME_dup(X509_get_issuer_name(cert))) == NULL)
785             goto err;
786         if (!sk_GENERAL_NAME_push(cid->issuer_serial->issuer, name))
787             goto err;
788         name = NULL;            /* Ownership is lost. */
789         ASN1_INTEGER_free(cid->issuer_serial->serial);
790         if (!(cid->issuer_serial->serial =
791               ASN1_INTEGER_dup(X509_get_serialNumber(cert))))
792             goto err;
793     }
794
795     return cid;
796  err:
797     GENERAL_NAME_free(name);
798     ESS_CERT_ID_free(cid);
799     TSerr(TS_F_ESS_CERT_ID_NEW_INIT, ERR_R_MALLOC_FAILURE);
800     return NULL;
801 }
802
803 static int ts_TST_INFO_content_new(PKCS7 *p7)
804 {
805     PKCS7 *ret = NULL;
806     ASN1_OCTET_STRING *octet_string = NULL;
807
808     /* Create new encapsulated NID_id_smime_ct_TSTInfo content. */
809     if ((ret = PKCS7_new()) == NULL)
810         goto err;
811     if ((ret->d.other = ASN1_TYPE_new()) == NULL)
812         goto err;
813     ret->type = OBJ_nid2obj(NID_id_smime_ct_TSTInfo);
814     if ((octet_string = ASN1_OCTET_STRING_new()) == NULL)
815         goto err;
816     ASN1_TYPE_set(ret->d.other, V_ASN1_OCTET_STRING, octet_string);
817     octet_string = NULL;
818
819     /* Add encapsulated content to signed PKCS7 structure. */
820     if (!PKCS7_set_content(p7, ret))
821         goto err;
822
823     return 1;
824  err:
825     ASN1_OCTET_STRING_free(octet_string);
826     PKCS7_free(ret);
827     return 0;
828 }
829
830 static int ess_add_signing_cert(PKCS7_SIGNER_INFO *si, ESS_SIGNING_CERT *sc)
831 {
832     ASN1_STRING *seq = NULL;
833     unsigned char *p, *pp = NULL;
834     int len;
835
836     len = i2d_ESS_SIGNING_CERT(sc, NULL);
837     if ((pp = OPENSSL_malloc(len)) == NULL) {
838         TSerr(TS_F_ESS_ADD_SIGNING_CERT, ERR_R_MALLOC_FAILURE);
839         goto err;
840     }
841     p = pp;
842     i2d_ESS_SIGNING_CERT(sc, &p);
843     if ((seq = ASN1_STRING_new()) == NULL || !ASN1_STRING_set(seq, pp, len)) {
844         TSerr(TS_F_ESS_ADD_SIGNING_CERT, ERR_R_MALLOC_FAILURE);
845         goto err;
846     }
847     OPENSSL_free(pp);
848     pp = NULL;
849     return PKCS7_add_signed_attribute(si,
850                                       NID_id_smime_aa_signingCertificate,
851                                       V_ASN1_SEQUENCE, seq);
852  err:
853     ASN1_STRING_free(seq);
854     OPENSSL_free(pp);
855
856     return 0;
857 }
858
859 static ESS_SIGNING_CERT_V2 *ess_signing_cert_v2_new_init(const EVP_MD *hash_alg,
860                                                          X509 *signcert,
861                                                          STACK_OF(X509) *certs)
862 {
863     ESS_CERT_ID_V2 *cid = NULL;
864     ESS_SIGNING_CERT_V2 *sc = NULL;
865     int i;
866
867     if ((sc = ESS_SIGNING_CERT_V2_new()) == NULL)
868         goto err;
869     if ((cid = ess_cert_id_v2_new_init(hash_alg, signcert, 0)) == NULL)
870         goto err;
871     if (!sk_ESS_CERT_ID_V2_push(sc->cert_ids, cid))
872         goto err;
873     cid = NULL;
874
875     for (i = 0; i < sk_X509_num(certs); ++i) {
876         X509 *cert = sk_X509_value(certs, i);
877
878         if ((cid = ess_cert_id_v2_new_init(hash_alg, cert, 1)) == NULL)
879             goto err;
880         if (!sk_ESS_CERT_ID_V2_push(sc->cert_ids, cid))
881             goto err;
882         cid = NULL;
883     }
884
885     return sc;
886  err:
887     ESS_SIGNING_CERT_V2_free(sc);
888     ESS_CERT_ID_V2_free(cid);
889     TSerr(TS_F_ESS_SIGNING_CERT_V2_NEW_INIT, ERR_R_MALLOC_FAILURE);
890     return NULL;
891 }
892
893 static ESS_CERT_ID_V2 *ess_cert_id_v2_new_init(const EVP_MD *hash_alg,
894                                                X509 *cert, int issuer_needed)
895 {
896     ESS_CERT_ID_V2 *cid = NULL;
897     GENERAL_NAME *name = NULL;
898     unsigned char hash[EVP_MAX_MD_SIZE];
899     unsigned int hash_len = sizeof(hash);
900     X509_ALGOR *alg = NULL;
901
902     memset(hash, 0, sizeof(hash));
903
904     if ((cid = ESS_CERT_ID_V2_new()) == NULL)
905         goto err;
906
907     if (hash_alg != EVP_sha256()) {
908         alg = X509_ALGOR_new();
909         if (alg == NULL)
910             goto err;
911         X509_ALGOR_set_md(alg, hash_alg);
912         if (alg->algorithm == NULL)
913             goto err;
914         cid->hash_alg = alg;
915         alg = NULL;
916     } else {
917         cid->hash_alg = NULL;
918     }
919
920     if (!X509_digest(cert, hash_alg, hash, &hash_len))
921         goto err;
922
923     if (!ASN1_OCTET_STRING_set(cid->hash, hash, hash_len))
924         goto err;
925
926     if (issuer_needed) {
927         if ((cid->issuer_serial = ESS_ISSUER_SERIAL_new()) == NULL)
928             goto err;
929         if ((name = GENERAL_NAME_new()) == NULL)
930             goto err;
931         name->type = GEN_DIRNAME;
932         if ((name->d.dirn = X509_NAME_dup(X509_get_issuer_name(cert))) == NULL)
933             goto err;
934         if (!sk_GENERAL_NAME_push(cid->issuer_serial->issuer, name))
935             goto err;
936         name = NULL;            /* Ownership is lost. */
937         ASN1_INTEGER_free(cid->issuer_serial->serial);
938         cid->issuer_serial->serial =
939                 ASN1_INTEGER_dup(X509_get_serialNumber(cert));
940         if (cid->issuer_serial->serial == NULL)
941             goto err;
942     }
943
944     return cid;
945  err:
946     X509_ALGOR_free(alg);
947     GENERAL_NAME_free(name);
948     ESS_CERT_ID_V2_free(cid);
949     TSerr(TS_F_ESS_CERT_ID_V2_NEW_INIT, ERR_R_MALLOC_FAILURE);
950     return NULL;
951 }
952
953 static int ess_add_signing_cert_v2(PKCS7_SIGNER_INFO *si,
954                                    ESS_SIGNING_CERT_V2 *sc)
955 {
956     ASN1_STRING *seq = NULL;
957     unsigned char *p, *pp = NULL;
958     int len = i2d_ESS_SIGNING_CERT_V2(sc, NULL);
959
960     if ((pp = OPENSSL_malloc(len)) == NULL) {
961         TSerr(TS_F_ESS_ADD_SIGNING_CERT_V2, ERR_R_MALLOC_FAILURE);
962         goto err;
963     }
964
965     p = pp;
966     i2d_ESS_SIGNING_CERT_V2(sc, &p);
967     if ((seq = ASN1_STRING_new()) == NULL || !ASN1_STRING_set(seq, pp, len)) {
968         TSerr(TS_F_ESS_ADD_SIGNING_CERT_V2, ERR_R_MALLOC_FAILURE);
969         goto err;
970     }
971
972     OPENSSL_free(pp);
973     pp = NULL;
974     return PKCS7_add_signed_attribute(si,
975                                       NID_id_smime_aa_signingCertificateV2,
976                                       V_ASN1_SEQUENCE, seq);
977  err:
978     ASN1_STRING_free(seq);
979     OPENSSL_free(pp);
980     return 0;
981 }
982
983 static ASN1_GENERALIZEDTIME *TS_RESP_set_genTime_with_precision(
984         ASN1_GENERALIZEDTIME *asn1_time, long sec, long usec,
985         unsigned precision)
986 {
987     time_t time_sec = (time_t)sec;
988     struct tm *tm = NULL;
989     char genTime_str[17 + TS_MAX_CLOCK_PRECISION_DIGITS];
990     char *p = genTime_str;
991     char *p_end = genTime_str + sizeof(genTime_str);
992
993     if (precision > TS_MAX_CLOCK_PRECISION_DIGITS)
994         goto err;
995
996     if ((tm = gmtime(&time_sec)) == NULL)
997         goto err;
998
999     /*
1000      * Put "genTime_str" in GeneralizedTime format.  We work around the
1001      * restrictions imposed by rfc3280 (i.e. "GeneralizedTime values MUST
1002      * NOT include fractional seconds") and OpenSSL related functions to
1003      * meet the rfc3161 requirement: "GeneralizedTime syntax can include
1004      * fraction-of-second details".
1005      */
1006     p += BIO_snprintf(p, p_end - p,
1007                       "%04d%02d%02d%02d%02d%02d",
1008                       tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1009                       tm->tm_hour, tm->tm_min, tm->tm_sec);
1010     if (precision > 0) {
1011         BIO_snprintf(p, 2 + precision, ".%06ld", usec);
1012         p += strlen(p);
1013
1014         /*
1015          * To make things a bit harder, X.690 | ISO/IEC 8825-1 provides the
1016          * following restrictions for a DER-encoding, which OpenSSL
1017          * (specifically ASN1_GENERALIZEDTIME_check() function) doesn't
1018          * support: "The encoding MUST terminate with a "Z" (which means
1019          * "Zulu" time). The decimal point element, if present, MUST be the
1020          * point option ".". The fractional-seconds elements, if present,
1021          * MUST omit all trailing 0's; if the elements correspond to 0, they
1022          * MUST be wholly omitted, and the decimal point element also MUST be
1023          * omitted."
1024          */
1025         /*
1026          * Remove trailing zeros. The dot guarantees the exit condition of
1027          * this loop even if all the digits are zero.
1028          */
1029         while (*--p == '0')
1030              continue;
1031         if (*p != '.')
1032             ++p;
1033     }
1034     *p++ = 'Z';
1035     *p++ = '\0';
1036
1037     if (asn1_time == NULL
1038         && (asn1_time = ASN1_GENERALIZEDTIME_new()) == NULL)
1039         goto err;
1040     if (!ASN1_GENERALIZEDTIME_set_string(asn1_time, genTime_str)) {
1041         ASN1_GENERALIZEDTIME_free(asn1_time);
1042         goto err;
1043     }
1044     return asn1_time;
1045
1046  err:
1047     TSerr(TS_F_TS_RESP_SET_GENTIME_WITH_PRECISION, TS_R_COULD_NOT_SET_TIME);
1048     return NULL;
1049 }
1050
1051 int TS_RESP_CTX_set_ess_cert_id_digest(TS_RESP_CTX *ctx, const EVP_MD *md)
1052 {
1053     ctx->ess_cert_id_digest = md;
1054     return 1;
1055 }