Skip to content

x509store: keep reference to Store in StoreContext - #1170

Merged
rhenium merged 1 commit into
ruby:masterfrom
hyc-alt:fix/x509-store-context-gc-store
Nov 30, 2026
Merged

rhenium merged 1 commit into
ruby:masterfrom
hyc-alt:fix/x509-store-context-gc-store

Conversation

@hyc-alt

@hyc-alt hyc-alt commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Summary

OpenSSL::X509::StoreContext#initialize passes the X509_STORE * from the given OpenSSL::X509::Store to X509_STORE_CTX_init(), which stores a raw pointer without incrementing the X509_STORE reference count. Because StoreContext did not retain a Ruby reference to the Store object, garbage collection of Store while StoreContext is still alive freed the underlying X509_STORE, causing a use-after-free on subsequent calls such as StoreContext#verify.

Fix

  • Store a hidden internal instance variable (id_store = rb_intern_const("store")) referencing store on StoreContext after X509_STORE_CTX_init() succeeds in ext/openssl/ossl_x509store.c, matching the existing hidden-ivar retention pattern used elsewhere in ruby/openssl (e.g., id_original_context in ossl_ssl.c).
  • Keeping the Ruby OpenSSL::X509::Store object alive ensures both the underlying X509_STORE and its dmark/dcompact hooks remain valid for the lifetime of the StoreContext, without exposing a new visible instance variable on StoreContext.

Verification

  • Added regression test test_store_context_gc in test/openssl/test_x509store.rb:
    • Before patch (master 1ea17b55): test_store_context_gc fails (OpenSSL::X509::Store is collected after GC.start), and running ctx.verify under MallocScribble=1 terminates with SIGSEGV.
    • After patch: compiled cleanly with RUBY_OPENSSL_EXTCFLAGS=-Werror; test/openssl/test_x509store.rb (13 tests, 110 assertions, including under MallocScribble=1) and test/openssl/test_x509*.rb (91 tests, 683 assertions) pass.

X509_STORE_CTX_init() stores a raw pointer to the underlying X509_STORE
without incrementing its reference count. If the Ruby OpenSSL::X509::Store
object passed to OpenSSL::X509::StoreContext.new is garbage collected
while the StoreContext is still live, subsequent operations such as
StoreContext#verify dereference the freed X509_STORE.

Store a hidden internal instance variable reference to the Store object
on the StoreContext after X509_STORE_CTX_init() succeeds so that the
Store (and its underlying X509_STORE) remains alive for the lifetime of
the StoreContext.

@rhenium rhenium left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@rhenium
rhenium merged commit 492edb1 into ruby:master Nov 30, 2026
49 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants