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