coverity 1462566 Resource leak
[openssl.git] / crypto / ts / ts_rsp_sign.c
1 /*
2  * Copyright 2006-2019 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 <openssl/crypto.h>
17 #include "ts_local.h"
18 #include "crypto/ess.h"
19
20 DEFINE_STACK_OF(X509)
21 DEFINE_STACK_OF(X509_EXTENSION)
22 DEFINE_STACK_OF(ASN1_UTF8STRING)
23 DEFINE_STACK_OF(ASN1_OBJECT)
24 DEFINE_STACK_OF_CONST(EVP_MD)
25
26 static ASN1_INTEGER *def_serial_cb(struct TS_resp_ctx *, void *);
27 static int def_time_cb(struct TS_resp_ctx *, void *, long *sec, long *usec);
28 static int def_extension_cb(struct TS_resp_ctx *, X509_EXTENSION *, void *);
29
30 static void ts_RESP_CTX_init(TS_RESP_CTX *ctx);
31 static void ts_RESP_CTX_cleanup(TS_RESP_CTX *ctx);
32 static int ts_RESP_check_request(TS_RESP_CTX *ctx);
33 static ASN1_OBJECT *ts_RESP_get_policy(TS_RESP_CTX *ctx);
34 static TS_TST_INFO *ts_RESP_create_tst_info(TS_RESP_CTX *ctx,
35                                             ASN1_OBJECT *policy);
36 static int ts_RESP_process_extensions(TS_RESP_CTX *ctx);
37 static int ts_RESP_sign(TS_RESP_CTX *ctx);
38
39 static int ts_TST_INFO_content_new(PKCS7 *p7);
40
41 static ASN1_GENERALIZEDTIME
42 *TS_RESP_set_genTime_with_precision(ASN1_GENERALIZEDTIME *, long, long,
43                                     unsigned);
44
45 /* Default callback for response generation. */
46 static ASN1_INTEGER *def_serial_cb(struct TS_resp_ctx *ctx, void *data)
47 {
48     ASN1_INTEGER *serial = ASN1_INTEGER_new();
49
50     if (serial == NULL)
51         goto err;
52     if (!ASN1_INTEGER_set(serial, 1))
53         goto err;
54     return serial;
55
56  err:
57     TSerr(TS_F_DEF_SERIAL_CB, ERR_R_MALLOC_FAILURE);
58     TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
59                                 "Error during serial number generation.");
60     ASN1_INTEGER_free(serial);
61     return NULL;
62 }
63
64 #if defined(OPENSSL_SYS_UNIX)
65
66 static int def_time_cb(struct TS_resp_ctx *ctx, void *data,
67                        long *sec, long *usec)
68 {
69     struct timeval tv;
70     if (gettimeofday(&tv, NULL) != 0) {
71         TSerr(TS_F_DEF_TIME_CB, TS_R_TIME_SYSCALL_ERROR);
72         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
73                                     "Time is not available.");
74         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_TIME_NOT_AVAILABLE);
75         return 0;
76     }
77     *sec = tv.tv_sec;
78     *usec = tv.tv_usec;
79
80     return 1;
81 }
82
83 #else
84
85 static int def_time_cb(struct TS_resp_ctx *ctx, void *data,
86                        long *sec, long *usec)
87 {
88     time_t t;
89     if (time(&t) == (time_t)-1) {
90         TSerr(TS_F_DEF_TIME_CB, TS_R_TIME_SYSCALL_ERROR);
91         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
92                                     "Time is not available.");
93         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_TIME_NOT_AVAILABLE);
94         return 0;
95     }
96     *sec = (long)t;
97     *usec = 0;
98
99     return 1;
100 }
101
102 #endif
103
104 static int def_extension_cb(struct TS_resp_ctx *ctx, X509_EXTENSION *ext,
105                             void *data)
106 {
107     TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
108                                 "Unsupported extension.");
109     TS_RESP_CTX_add_failure_info(ctx, TS_INFO_UNACCEPTED_EXTENSION);
110     return 0;
111 }
112
113 /* TS_RESP_CTX management functions. */
114
115 TS_RESP_CTX *TS_RESP_CTX_new(void)
116 {
117     TS_RESP_CTX *ctx;
118
119     if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL) {
120         TSerr(TS_F_TS_RESP_CTX_NEW, ERR_R_MALLOC_FAILURE);
121         return NULL;
122     }
123
124     ctx->signer_md = EVP_sha256();
125
126     ctx->serial_cb = def_serial_cb;
127     ctx->time_cb = def_time_cb;
128     ctx->extension_cb = def_extension_cb;
129
130     return ctx;
131 }
132
133 void TS_RESP_CTX_free(TS_RESP_CTX *ctx)
134 {
135     if (!ctx)
136         return;
137
138     X509_free(ctx->signer_cert);
139     EVP_PKEY_free(ctx->signer_key);
140     sk_X509_pop_free(ctx->certs, X509_free);
141     sk_ASN1_OBJECT_pop_free(ctx->policies, ASN1_OBJECT_free);
142     ASN1_OBJECT_free(ctx->default_policy);
143     sk_EVP_MD_free(ctx->mds);   /* No EVP_MD_free method exists. */
144     ASN1_INTEGER_free(ctx->seconds);
145     ASN1_INTEGER_free(ctx->millis);
146     ASN1_INTEGER_free(ctx->micros);
147     OPENSSL_free(ctx);
148 }
149
150 int TS_RESP_CTX_set_signer_cert(TS_RESP_CTX *ctx, X509 *signer)
151 {
152     if (X509_check_purpose(signer, X509_PURPOSE_TIMESTAMP_SIGN, 0) != 1) {
153         TSerr(TS_F_TS_RESP_CTX_SET_SIGNER_CERT,
154               TS_R_INVALID_SIGNER_CERTIFICATE_PURPOSE);
155         return 0;
156     }
157     X509_free(ctx->signer_cert);
158     ctx->signer_cert = signer;
159     X509_up_ref(ctx->signer_cert);
160     return 1;
161 }
162
163 int TS_RESP_CTX_set_signer_key(TS_RESP_CTX *ctx, EVP_PKEY *key)
164 {
165     EVP_PKEY_free(ctx->signer_key);
166     ctx->signer_key = key;
167     EVP_PKEY_up_ref(ctx->signer_key);
168
169     return 1;
170 }
171
172 int TS_RESP_CTX_set_signer_digest(TS_RESP_CTX *ctx, const EVP_MD *md)
173 {
174     ctx->signer_md = md;
175     return 1;
176 }
177
178 int TS_RESP_CTX_set_def_policy(TS_RESP_CTX *ctx, const ASN1_OBJECT *def_policy)
179 {
180     ASN1_OBJECT_free(ctx->default_policy);
181     if ((ctx->default_policy = OBJ_dup(def_policy)) == NULL)
182         goto err;
183     return 1;
184  err:
185     TSerr(TS_F_TS_RESP_CTX_SET_DEF_POLICY, ERR_R_MALLOC_FAILURE);
186     return 0;
187 }
188
189 int TS_RESP_CTX_set_certs(TS_RESP_CTX *ctx, STACK_OF(X509) *certs)
190 {
191
192     sk_X509_pop_free(ctx->certs, X509_free);
193     ctx->certs = NULL;
194     if (!certs)
195         return 1;
196     if ((ctx->certs = X509_chain_up_ref(certs)) == NULL) {
197         TSerr(TS_F_TS_RESP_CTX_SET_CERTS, ERR_R_MALLOC_FAILURE);
198         return 0;
199     }
200
201     return 1;
202 }
203
204 int TS_RESP_CTX_add_policy(TS_RESP_CTX *ctx, const ASN1_OBJECT *policy)
205 {
206     ASN1_OBJECT *copy = NULL;
207
208     if (ctx->policies == NULL
209         && (ctx->policies = sk_ASN1_OBJECT_new_null()) == NULL)
210         goto err;
211     if ((copy = OBJ_dup(policy)) == NULL)
212         goto err;
213     if (!sk_ASN1_OBJECT_push(ctx->policies, copy))
214         goto err;
215
216     return 1;
217  err:
218     TSerr(TS_F_TS_RESP_CTX_ADD_POLICY, ERR_R_MALLOC_FAILURE);
219     ASN1_OBJECT_free(copy);
220     return 0;
221 }
222
223 int TS_RESP_CTX_add_md(TS_RESP_CTX *ctx, const EVP_MD *md)
224 {
225     if (ctx->mds == NULL
226         && (ctx->mds = sk_EVP_MD_new_null()) == NULL)
227         goto err;
228     if (!sk_EVP_MD_push(ctx->mds, md))
229         goto err;
230
231     return 1;
232  err:
233     TSerr(TS_F_TS_RESP_CTX_ADD_MD, ERR_R_MALLOC_FAILURE);
234     return 0;
235 }
236
237 #define TS_RESP_CTX_accuracy_free(ctx)          \
238         ASN1_INTEGER_free(ctx->seconds);        \
239         ctx->seconds = NULL;                    \
240         ASN1_INTEGER_free(ctx->millis);         \
241         ctx->millis = NULL;                     \
242         ASN1_INTEGER_free(ctx->micros);         \
243         ctx->micros = NULL;
244
245 int TS_RESP_CTX_set_accuracy(TS_RESP_CTX *ctx,
246                              int secs, int millis, int micros)
247 {
248
249     TS_RESP_CTX_accuracy_free(ctx);
250     if (secs
251         && ((ctx->seconds = ASN1_INTEGER_new()) == NULL
252             || !ASN1_INTEGER_set(ctx->seconds, secs)))
253         goto err;
254     if (millis
255         && ((ctx->millis = ASN1_INTEGER_new()) == NULL
256             || !ASN1_INTEGER_set(ctx->millis, millis)))
257         goto err;
258     if (micros
259         && ((ctx->micros = ASN1_INTEGER_new()) == NULL
260             || !ASN1_INTEGER_set(ctx->micros, micros)))
261         goto err;
262
263     return 1;
264  err:
265     TS_RESP_CTX_accuracy_free(ctx);
266     TSerr(TS_F_TS_RESP_CTX_SET_ACCURACY, ERR_R_MALLOC_FAILURE);
267     return 0;
268 }
269
270 void TS_RESP_CTX_add_flags(TS_RESP_CTX *ctx, int flags)
271 {
272     ctx->flags |= flags;
273 }
274
275 void TS_RESP_CTX_set_serial_cb(TS_RESP_CTX *ctx, TS_serial_cb cb, void *data)
276 {
277     ctx->serial_cb = cb;
278     ctx->serial_cb_data = data;
279 }
280
281 void TS_RESP_CTX_set_time_cb(TS_RESP_CTX *ctx, TS_time_cb cb, void *data)
282 {
283     ctx->time_cb = cb;
284     ctx->time_cb_data = data;
285 }
286
287 void TS_RESP_CTX_set_extension_cb(TS_RESP_CTX *ctx,
288                                   TS_extension_cb cb, void *data)
289 {
290     ctx->extension_cb = cb;
291     ctx->extension_cb_data = data;
292 }
293
294 int TS_RESP_CTX_set_status_info(TS_RESP_CTX *ctx,
295                                 int status, const char *text)
296 {
297     TS_STATUS_INFO *si = NULL;
298     ASN1_UTF8STRING *utf8_text = NULL;
299     int ret = 0;
300
301     if ((si = TS_STATUS_INFO_new()) == NULL)
302         goto err;
303     if (!ASN1_INTEGER_set(si->status, status))
304         goto err;
305     if (text) {
306         if ((utf8_text = ASN1_UTF8STRING_new()) == NULL
307             || !ASN1_STRING_set(utf8_text, text, strlen(text)))
308             goto err;
309         if (si->text == NULL
310             && (si->text = sk_ASN1_UTF8STRING_new_null()) == NULL)
311             goto err;
312         if (!sk_ASN1_UTF8STRING_push(si->text, utf8_text))
313             goto err;
314         utf8_text = NULL;       /* Ownership is lost. */
315     }
316     if (!TS_RESP_set_status_info(ctx->response, si))
317         goto err;
318     ret = 1;
319  err:
320     if (!ret)
321         TSerr(TS_F_TS_RESP_CTX_SET_STATUS_INFO, ERR_R_MALLOC_FAILURE);
322     TS_STATUS_INFO_free(si);
323     ASN1_UTF8STRING_free(utf8_text);
324     return ret;
325 }
326
327 int TS_RESP_CTX_set_status_info_cond(TS_RESP_CTX *ctx,
328                                      int status, const char *text)
329 {
330     int ret = 1;
331     TS_STATUS_INFO *si = ctx->response->status_info;
332
333     if (ASN1_INTEGER_get(si->status) == TS_STATUS_GRANTED) {
334         ret = TS_RESP_CTX_set_status_info(ctx, status, text);
335     }
336     return ret;
337 }
338
339 int TS_RESP_CTX_add_failure_info(TS_RESP_CTX *ctx, int failure)
340 {
341     TS_STATUS_INFO *si = ctx->response->status_info;
342     if (si->failure_info == NULL
343         && (si->failure_info = ASN1_BIT_STRING_new()) == NULL)
344         goto err;
345     if (!ASN1_BIT_STRING_set_bit(si->failure_info, failure, 1))
346         goto err;
347     return 1;
348  err:
349     TSerr(TS_F_TS_RESP_CTX_ADD_FAILURE_INFO, ERR_R_MALLOC_FAILURE);
350     return 0;
351 }
352
353 TS_REQ *TS_RESP_CTX_get_request(TS_RESP_CTX *ctx)
354 {
355     return ctx->request;
356 }
357
358 TS_TST_INFO *TS_RESP_CTX_get_tst_info(TS_RESP_CTX *ctx)
359 {
360     return ctx->tst_info;
361 }
362
363 int TS_RESP_CTX_set_clock_precision_digits(TS_RESP_CTX *ctx,
364                                            unsigned precision)
365 {
366     if (precision > TS_MAX_CLOCK_PRECISION_DIGITS)
367         return 0;
368     ctx->clock_precision_digits = precision;
369     return 1;
370 }
371
372 /* Main entry method of the response generation. */
373 TS_RESP *TS_RESP_create_response(TS_RESP_CTX *ctx, BIO *req_bio)
374 {
375     ASN1_OBJECT *policy;
376     TS_RESP *response;
377     int result = 0;
378
379     ts_RESP_CTX_init(ctx);
380
381     if ((ctx->response = TS_RESP_new()) == NULL) {
382         TSerr(TS_F_TS_RESP_CREATE_RESPONSE, ERR_R_MALLOC_FAILURE);
383         goto end;
384     }
385     if ((ctx->request = d2i_TS_REQ_bio(req_bio, NULL)) == NULL) {
386         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
387                                     "Bad request format or system error.");
388         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_DATA_FORMAT);
389         goto end;
390     }
391     if (!TS_RESP_CTX_set_status_info(ctx, TS_STATUS_GRANTED, NULL))
392         goto end;
393     if (!ts_RESP_check_request(ctx))
394         goto end;
395     if ((policy = ts_RESP_get_policy(ctx)) == NULL)
396         goto end;
397     if ((ctx->tst_info = ts_RESP_create_tst_info(ctx, policy)) == NULL)
398         goto end;
399     if (!ts_RESP_process_extensions(ctx))
400         goto end;
401     if (!ts_RESP_sign(ctx))
402         goto end;
403     result = 1;
404
405  end:
406     if (!result) {
407         TSerr(TS_F_TS_RESP_CREATE_RESPONSE, TS_R_RESPONSE_SETUP_ERROR);
408         if (ctx->response != NULL) {
409             if (TS_RESP_CTX_set_status_info_cond(ctx,
410                                                  TS_STATUS_REJECTION,
411                                                  "Error during response "
412                                                  "generation.") == 0) {
413                 TS_RESP_free(ctx->response);
414                 ctx->response = NULL;
415             }
416         }
417     }
418     response = ctx->response;
419     ctx->response = NULL;       /* Ownership will be returned to caller. */
420     ts_RESP_CTX_cleanup(ctx);
421     return response;
422 }
423
424 /* Initializes the variable part of the context. */
425 static void ts_RESP_CTX_init(TS_RESP_CTX *ctx)
426 {
427     ctx->request = NULL;
428     ctx->response = NULL;
429     ctx->tst_info = NULL;
430 }
431
432 /* Cleans up the variable part of the context. */
433 static void ts_RESP_CTX_cleanup(TS_RESP_CTX *ctx)
434 {
435     TS_REQ_free(ctx->request);
436     ctx->request = NULL;
437     TS_RESP_free(ctx->response);
438     ctx->response = NULL;
439     TS_TST_INFO_free(ctx->tst_info);
440     ctx->tst_info = NULL;
441 }
442
443 /* Checks the format and content of the request. */
444 static int ts_RESP_check_request(TS_RESP_CTX *ctx)
445 {
446     TS_REQ *request = ctx->request;
447     TS_MSG_IMPRINT *msg_imprint;
448     X509_ALGOR *md_alg;
449     int md_alg_id;
450     const ASN1_OCTET_STRING *digest;
451     const EVP_MD *md = NULL;
452     int i;
453
454     if (TS_REQ_get_version(request) != 1) {
455         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
456                                     "Bad request version.");
457         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_REQUEST);
458         return 0;
459     }
460
461     msg_imprint = request->msg_imprint;
462     md_alg = msg_imprint->hash_algo;
463     md_alg_id = OBJ_obj2nid(md_alg->algorithm);
464     for (i = 0; !md && i < sk_EVP_MD_num(ctx->mds); ++i) {
465         const EVP_MD *current_md = sk_EVP_MD_value(ctx->mds, i);
466         if (md_alg_id == EVP_MD_type(current_md))
467             md = current_md;
468     }
469     if (!md) {
470         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
471                                     "Message digest algorithm is "
472                                     "not supported.");
473         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_ALG);
474         return 0;
475     }
476
477     if (md_alg->parameter && ASN1_TYPE_get(md_alg->parameter) != V_ASN1_NULL) {
478         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
479                                     "Superfluous message digest "
480                                     "parameter.");
481         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_ALG);
482         return 0;
483     }
484     digest = msg_imprint->hashed_msg;
485     if (digest->length != EVP_MD_size(md)) {
486         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
487                                     "Bad message digest.");
488         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_BAD_DATA_FORMAT);
489         return 0;
490     }
491
492     return 1;
493 }
494
495 /* Returns the TSA policy based on the requested and acceptable policies. */
496 static ASN1_OBJECT *ts_RESP_get_policy(TS_RESP_CTX *ctx)
497 {
498     ASN1_OBJECT *requested = ctx->request->policy_id;
499     ASN1_OBJECT *policy = NULL;
500     int i;
501
502     if (ctx->default_policy == NULL) {
503         TSerr(TS_F_TS_RESP_GET_POLICY, TS_R_INVALID_NULL_POINTER);
504         return NULL;
505     }
506     if (!requested || !OBJ_cmp(requested, ctx->default_policy))
507         policy = ctx->default_policy;
508
509     /* Check if the policy is acceptable. */
510     for (i = 0; !policy && i < sk_ASN1_OBJECT_num(ctx->policies); ++i) {
511         ASN1_OBJECT *current = sk_ASN1_OBJECT_value(ctx->policies, i);
512         if (!OBJ_cmp(requested, current))
513             policy = current;
514     }
515     if (policy == NULL) {
516         TSerr(TS_F_TS_RESP_GET_POLICY, TS_R_UNACCEPTABLE_POLICY);
517         TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
518                                     "Requested policy is not " "supported.");
519         TS_RESP_CTX_add_failure_info(ctx, TS_INFO_UNACCEPTED_POLICY);
520     }
521     return policy;
522 }
523
524 /* Creates the TS_TST_INFO object based on the settings of the context. */
525 static TS_TST_INFO *ts_RESP_create_tst_info(TS_RESP_CTX *ctx,
526                                             ASN1_OBJECT *policy)
527 {
528     int result = 0;
529     TS_TST_INFO *tst_info = NULL;
530     ASN1_INTEGER *serial = NULL;
531     ASN1_GENERALIZEDTIME *asn1_time = NULL;
532     long sec, usec;
533     TS_ACCURACY *accuracy = NULL;
534     const ASN1_INTEGER *nonce;
535     GENERAL_NAME *tsa_name = NULL;
536
537     if ((tst_info = TS_TST_INFO_new()) == NULL)
538         goto end;
539     if (!TS_TST_INFO_set_version(tst_info, 1))
540         goto end;
541     if (!TS_TST_INFO_set_policy_id(tst_info, policy))
542         goto end;
543     if (!TS_TST_INFO_set_msg_imprint(tst_info, ctx->request->msg_imprint))
544         goto end;
545     if ((serial = ctx->serial_cb(ctx, ctx->serial_cb_data)) == NULL
546         || !TS_TST_INFO_set_serial(tst_info, serial))
547         goto end;
548     if (!ctx->time_cb(ctx, ctx->time_cb_data, &sec, &usec)
549         || (asn1_time =
550             TS_RESP_set_genTime_with_precision(NULL, sec, usec,
551                                         ctx->clock_precision_digits)) == NULL
552         || !TS_TST_INFO_set_time(tst_info, asn1_time))
553         goto end;
554
555     if ((ctx->seconds || ctx->millis || ctx->micros)
556         && (accuracy = TS_ACCURACY_new()) == NULL)
557         goto end;
558     if (ctx->seconds && !TS_ACCURACY_set_seconds(accuracy, ctx->seconds))
559         goto end;
560     if (ctx->millis && !TS_ACCURACY_set_millis(accuracy, ctx->millis))
561         goto end;
562     if (ctx->micros && !TS_ACCURACY_set_micros(accuracy, ctx->micros))
563         goto end;
564     if (accuracy && !TS_TST_INFO_set_accuracy(tst_info, accuracy))
565         goto end;
566
567     if ((ctx->flags & TS_ORDERING)
568         && !TS_TST_INFO_set_ordering(tst_info, 1))
569         goto end;
570
571     if ((nonce = ctx->request->nonce) != NULL
572         && !TS_TST_INFO_set_nonce(tst_info, nonce))
573         goto end;
574
575     if (ctx->flags & TS_TSA_NAME) {
576         if ((tsa_name = GENERAL_NAME_new()) == NULL)
577             goto end;
578         tsa_name->type = GEN_DIRNAME;
579         tsa_name->d.dirn =
580             X509_NAME_dup(X509_get_subject_name(ctx->signer_cert));
581         if (!tsa_name->d.dirn)
582             goto end;
583         if (!TS_TST_INFO_set_tsa(tst_info, tsa_name))
584             goto end;
585     }
586
587     result = 1;
588  end:
589     if (!result) {
590         TS_TST_INFO_free(tst_info);
591         tst_info = NULL;
592         TSerr(TS_F_TS_RESP_CREATE_TST_INFO, TS_R_TST_INFO_SETUP_ERROR);
593         TS_RESP_CTX_set_status_info_cond(ctx, TS_STATUS_REJECTION,
594                                          "Error during TSTInfo "
595                                          "generation.");
596     }
597     GENERAL_NAME_free(tsa_name);
598     TS_ACCURACY_free(accuracy);
599     ASN1_GENERALIZEDTIME_free(asn1_time);
600     ASN1_INTEGER_free(serial);
601
602     return tst_info;
603 }
604
605 /* Processing the extensions of the request. */
606 static int ts_RESP_process_extensions(TS_RESP_CTX *ctx)
607 {
608     STACK_OF(X509_EXTENSION) *exts = ctx->request->extensions;
609     int i;
610     int ok = 1;
611
612     for (i = 0; ok && i < sk_X509_EXTENSION_num(exts); ++i) {
613         X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
614         /*
615          * The last argument was previously (void *)ctx->extension_cb,
616          * but ISO C doesn't permit converting a function pointer to void *.
617          * For lack of better information, I'm placing a NULL there instead.
618          * The callback can pick its own address out from the ctx anyway...
619          */
620         ok = (*ctx->extension_cb) (ctx, ext, NULL);
621     }
622
623     return ok;
624 }
625
626 /* Functions for signing the TS_TST_INFO structure of the context. */
627 static int ts_RESP_sign(TS_RESP_CTX *ctx)
628 {
629     int ret = 0;
630     PKCS7 *p7 = NULL;
631     PKCS7_SIGNER_INFO *si;
632     STACK_OF(X509) *certs;      /* Certificates to include in sc. */
633     ESS_SIGNING_CERT_V2 *sc2 = NULL;
634     ESS_SIGNING_CERT *sc = NULL;
635     ASN1_OBJECT *oid;
636     BIO *p7bio = NULL;
637     int i;
638
639     if (!X509_check_private_key(ctx->signer_cert, ctx->signer_key)) {
640         TSerr(TS_F_TS_RESP_SIGN, TS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
641         goto err;
642     }
643
644     if ((p7 = PKCS7_new()) == NULL) {
645         TSerr(TS_F_TS_RESP_SIGN, ERR_R_MALLOC_FAILURE);
646         goto err;
647     }
648     if (!PKCS7_set_type(p7, NID_pkcs7_signed))
649         goto err;
650     if (!ASN1_INTEGER_set(p7->d.sign->version, 3))
651         goto err;
652
653     if (ctx->request->cert_req) {
654         PKCS7_add_certificate(p7, ctx->signer_cert);
655         if (ctx->certs) {
656             for (i = 0; i < sk_X509_num(ctx->certs); ++i) {
657                 X509 *cert = sk_X509_value(ctx->certs, i);
658                 PKCS7_add_certificate(p7, cert);
659             }
660         }
661     }
662
663     if ((si = PKCS7_add_signature(p7, ctx->signer_cert,
664                                   ctx->signer_key, ctx->signer_md)) == NULL) {
665         TSerr(TS_F_TS_RESP_SIGN, TS_R_PKCS7_ADD_SIGNATURE_ERROR);
666         goto err;
667     }
668
669     oid = OBJ_nid2obj(NID_id_smime_ct_TSTInfo);
670     if (!PKCS7_add_signed_attribute(si, NID_pkcs9_contentType,
671                                     V_ASN1_OBJECT, oid)) {
672         TSerr(TS_F_TS_RESP_SIGN, TS_R_PKCS7_ADD_SIGNED_ATTR_ERROR);
673         goto err;
674     }
675
676     certs = ctx->flags & TS_ESS_CERT_ID_CHAIN ? ctx->certs : NULL;
677     if (ctx->ess_cert_id_digest == NULL
678         || ctx->ess_cert_id_digest == EVP_sha1()) {
679         if ((sc = ESS_SIGNING_CERT_new_init(ctx->signer_cert, certs, 0)) == NULL)
680             goto err;
681
682         if (!ESS_SIGNING_CERT_add(si, sc)) {
683             TSerr(TS_F_TS_RESP_SIGN, TS_R_ESS_ADD_SIGNING_CERT_ERROR);
684             goto err;
685         }
686     } else {
687         sc2 = ESS_SIGNING_CERT_V2_new_init(ctx->ess_cert_id_digest,
688                                            ctx->signer_cert, certs, 0);
689         if (sc2 == NULL)
690             goto err;
691
692         if (!ESS_SIGNING_CERT_V2_add(si, sc2)) {
693             TSerr(TS_F_TS_RESP_SIGN, TS_R_ESS_ADD_SIGNING_CERT_V2_ERROR);
694             goto err;
695         }
696     }
697
698     if (!ts_TST_INFO_content_new(p7))
699         goto err;
700     if ((p7bio = PKCS7_dataInit(p7, NULL)) == NULL) {
701         TSerr(TS_F_TS_RESP_SIGN, ERR_R_MALLOC_FAILURE);
702         goto err;
703     }
704     if (!i2d_TS_TST_INFO_bio(p7bio, ctx->tst_info)) {
705         TSerr(TS_F_TS_RESP_SIGN, TS_R_TS_DATASIGN);
706         goto err;
707     }
708     if (!PKCS7_dataFinal(p7, p7bio)) {
709         TSerr(TS_F_TS_RESP_SIGN, TS_R_TS_DATASIGN);
710         goto err;
711     }
712     TS_RESP_set_tst_info(ctx->response, p7, ctx->tst_info);
713     p7 = NULL;                  /* Ownership is lost. */
714     ctx->tst_info = NULL;       /* Ownership is lost. */
715
716     ret = 1;
717  err:
718     if (!ret)
719         TS_RESP_CTX_set_status_info_cond(ctx, TS_STATUS_REJECTION,
720                                          "Error during signature "
721                                          "generation.");
722     BIO_free_all(p7bio);
723     ESS_SIGNING_CERT_V2_free(sc2);
724     ESS_SIGNING_CERT_free(sc);
725     PKCS7_free(p7);
726     return ret;
727 }
728
729 static int ts_TST_INFO_content_new(PKCS7 *p7)
730 {
731     PKCS7 *ret = NULL;
732     ASN1_OCTET_STRING *octet_string = NULL;
733
734     /* Create new encapsulated NID_id_smime_ct_TSTInfo content. */
735     if ((ret = PKCS7_new()) == NULL)
736         goto err;
737     if ((ret->d.other = ASN1_TYPE_new()) == NULL)
738         goto err;
739     ret->type = OBJ_nid2obj(NID_id_smime_ct_TSTInfo);
740     if ((octet_string = ASN1_OCTET_STRING_new()) == NULL)
741         goto err;
742     ASN1_TYPE_set(ret->d.other, V_ASN1_OCTET_STRING, octet_string);
743     octet_string = NULL;
744
745     /* Add encapsulated content to signed PKCS7 structure. */
746     if (!PKCS7_set_content(p7, ret))
747         goto err;
748
749     return 1;
750  err:
751     ASN1_OCTET_STRING_free(octet_string);
752     PKCS7_free(ret);
753     return 0;
754 }
755
756 static ASN1_GENERALIZEDTIME *TS_RESP_set_genTime_with_precision(
757         ASN1_GENERALIZEDTIME *asn1_time, long sec, long usec,
758         unsigned precision)
759 {
760     time_t time_sec = (time_t)sec;
761     struct tm *tm = NULL, tm_result;
762     char genTime_str[17 + TS_MAX_CLOCK_PRECISION_DIGITS];
763     char *p = genTime_str;
764     char *p_end = genTime_str + sizeof(genTime_str);
765
766     if (precision > TS_MAX_CLOCK_PRECISION_DIGITS)
767         goto err;
768
769     if ((tm = OPENSSL_gmtime(&time_sec, &tm_result)) == NULL)
770         goto err;
771
772     /*
773      * Put "genTime_str" in GeneralizedTime format.  We work around the
774      * restrictions imposed by rfc3280 (i.e. "GeneralizedTime values MUST
775      * NOT include fractional seconds") and OpenSSL related functions to
776      * meet the rfc3161 requirement: "GeneralizedTime syntax can include
777      * fraction-of-second details".
778      */
779     p += BIO_snprintf(p, p_end - p,
780                       "%04d%02d%02d%02d%02d%02d",
781                       tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
782                       tm->tm_hour, tm->tm_min, tm->tm_sec);
783     if (precision > 0) {
784         BIO_snprintf(p, 2 + precision, ".%06ld", usec);
785         p += strlen(p);
786
787         /*
788          * To make things a bit harder, X.690 | ISO/IEC 8825-1 provides the
789          * following restrictions for a DER-encoding, which OpenSSL
790          * (specifically ASN1_GENERALIZEDTIME_check() function) doesn't
791          * support: "The encoding MUST terminate with a "Z" (which means
792          * "Zulu" time). The decimal point element, if present, MUST be the
793          * point option ".". The fractional-seconds elements, if present,
794          * MUST omit all trailing 0's; if the elements correspond to 0, they
795          * MUST be wholly omitted, and the decimal point element also MUST be
796          * omitted."
797          */
798         /*
799          * Remove trailing zeros. The dot guarantees the exit condition of
800          * this loop even if all the digits are zero.
801          */
802         while (*--p == '0')
803              continue;
804         if (*p != '.')
805             ++p;
806     }
807     *p++ = 'Z';
808     *p++ = '\0';
809
810     if (asn1_time == NULL
811         && (asn1_time = ASN1_GENERALIZEDTIME_new()) == NULL)
812         goto err;
813     if (!ASN1_GENERALIZEDTIME_set_string(asn1_time, genTime_str)) {
814         ASN1_GENERALIZEDTIME_free(asn1_time);
815         goto err;
816     }
817     return asn1_time;
818
819  err:
820     TSerr(TS_F_TS_RESP_SET_GENTIME_WITH_PRECISION, TS_R_COULD_NOT_SET_TIME);
821     return NULL;
822 }
823
824 int TS_RESP_CTX_set_ess_cert_id_digest(TS_RESP_CTX *ctx, const EVP_MD *md)
825 {
826     ctx->ess_cert_id_digest = md;
827     return 1;
828 }