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