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