From 8176c7633cfab82347a26983971b64d28a17440e Mon Sep 17 00:00:00 2001 From: "Dr. David von Oheimb" Date: Wed, 4 Oct 2023 21:28:04 +0200 Subject: [PATCH] CMS_get1_{certs,crls}(): make sure they return NULL only on error --- crypto/cms/cms_lib.c | 21 ++++++++++++++++----- doc/man3/CMS_add0_cert.pod | 5 +++-- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/crypto/cms/cms_lib.c b/crypto/cms/cms_lib.c index afc210c9d0c8a8..d8c4b0b8fc69bd 100644 --- a/crypto/cms/cms_lib.c +++ b/crypto/cms/cms_lib.c @@ -635,12 +635,18 @@ STACK_OF(X509) *CMS_get1_certs(CMS_ContentInfo *cms) STACK_OF(X509) *certs = NULL; CMS_CertificateChoices *cch; STACK_OF(CMS_CertificateChoices) **pcerts; - int i; + int i, n; pcerts = cms_get0_certificate_choices(cms); if (pcerts == NULL) return NULL; - for (i = 0; i < sk_CMS_CertificateChoices_num(*pcerts); i++) { + + /* make sure to return NULL only on error */ + n = sk_CMS_CertificateChoices_num(*pcerts); + if ((certs = sk_X509_new_reserve(NULL, n)) == NULL) + return NULL; + + for (i = 0; i < n; i++) { cch = sk_CMS_CertificateChoices_value(*pcerts, i); if (cch->type == 0) { if (!ossl_x509_add_cert_new(&certs, cch->d.certificate, @@ -651,7 +657,6 @@ STACK_OF(X509) *CMS_get1_certs(CMS_ContentInfo *cms) } } return certs; - } STACK_OF(X509_CRL) *CMS_get1_crls(CMS_ContentInfo *cms) @@ -659,12 +664,18 @@ STACK_OF(X509_CRL) *CMS_get1_crls(CMS_ContentInfo *cms) STACK_OF(X509_CRL) *crls = NULL; STACK_OF(CMS_RevocationInfoChoice) **pcrls; CMS_RevocationInfoChoice *rch; - int i; + int i, n; pcrls = cms_get0_revocation_choices(cms); if (pcrls == NULL) return NULL; - for (i = 0; i < sk_CMS_RevocationInfoChoice_num(*pcrls); i++) { + + /* make sure to return NULL only on error */ + n = sk_CMS_RevocationInfoChoice_num(*pcrls); + if ((crls = sk_X509_CRL_new_reserve(NULL, n)) == NULL) + return NULL; + + for (i = 0; i < n; i++) { rch = sk_CMS_RevocationInfoChoice_value(*pcrls, i); if (rch->type == 0) { if (crls == NULL) { diff --git a/doc/man3/CMS_add0_cert.pod b/doc/man3/CMS_add0_cert.pod index c876238fe4e534..8f61813f6fc1c4 100644 --- a/doc/man3/CMS_add0_cert.pod +++ b/doc/man3/CMS_add0_cert.pod @@ -57,8 +57,9 @@ For enveloped data they are added to B. CMS_add0_cert(), CMS_add1_cert() and CMS_add0_crl() and CMS_add1_crl() return 1 for success and 0 for failure. -CMS_get1_certs() and CMS_get1_crls() return the STACK of certificates or CRLs -or NULL if there are none or an error occurs. The only error which will occur +CMS_get1_certs() and CMS_get1_crls() return the STACK of certificates or CRLs, +which is empty if there are none. They return NULL on error. +Besides out-of-memory, the only error which will occur in practice is if the I type is invalid. =head1 SEE ALSO