From d84a5f24230b93f49830e2434214f602d26d6cb4 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Thu, 26 Oct 2023 12:40:56 -0700 Subject: [PATCH] Handle empty signed data in PKCS7 This will have certificates and crls return nil instead of segfaulting. Fixes [Bug #19974] --- ext/openssl/ossl_pkcs7.c | 24 ++++++++++++++++-------- test/openssl/test_pkcs7.rb | 7 +++++++ 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/ext/openssl/ossl_pkcs7.c b/ext/openssl/ossl_pkcs7.c index 78dcbd667..5b6a181eb 100644 --- a/ext/openssl/ossl_pkcs7.c +++ b/ext/openssl/ossl_pkcs7.c @@ -609,20 +609,24 @@ static STACK_OF(X509) * pkcs7_get_certs(VALUE self) { PKCS7 *pkcs7; - STACK_OF(X509) *certs; + STACK_OF(X509) *certs = NULL; int i; GetPKCS7(self, pkcs7); i = OBJ_obj2nid(pkcs7->type); switch(i){ case NID_pkcs7_signed: - certs = pkcs7->d.sign->cert; + if (pkcs7->d.sign) { + certs = pkcs7->d.sign->cert; + } break; case NID_pkcs7_signedAndEnveloped: - certs = pkcs7->d.signed_and_enveloped->cert; + if (pkcs7->d.signed_and_enveloped) { + certs = pkcs7->d.signed_and_enveloped->cert; + } break; default: - certs = NULL; + ; /* nothing */ } return certs; @@ -632,20 +636,24 @@ static STACK_OF(X509_CRL) * pkcs7_get_crls(VALUE self) { PKCS7 *pkcs7; - STACK_OF(X509_CRL) *crls; + STACK_OF(X509_CRL) *crls = NULL; int i; GetPKCS7(self, pkcs7); i = OBJ_obj2nid(pkcs7->type); switch(i){ case NID_pkcs7_signed: - crls = pkcs7->d.sign->crl; + if (pkcs7->d.sign) { + crls = pkcs7->d.sign->crl; + } break; case NID_pkcs7_signedAndEnveloped: - crls = pkcs7->d.signed_and_enveloped->crl; + if (pkcs7->d.signed_and_enveloped) { + crls = pkcs7->d.signed_and_enveloped->crl; + } break; default: - crls = NULL; + ; /* nothing */ } return crls; diff --git a/test/openssl/test_pkcs7.rb b/test/openssl/test_pkcs7.rb index ba8b93d03..b05904e2d 100644 --- a/test/openssl/test_pkcs7.rb +++ b/test/openssl/test_pkcs7.rb @@ -155,6 +155,13 @@ def test_enveloped assert_equal(data, p7.decrypt(@rsa1024)) end + def test_empty_signed_data_ruby_bug_19974 + data = "-----BEGIN PKCS7-----\nMAsGCSqGSIb3DQEHAg==\n-----END PKCS7-----\n" + p7 = OpenSSL::PKCS7.new(data) + assert_nil p7.certificates + assert_nil p7.crls + end + def test_graceful_parsing_failure #[ruby-core:43250] contents = File.read(__FILE__) assert_raise(ArgumentError) { OpenSSL::PKCS7.new(contents) }