Skip to content

Fix use-after-free in Context.get_cert_store() - #1549

Open
qianeric-backup wants to merge 2 commits into
pyca:mainfrom
qianeric-backup:get-cert-store-uaf
Open

qianeric-backup wants to merge 2 commits into
pyca:mainfrom
qianeric-backup:get-cert-store-uaf

Conversation

@qianeric-backup

Copy link
Copy Markdown

Context.get_cert_store() returns the X509_STORE * that the context owns, and X509Store.__new__() wraps that borrowed pointer without holding on to the context:

pystore = X509Store.__new__(X509Store)
pystore._store = _lib.SSL_CTX_get_cert_store(self._context)
return pystore

Dropping the last reference to the Context frees the SSL_CTX and with it the store, so the X509Store is left pointing at freed memory. The docstring recommends exactly this call ("can be used to add trusted certificates without using load_verify_locations"), which makes it an easy one to hit:

store = Context(SSLv23_METHOD).get_cert_store()
store.add_cert(cert)   # writes into whatever now occupies that memory

Depending on what the allocator hands out next, add_cert either writes into another live context's store or spins forever on the freed store's lock - measured 20s with no return, against 3us once the context stays alive.

Change

Keep the context alive from the store, the way X509._get_name() already keeps its X509 alive for the X509Name it returns (the only other borrowed handle in the package):

+        # The store is owned by the context.  As long as the X509Store Python
+        # object is alive, keep the Context Python object alive.
+        pystore._owner = self

X509Store gets an _owner attribute defaulted to None for the type checker.

Test

tests/test_ssl.py::TestContext::test_get_cert_store_keeps_context_alive drops every reference to the context and asserts, through a weakref, that it is still alive while the store is. It fails on the unpatched tree.

get_cert_store returns the X509_STORE* owned by the context, but the X509Store
it hands back does not keep the context alive, so dropping the Context frees
the store and leaves the Python object pointing at freed memory. add_cert on
such a store writes into another context's store, or hangs on the freed lock.

Keep the context alive from the store, like X509._get_name keeps its X509
alive for the X509Name it returns.
@qianeric-backup
qianeric-backup marked this pull request as ready for review November 30, 2026 10:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant