From 8378c1ff784a9601966b88f1c5587d50120038c3 Mon Sep 17 00:00:00 2001
From: Alex Gaynor <alex.gaynor@gmail.com>
Date: Mon, 27 Nov 2023 14:35:35 -0500
Subject: Fixed crash when loading a PKCS#7 bundle with no certificates (#9926)

---
 src/cryptography/hazmat/backends/openssl/backend.py | 5 ++++-
 tests/hazmat/primitives/test_pkcs7.py               | 6 ++++++
 2 files changed, 10 insertions(+), 1 deletion(-)

diff --git a/src/cryptography/hazmat/backends/openssl/backend.py b/src/cryptography/hazmat/backends/openssl/backend.py
index f8776b732..45a644cf6 100644
--- a/src/cryptography/hazmat/backends/openssl/backend.py
+++ b/src/cryptography/hazmat/backends/openssl/backend.py
@@ -2454,9 +2454,12 @@ class Backend:
                 _Reasons.UNSUPPORTED_SERIALIZATION,
             )
 
+        certs: list[x509.Certificate] = []
+        if p7.d.sign == self._ffi.NULL:
+            return certs
+
         sk_x509 = p7.d.sign.cert
         num = self._lib.sk_X509_num(sk_x509)
-        certs = []
         for i in range(num):
             x509 = self._lib.sk_X509_value(sk_x509, i)
             self.openssl_assert(x509 != self._ffi.NULL)
diff --git a/tests/hazmat/primitives/test_pkcs7.py b/tests/hazmat/primitives/test_pkcs7.py
index 138bc0f3b..559e1f274 100644
--- a/tests/hazmat/primitives/test_pkcs7.py
+++ b/tests/hazmat/primitives/test_pkcs7.py
@@ -89,6 +89,12 @@ class TestPKCS7Loading:
                 mode="rb",
             )
 
+    def test_load_pkcs7_empty_certificates(self, backend):
+        der = b"\x30\x0B\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x07\x02"
+
+        certificates = pkcs7.load_der_pkcs7_certificates(der)
+        assert certificates == []
+
 
 # We have no public verification API and won't be adding one until we get
 # some requirements from users so this function exists to give us basic
-- 
2.30.2

