Fix safestack issues in x509.h
[openssl.git] / crypto / ts / ts_rsp_verify.c
1 /*
2  * Copyright 2006-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include "internal/cryptlib.h"
12 #include <openssl/objects.h>
13 #include <openssl/ts.h>
14 #include <openssl/pkcs7.h>
15 #include "ts_local.h"
16 #include "crypto/ess.h"
17
18 DEFINE_STACK_OF(PKCS7_SIGNER_INFO)
19 DEFINE_STACK_OF(ESS_CERT_ID)
20 DEFINE_STACK_OF(ESS_CERT_ID_V2)
21 DEFINE_STACK_OF(ASN1_UTF8STRING)
22 DEFINE_STACK_OF(GENERAL_NAME)
23
24 static int ts_verify_cert(X509_STORE *store, STACK_OF(X509) *untrusted,
25                           X509 *signer, STACK_OF(X509) **chain);
26 static int ts_check_signing_certs(PKCS7_SIGNER_INFO *si,
27                                   STACK_OF(X509) *chain);
28
29 static int int_ts_RESP_verify_token(TS_VERIFY_CTX *ctx,
30                                     PKCS7 *token, TS_TST_INFO *tst_info);
31 static int ts_check_status_info(TS_RESP *response);
32 static char *ts_get_status_text(STACK_OF(ASN1_UTF8STRING) *text);
33 static int ts_check_policy(const ASN1_OBJECT *req_oid,
34                            const TS_TST_INFO *tst_info);
35 static int ts_compute_imprint(BIO *data, TS_TST_INFO *tst_info,
36                               X509_ALGOR **md_alg,
37                               unsigned char **imprint, unsigned *imprint_len);
38 static int ts_check_imprints(X509_ALGOR *algor_a,
39                              const unsigned char *imprint_a, unsigned len_a,
40                              TS_TST_INFO *tst_info);
41 static int ts_check_nonces(const ASN1_INTEGER *a, TS_TST_INFO *tst_info);
42 static int ts_check_signer_name(GENERAL_NAME *tsa_name, X509 *signer);
43 static int ts_find_name(STACK_OF(GENERAL_NAME) *gen_names,
44                         GENERAL_NAME *name);
45
46 /*
47  * This must be large enough to hold all values in ts_status_text (with
48  * comma separator) or all text fields in ts_failure_info (also with comma).
49  */
50 #define TS_STATUS_BUF_SIZE      256
51
52 /*
53  * Local mapping between response codes and descriptions.
54  */
55 static const char *ts_status_text[] = {
56     "granted",
57     "grantedWithMods",
58     "rejection",
59     "waiting",
60     "revocationWarning",
61     "revocationNotification"
62 };
63
64 #define TS_STATUS_TEXT_SIZE     OSSL_NELEM(ts_status_text)
65
66 static struct {
67     int code;
68     const char *text;
69 } ts_failure_info[] = {
70     {TS_INFO_BAD_ALG, "badAlg"},
71     {TS_INFO_BAD_REQUEST, "badRequest"},
72     {TS_INFO_BAD_DATA_FORMAT, "badDataFormat"},
73     {TS_INFO_TIME_NOT_AVAILABLE, "timeNotAvailable"},
74     {TS_INFO_UNACCEPTED_POLICY, "unacceptedPolicy"},
75     {TS_INFO_UNACCEPTED_EXTENSION, "unacceptedExtension"},
76     {TS_INFO_ADD_INFO_NOT_AVAILABLE, "addInfoNotAvailable"},
77     {TS_INFO_SYSTEM_FAILURE, "systemFailure"}
78 };
79
80
81 /*-
82  * This function carries out the following tasks:
83  *      - Checks if there is one and only one signer.
84  *      - Search for the signing certificate in 'certs' and in the response.
85  *      - Check the extended key usage and key usage fields of the signer
86  *      certificate (done by the path validation).
87  *      - Build and validate the certificate path.
88  *      - Check if the certificate path meets the requirements of the
89  *      SigningCertificate ESS signed attribute.
90  *      - Verify the signature value.
91  *      - Returns the signer certificate in 'signer', if 'signer' is not NULL.
92  */
93 int TS_RESP_verify_signature(PKCS7 *token, STACK_OF(X509) *certs,
94                              X509_STORE *store, X509 **signer_out)
95 {
96     STACK_OF(PKCS7_SIGNER_INFO) *sinfos = NULL;
97     PKCS7_SIGNER_INFO *si;
98     STACK_OF(X509) *signers = NULL;
99     X509 *signer;
100     STACK_OF(X509) *chain = NULL;
101     char buf[4096];
102     int i, j = 0, ret = 0;
103     BIO *p7bio = NULL;
104
105     /* Some sanity checks first. */
106     if (!token) {
107         TSerr(TS_F_TS_RESP_VERIFY_SIGNATURE, TS_R_INVALID_NULL_POINTER);
108         goto err;
109     }
110     if (!PKCS7_type_is_signed(token)) {
111         TSerr(TS_F_TS_RESP_VERIFY_SIGNATURE, TS_R_WRONG_CONTENT_TYPE);
112         goto err;
113     }
114     sinfos = PKCS7_get_signer_info(token);
115     if (!sinfos || sk_PKCS7_SIGNER_INFO_num(sinfos) != 1) {
116         TSerr(TS_F_TS_RESP_VERIFY_SIGNATURE, TS_R_THERE_MUST_BE_ONE_SIGNER);
117         goto err;
118     }
119     si = sk_PKCS7_SIGNER_INFO_value(sinfos, 0);
120     if (PKCS7_get_detached(token)) {
121         TSerr(TS_F_TS_RESP_VERIFY_SIGNATURE, TS_R_NO_CONTENT);
122         goto err;
123     }
124
125     /*
126      * Get hold of the signer certificate, search only internal certificates
127      * if it was requested.
128      */
129     signers = PKCS7_get0_signers(token, certs, 0);
130     if (!signers || sk_X509_num(signers) != 1)
131         goto err;
132     signer = sk_X509_value(signers, 0);
133
134     if (!ts_verify_cert(store, certs, signer, &chain))
135         goto err;
136     if (!ts_check_signing_certs(si, chain))
137         goto err;
138     p7bio = PKCS7_dataInit(token, NULL);
139
140     /* We now have to 'read' from p7bio to calculate digests etc. */
141     while ((i = BIO_read(p7bio, buf, sizeof(buf))) > 0)
142         continue;
143
144     j = PKCS7_signatureVerify(p7bio, token, si, signer);
145     if (j <= 0) {
146         TSerr(TS_F_TS_RESP_VERIFY_SIGNATURE, TS_R_SIGNATURE_FAILURE);
147         goto err;
148     }
149
150     if (signer_out) {
151         *signer_out = signer;
152         X509_up_ref(signer);
153     }
154     ret = 1;
155
156  err:
157     BIO_free_all(p7bio);
158     sk_X509_pop_free(chain, X509_free);
159     sk_X509_free(signers);
160
161     return ret;
162 }
163
164 /*
165  * The certificate chain is returned in chain. Caller is responsible for
166  * freeing the vector.
167  */
168 static int ts_verify_cert(X509_STORE *store, STACK_OF(X509) *untrusted,
169                           X509 *signer, STACK_OF(X509) **chain)
170 {
171     X509_STORE_CTX *cert_ctx = NULL;
172     int i;
173     int ret = 0;
174
175     *chain = NULL;
176     cert_ctx = X509_STORE_CTX_new();
177     if (cert_ctx == NULL) {
178         TSerr(TS_F_TS_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
179         goto err;
180     }
181     if (!X509_STORE_CTX_init(cert_ctx, store, signer, untrusted))
182         goto end;
183     X509_STORE_CTX_set_purpose(cert_ctx, X509_PURPOSE_TIMESTAMP_SIGN);
184     i = X509_verify_cert(cert_ctx);
185     if (i <= 0) {
186         int j = X509_STORE_CTX_get_error(cert_ctx);
187         TSerr(TS_F_TS_VERIFY_CERT, TS_R_CERTIFICATE_VERIFY_ERROR);
188         ERR_add_error_data(2, "Verify error:",
189                            X509_verify_cert_error_string(j));
190         goto err;
191     }
192     *chain = X509_STORE_CTX_get1_chain(cert_ctx);
193     ret = 1;
194     goto end;
195
196 err:
197     ret = 0;
198
199 end:
200     X509_STORE_CTX_free(cert_ctx);
201     return ret;
202 }
203
204 static int ts_check_signing_certs(PKCS7_SIGNER_INFO *si,
205                                   STACK_OF(X509) *chain)
206 {
207     ESS_SIGNING_CERT *ss = ESS_SIGNING_CERT_get(si);
208     STACK_OF(ESS_CERT_ID) *cert_ids = NULL;
209     ESS_SIGNING_CERT_V2 *ssv2 = ESS_SIGNING_CERT_V2_get(si);
210     STACK_OF(ESS_CERT_ID_V2) *cert_ids_v2 = NULL;
211     X509 *cert;
212     int i = 0;
213     int ret = 0;
214
215     if (ss != NULL) {
216         cert_ids = ss->cert_ids;
217         cert = sk_X509_value(chain, 0);
218         if (ess_find_cert(cert_ids, cert) != 0)
219             goto err;
220
221         /*
222          * Check the other certificates of the chain if there are more than one
223          * certificate ids in cert_ids.
224          */
225         if (sk_ESS_CERT_ID_num(cert_ids) > 1) {
226             for (i = 1; i < sk_X509_num(chain); ++i) {
227                 cert = sk_X509_value(chain, i);
228                 if (ess_find_cert(cert_ids, cert) < 0)
229                     goto err;
230             }
231         }
232     } else if (ssv2 != NULL) {
233         cert_ids_v2 = ssv2->cert_ids;
234         cert = sk_X509_value(chain, 0);
235         if (ess_find_cert_v2(cert_ids_v2, cert) != 0)
236             goto err;
237
238         /*
239          * Check the other certificates of the chain if there are more than one
240          * certificate ids in cert_ids.
241          */
242         if (sk_ESS_CERT_ID_V2_num(cert_ids_v2) > 1) {
243             for (i = 1; i < sk_X509_num(chain); ++i) {
244                 cert = sk_X509_value(chain, i);
245                 if (ess_find_cert_v2(cert_ids_v2, cert) < 0)
246                     goto err;
247             }
248         }
249     } else {
250         goto err;
251     }
252
253     ret = 1;
254  err:
255     if (!ret)
256         TSerr(TS_F_TS_CHECK_SIGNING_CERTS,
257               TS_R_ESS_SIGNING_CERTIFICATE_ERROR);
258     ESS_SIGNING_CERT_free(ss);
259     ESS_SIGNING_CERT_V2_free(ssv2);
260     return ret;
261 }
262
263 /*-
264  * Verifies whether 'response' contains a valid response with regards
265  * to the settings of the context:
266  *      - Gives an error message if the TS_TST_INFO is not present.
267  *      - Calls _TS_RESP_verify_token to verify the token content.
268  */
269 int TS_RESP_verify_response(TS_VERIFY_CTX *ctx, TS_RESP *response)
270 {
271     PKCS7 *token = response->token;
272     TS_TST_INFO *tst_info = response->tst_info;
273     int ret = 0;
274
275     if (!ts_check_status_info(response))
276         goto err;
277     if (!int_ts_RESP_verify_token(ctx, token, tst_info))
278         goto err;
279     ret = 1;
280
281  err:
282     return ret;
283 }
284
285 /*
286  * Tries to extract a TS_TST_INFO structure from the PKCS7 token and
287  * calls the internal int_TS_RESP_verify_token function for verifying it.
288  */
289 int TS_RESP_verify_token(TS_VERIFY_CTX *ctx, PKCS7 *token)
290 {
291     TS_TST_INFO *tst_info = PKCS7_to_TS_TST_INFO(token);
292     int ret = 0;
293     if (tst_info) {
294         ret = int_ts_RESP_verify_token(ctx, token, tst_info);
295         TS_TST_INFO_free(tst_info);
296     }
297     return ret;
298 }
299
300 /*-
301  * Verifies whether the 'token' contains a valid time stamp token
302  * with regards to the settings of the context. Only those checks are
303  * carried out that are specified in the context:
304  *      - Verifies the signature of the TS_TST_INFO.
305  *      - Checks the version number of the response.
306  *      - Check if the requested and returned policies math.
307  *      - Check if the message imprints are the same.
308  *      - Check if the nonces are the same.
309  *      - Check if the TSA name matches the signer.
310  *      - Check if the TSA name is the expected TSA.
311  */
312 static int int_ts_RESP_verify_token(TS_VERIFY_CTX *ctx,
313                                     PKCS7 *token, TS_TST_INFO *tst_info)
314 {
315     X509 *signer = NULL;
316     GENERAL_NAME *tsa_name = tst_info->tsa;
317     X509_ALGOR *md_alg = NULL;
318     unsigned char *imprint = NULL;
319     unsigned imprint_len = 0;
320     int ret = 0;
321     int flags = ctx->flags;
322
323     /* Some options require us to also check the signature */
324     if (((flags & TS_VFY_SIGNER) && tsa_name != NULL)
325             || (flags & TS_VFY_TSA_NAME)) {
326         flags |= TS_VFY_SIGNATURE;
327     }
328
329     if ((flags & TS_VFY_SIGNATURE)
330         && !TS_RESP_verify_signature(token, ctx->certs, ctx->store, &signer))
331         goto err;
332     if ((flags & TS_VFY_VERSION)
333         && TS_TST_INFO_get_version(tst_info) != 1) {
334         TSerr(TS_F_INT_TS_RESP_VERIFY_TOKEN, TS_R_UNSUPPORTED_VERSION);
335         goto err;
336     }
337     if ((flags & TS_VFY_POLICY)
338         && !ts_check_policy(ctx->policy, tst_info))
339         goto err;
340     if ((flags & TS_VFY_IMPRINT)
341         && !ts_check_imprints(ctx->md_alg, ctx->imprint, ctx->imprint_len,
342                               tst_info))
343         goto err;
344     if ((flags & TS_VFY_DATA)
345         && (!ts_compute_imprint(ctx->data, tst_info,
346                                 &md_alg, &imprint, &imprint_len)
347             || !ts_check_imprints(md_alg, imprint, imprint_len, tst_info)))
348         goto err;
349     if ((flags & TS_VFY_NONCE)
350         && !ts_check_nonces(ctx->nonce, tst_info))
351         goto err;
352     if ((flags & TS_VFY_SIGNER)
353         && tsa_name && !ts_check_signer_name(tsa_name, signer)) {
354         TSerr(TS_F_INT_TS_RESP_VERIFY_TOKEN, TS_R_TSA_NAME_MISMATCH);
355         goto err;
356     }
357     if ((flags & TS_VFY_TSA_NAME)
358         && !ts_check_signer_name(ctx->tsa_name, signer)) {
359         TSerr(TS_F_INT_TS_RESP_VERIFY_TOKEN, TS_R_TSA_UNTRUSTED);
360         goto err;
361     }
362     ret = 1;
363
364  err:
365     X509_free(signer);
366     X509_ALGOR_free(md_alg);
367     OPENSSL_free(imprint);
368     return ret;
369 }
370
371 static int ts_check_status_info(TS_RESP *response)
372 {
373     TS_STATUS_INFO *info = response->status_info;
374     long status = ASN1_INTEGER_get(info->status);
375     const char *status_text = NULL;
376     char *embedded_status_text = NULL;
377     char failure_text[TS_STATUS_BUF_SIZE] = "";
378
379     if (status == 0 || status == 1)
380         return 1;
381
382     /* There was an error, get the description in status_text. */
383     if (0 <= status && status < (long) OSSL_NELEM(ts_status_text))
384         status_text = ts_status_text[status];
385     else
386         status_text = "unknown code";
387
388     if (sk_ASN1_UTF8STRING_num(info->text) > 0
389         && (embedded_status_text = ts_get_status_text(info->text)) == NULL)
390         return 0;
391
392     /* Fill in failure_text with the failure information. */
393     if (info->failure_info) {
394         int i;
395         int first = 1;
396         for (i = 0; i < (int)OSSL_NELEM(ts_failure_info); ++i) {
397             if (ASN1_BIT_STRING_get_bit(info->failure_info,
398                                         ts_failure_info[i].code)) {
399                 if (!first)
400                     strcat(failure_text, ",");
401                 else
402                     first = 0;
403                 strcat(failure_text, ts_failure_info[i].text);
404             }
405         }
406     }
407     if (failure_text[0] == '\0')
408         strcpy(failure_text, "unspecified");
409
410     TSerr(TS_F_TS_CHECK_STATUS_INFO, TS_R_NO_TIME_STAMP_TOKEN);
411     ERR_add_error_data(6,
412                        "status code: ", status_text,
413                        ", status text: ", embedded_status_text ?
414                        embedded_status_text : "unspecified",
415                        ", failure codes: ", failure_text);
416     OPENSSL_free(embedded_status_text);
417
418     return 0;
419 }
420
421 static char *ts_get_status_text(STACK_OF(ASN1_UTF8STRING) *text)
422 {
423     return sk_ASN1_UTF8STRING2text(text, "/", TS_MAX_STATUS_LENGTH);
424 }
425
426 static int ts_check_policy(const ASN1_OBJECT *req_oid,
427                            const TS_TST_INFO *tst_info)
428 {
429     const ASN1_OBJECT *resp_oid = tst_info->policy_id;
430
431     if (OBJ_cmp(req_oid, resp_oid) != 0) {
432         TSerr(TS_F_TS_CHECK_POLICY, TS_R_POLICY_MISMATCH);
433         return 0;
434     }
435
436     return 1;
437 }
438
439 static int ts_compute_imprint(BIO *data, TS_TST_INFO *tst_info,
440                               X509_ALGOR **md_alg,
441                               unsigned char **imprint, unsigned *imprint_len)
442 {
443     TS_MSG_IMPRINT *msg_imprint = tst_info->msg_imprint;
444     X509_ALGOR *md_alg_resp = msg_imprint->hash_algo;
445     const EVP_MD *md;
446     EVP_MD_CTX *md_ctx = NULL;
447     unsigned char buffer[4096];
448     int length;
449
450     *md_alg = NULL;
451     *imprint = NULL;
452
453     if ((*md_alg = X509_ALGOR_dup(md_alg_resp)) == NULL)
454         goto err;
455     if ((md = EVP_get_digestbyobj((*md_alg)->algorithm)) == NULL) {
456         TSerr(TS_F_TS_COMPUTE_IMPRINT, TS_R_UNSUPPORTED_MD_ALGORITHM);
457         goto err;
458     }
459     length = EVP_MD_size(md);
460     if (length < 0)
461         goto err;
462     *imprint_len = length;
463     if ((*imprint = OPENSSL_malloc(*imprint_len)) == NULL) {
464         TSerr(TS_F_TS_COMPUTE_IMPRINT, ERR_R_MALLOC_FAILURE);
465         goto err;
466     }
467
468     md_ctx = EVP_MD_CTX_new();
469     if (md_ctx == NULL) {
470         TSerr(TS_F_TS_COMPUTE_IMPRINT, ERR_R_MALLOC_FAILURE);
471         goto err;
472     }
473     if (!EVP_DigestInit(md_ctx, md))
474         goto err;
475     while ((length = BIO_read(data, buffer, sizeof(buffer))) > 0) {
476         if (!EVP_DigestUpdate(md_ctx, buffer, length))
477             goto err;
478     }
479     if (!EVP_DigestFinal(md_ctx, *imprint, NULL))
480         goto err;
481     EVP_MD_CTX_free(md_ctx);
482
483     return 1;
484  err:
485     EVP_MD_CTX_free(md_ctx);
486     X509_ALGOR_free(*md_alg);
487     OPENSSL_free(*imprint);
488     *imprint_len = 0;
489     *imprint = 0;
490     return 0;
491 }
492
493 static int ts_check_imprints(X509_ALGOR *algor_a,
494                              const unsigned char *imprint_a, unsigned len_a,
495                              TS_TST_INFO *tst_info)
496 {
497     TS_MSG_IMPRINT *b = tst_info->msg_imprint;
498     X509_ALGOR *algor_b = b->hash_algo;
499     int ret = 0;
500
501     if (algor_a) {
502         if (OBJ_cmp(algor_a->algorithm, algor_b->algorithm))
503             goto err;
504
505         /* The parameter must be NULL in both. */
506         if ((algor_a->parameter
507              && ASN1_TYPE_get(algor_a->parameter) != V_ASN1_NULL)
508             || (algor_b->parameter
509                 && ASN1_TYPE_get(algor_b->parameter) != V_ASN1_NULL))
510             goto err;
511     }
512
513     ret = len_a == (unsigned)ASN1_STRING_length(b->hashed_msg) &&
514         memcmp(imprint_a, ASN1_STRING_get0_data(b->hashed_msg), len_a) == 0;
515  err:
516     if (!ret)
517         TSerr(TS_F_TS_CHECK_IMPRINTS, TS_R_MESSAGE_IMPRINT_MISMATCH);
518     return ret;
519 }
520
521 static int ts_check_nonces(const ASN1_INTEGER *a, TS_TST_INFO *tst_info)
522 {
523     const ASN1_INTEGER *b = tst_info->nonce;
524
525     if (!b) {
526         TSerr(TS_F_TS_CHECK_NONCES, TS_R_NONCE_NOT_RETURNED);
527         return 0;
528     }
529
530     /* No error if a nonce is returned without being requested. */
531     if (ASN1_INTEGER_cmp(a, b) != 0) {
532         TSerr(TS_F_TS_CHECK_NONCES, TS_R_NONCE_MISMATCH);
533         return 0;
534     }
535
536     return 1;
537 }
538
539 /*
540  * Check if the specified TSA name matches either the subject or one of the
541  * subject alternative names of the TSA certificate.
542  */
543 static int ts_check_signer_name(GENERAL_NAME *tsa_name, X509 *signer)
544 {
545     STACK_OF(GENERAL_NAME) *gen_names = NULL;
546     int idx = -1;
547     int found = 0;
548
549     if (tsa_name->type == GEN_DIRNAME
550         && X509_name_cmp(tsa_name->d.dirn, X509_get_subject_name(signer)) == 0)
551         return 1;
552     gen_names = X509_get_ext_d2i(signer, NID_subject_alt_name, NULL, &idx);
553     while (gen_names != NULL) {
554         found = ts_find_name(gen_names, tsa_name) >= 0;
555         if (found)
556             break;
557         /*
558          * Get the next subject alternative name, although there should be no
559          * more than one.
560          */
561         GENERAL_NAMES_free(gen_names);
562         gen_names = X509_get_ext_d2i(signer, NID_subject_alt_name, NULL, &idx);
563     }
564     GENERAL_NAMES_free(gen_names);
565
566     return found;
567 }
568
569 /* Returns 1 if name is in gen_names, 0 otherwise. */
570 static int ts_find_name(STACK_OF(GENERAL_NAME) *gen_names, GENERAL_NAME *name)
571 {
572     int i, found;
573     for (i = 0, found = 0; !found && i < sk_GENERAL_NAME_num(gen_names); ++i) {
574         GENERAL_NAME *current = sk_GENERAL_NAME_value(gen_names, i);
575         found = GENERAL_NAME_cmp(current, name) == 0;
576     }
577     return found ? i - 1 : -1;
578 }