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