add OSSL_STACK_OF_X509_free() for commonly used pattern
[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     OSSL_STACK_OF_X509_free(ctx->certs);
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     OSSL_STACK_OF_X509_free(ctx->certs);
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_get_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 ossl_ess_add1_signing_cert(PKCS7_SIGNER_INFO *si,
630                                       const ESS_SIGNING_CERT *sc)
631 {
632     ASN1_STRING *seq = NULL;
633     int len = i2d_ESS_SIGNING_CERT(sc, NULL);
634     unsigned char *p, *pp = OPENSSL_malloc(len);
635
636     if (pp == NULL)
637         return 0;
638
639     p = pp;
640     i2d_ESS_SIGNING_CERT(sc, &p);
641     if ((seq = ASN1_STRING_new()) == NULL || !ASN1_STRING_set(seq, pp, len)) {
642         ASN1_STRING_free(seq);
643         OPENSSL_free(pp);
644         return 0;
645     }
646
647     OPENSSL_free(pp);
648     return PKCS7_add_signed_attribute(si, NID_id_smime_aa_signingCertificate,
649                                       V_ASN1_SEQUENCE, seq);
650 }
651
652 static int ossl_ess_add1_signing_cert_v2(PKCS7_SIGNER_INFO *si,
653                                          const ESS_SIGNING_CERT_V2 *sc)
654 {
655     ASN1_STRING *seq = NULL;
656     int len = i2d_ESS_SIGNING_CERT_V2(sc, NULL);
657     unsigned char *p, *pp = OPENSSL_malloc(len);
658
659     if (pp == NULL)
660         return 0;
661
662     p = pp;
663     i2d_ESS_SIGNING_CERT_V2(sc, &p);
664     if ((seq = ASN1_STRING_new()) == NULL || !ASN1_STRING_set(seq, pp, len)) {
665         ASN1_STRING_free(seq);
666         OPENSSL_free(pp);
667         return 0;
668     }
669
670     OPENSSL_free(pp);
671     return PKCS7_add_signed_attribute(si, NID_id_smime_aa_signingCertificateV2,
672                                       V_ASN1_SEQUENCE, seq);
673 }
674
675 static int ts_RESP_sign(TS_RESP_CTX *ctx)
676 {
677     int ret = 0;
678     PKCS7 *p7 = NULL;
679     PKCS7_SIGNER_INFO *si;
680     STACK_OF(X509) *certs;      /* Certificates to include in sc. */
681     ESS_SIGNING_CERT_V2 *sc2 = NULL;
682     ESS_SIGNING_CERT *sc = NULL;
683     ASN1_OBJECT *oid;
684     BIO *p7bio = NULL;
685     int i;
686     EVP_MD *signer_md = NULL;
687
688     if (!X509_check_private_key(ctx->signer_cert, ctx->signer_key)) {
689         ERR_raise(ERR_LIB_TS, TS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
690         goto err;
691     }
692
693     if ((p7 = PKCS7_new_ex(ctx->libctx, ctx->propq)) == NULL) {
694         ERR_raise(ERR_LIB_TS, ERR_R_MALLOC_FAILURE);
695         goto err;
696     }
697     if (!PKCS7_set_type(p7, NID_pkcs7_signed))
698         goto err;
699     if (!ASN1_INTEGER_set(p7->d.sign->version, 3))
700         goto err;
701
702     if (ctx->request->cert_req) {
703         PKCS7_add_certificate(p7, ctx->signer_cert);
704         if (ctx->certs) {
705             for (i = 0; i < sk_X509_num(ctx->certs); ++i) {
706                 X509 *cert = sk_X509_value(ctx->certs, i);
707                 PKCS7_add_certificate(p7, cert);
708             }
709         }
710     }
711
712     if (ctx->signer_md == NULL)
713         signer_md = EVP_MD_fetch(ctx->libctx, "SHA256", ctx->propq);
714     else if (EVP_MD_get0_provider(ctx->signer_md) == NULL)
715         signer_md = EVP_MD_fetch(ctx->libctx, EVP_MD_get0_name(ctx->signer_md),
716                                  ctx->propq);
717     else
718         signer_md = (EVP_MD *)ctx->signer_md;
719
720     if ((si = PKCS7_add_signature(p7, ctx->signer_cert,
721                                   ctx->signer_key, signer_md)) == NULL) {
722         ERR_raise(ERR_LIB_TS, TS_R_PKCS7_ADD_SIGNATURE_ERROR);
723         goto err;
724     }
725
726     oid = OBJ_nid2obj(NID_id_smime_ct_TSTInfo);
727     if (!PKCS7_add_signed_attribute(si, NID_pkcs9_contentType,
728                                     V_ASN1_OBJECT, oid)) {
729         ERR_raise(ERR_LIB_TS, TS_R_PKCS7_ADD_SIGNED_ATTR_ERROR);
730         goto err;
731     }
732
733     certs = ctx->flags & TS_ESS_CERT_ID_CHAIN ? ctx->certs : NULL;
734     if (ctx->ess_cert_id_digest == NULL
735         || EVP_MD_is_a(ctx->ess_cert_id_digest, SN_sha1)) {
736         if ((sc = OSSL_ESS_signing_cert_new_init(ctx->signer_cert,
737                                                  certs, 0)) == NULL)
738             goto err;
739
740         if (!ossl_ess_add1_signing_cert(si, sc)) {
741             ERR_raise(ERR_LIB_TS, TS_R_ESS_ADD_SIGNING_CERT_ERROR);
742             goto err;
743         }
744     } else {
745         sc2 = OSSL_ESS_signing_cert_v2_new_init(ctx->ess_cert_id_digest,
746                                                 ctx->signer_cert, certs, 0);
747         if (sc2 == NULL)
748             goto err;
749
750         if (!ossl_ess_add1_signing_cert_v2(si, sc2)) {
751             ERR_raise(ERR_LIB_TS, TS_R_ESS_ADD_SIGNING_CERT_V2_ERROR);
752             goto err;
753         }
754     }
755
756     if (!ts_TST_INFO_content_new(p7))
757         goto err;
758     if ((p7bio = PKCS7_dataInit(p7, NULL)) == NULL) {
759         ERR_raise(ERR_LIB_TS, ERR_R_MALLOC_FAILURE);
760         goto err;
761     }
762     if (!i2d_TS_TST_INFO_bio(p7bio, ctx->tst_info)) {
763         ERR_raise(ERR_LIB_TS, TS_R_TS_DATASIGN);
764         goto err;
765     }
766     if (!PKCS7_dataFinal(p7, p7bio)) {
767         ERR_raise(ERR_LIB_TS, TS_R_TS_DATASIGN);
768         goto err;
769     }
770     TS_RESP_set_tst_info(ctx->response, p7, ctx->tst_info);
771     p7 = NULL;                  /* Ownership is lost. */
772     ctx->tst_info = NULL;       /* Ownership is lost. */
773
774     ret = 1;
775  err:
776     if (signer_md != ctx->signer_md)
777         EVP_MD_free(signer_md);
778
779     if (!ret)
780         TS_RESP_CTX_set_status_info_cond(ctx, TS_STATUS_REJECTION,
781                                          "Error during signature "
782                                          "generation.");
783     BIO_free_all(p7bio);
784     ESS_SIGNING_CERT_V2_free(sc2);
785     ESS_SIGNING_CERT_free(sc);
786     PKCS7_free(p7);
787     return ret;
788 }
789
790 static int ts_TST_INFO_content_new(PKCS7 *p7)
791 {
792     PKCS7 *ret = NULL;
793     ASN1_OCTET_STRING *octet_string = NULL;
794
795     /* Create new encapsulated NID_id_smime_ct_TSTInfo content. */
796     if ((ret = PKCS7_new()) == NULL)
797         goto err;
798     if ((ret->d.other = ASN1_TYPE_new()) == NULL)
799         goto err;
800     ret->type = OBJ_nid2obj(NID_id_smime_ct_TSTInfo);
801     if ((octet_string = ASN1_OCTET_STRING_new()) == NULL)
802         goto err;
803     ASN1_TYPE_set(ret->d.other, V_ASN1_OCTET_STRING, octet_string);
804     octet_string = NULL;
805
806     /* Add encapsulated content to signed PKCS7 structure. */
807     if (!PKCS7_set_content(p7, ret))
808         goto err;
809
810     return 1;
811  err:
812     ASN1_OCTET_STRING_free(octet_string);
813     PKCS7_free(ret);
814     return 0;
815 }
816
817 static ASN1_GENERALIZEDTIME *TS_RESP_set_genTime_with_precision(
818         ASN1_GENERALIZEDTIME *asn1_time, long sec, long usec,
819         unsigned precision)
820 {
821     time_t time_sec = (time_t)sec;
822     struct tm *tm = NULL, tm_result;
823     char genTime_str[17 + TS_MAX_CLOCK_PRECISION_DIGITS];
824     char *p = genTime_str;
825     char *p_end = genTime_str + sizeof(genTime_str);
826
827     if (precision > TS_MAX_CLOCK_PRECISION_DIGITS)
828         goto err;
829
830     if ((tm = OPENSSL_gmtime(&time_sec, &tm_result)) == NULL)
831         goto err;
832
833     /*
834      * Put "genTime_str" in GeneralizedTime format.  We work around the
835      * restrictions imposed by rfc3280 (i.e. "GeneralizedTime values MUST
836      * NOT include fractional seconds") and OpenSSL related functions to
837      * meet the rfc3161 requirement: "GeneralizedTime syntax can include
838      * fraction-of-second details".
839      */
840     p += BIO_snprintf(p, p_end - p,
841                       "%04d%02d%02d%02d%02d%02d",
842                       tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
843                       tm->tm_hour, tm->tm_min, tm->tm_sec);
844     if (precision > 0) {
845         BIO_snprintf(p, 2 + precision, ".%06ld", usec);
846         p += strlen(p);
847
848         /*
849          * To make things a bit harder, X.690 | ISO/IEC 8825-1 provides the
850          * following restrictions for a DER-encoding, which OpenSSL
851          * (specifically ASN1_GENERALIZEDTIME_check() function) doesn't
852          * support: "The encoding MUST terminate with a "Z" (which means
853          * "Zulu" time). The decimal point element, if present, MUST be the
854          * point option ".". The fractional-seconds elements, if present,
855          * MUST omit all trailing 0's; if the elements correspond to 0, they
856          * MUST be wholly omitted, and the decimal point element also MUST be
857          * omitted."
858          */
859         /*
860          * Remove trailing zeros. The dot guarantees the exit condition of
861          * this loop even if all the digits are zero.
862          */
863         while (*--p == '0')
864              continue;
865         if (*p != '.')
866             ++p;
867     }
868     *p++ = 'Z';
869     *p++ = '\0';
870
871     if (asn1_time == NULL
872         && (asn1_time = ASN1_GENERALIZEDTIME_new()) == NULL)
873         goto err;
874     if (!ASN1_GENERALIZEDTIME_set_string(asn1_time, genTime_str)) {
875         ASN1_GENERALIZEDTIME_free(asn1_time);
876         goto err;
877     }
878     return asn1_time;
879
880  err:
881     ERR_raise(ERR_LIB_TS, TS_R_COULD_NOT_SET_TIME);
882     return NULL;
883 }
884
885 int TS_RESP_CTX_set_ess_cert_id_digest(TS_RESP_CTX *ctx, const EVP_MD *md)
886 {
887     ctx->ess_cert_id_digest = md;
888     return 1;
889 }