From 80bf917897bbde325748f0255a34fa5713150ec6 Mon Sep 17 00:00:00 2001 From: Kazuki Yamaguchi Date: Mon, 9 Nov 2026 18:16:50 +0900 Subject: [PATCH 1/2] x509store: do not suppress exceptions in verify_callback Currently, verify_callback has no common place to store the jump tag type when an exception is raised or the thread is interrupted, so it suppresses the jump and emits a warning instead. Use Fiber-local storage for the callback state. Wrap all callers that may invoke verify_callback with ossl_cb_state_{begin,end}() so that the suspended jump can be resumed afterward. [ Known limitations: A user can freeze the Thread object to make it suppress exceptions again. A user can store a random Fixnum in Thread.current[:__ossl_cb_state__] to break ruby/openssl. I consider these out of scope at this time, because there doesn't seem to be a better alternative. ] --- ext/openssl/ossl.c | 46 +++++++++++++++++++++++++++++++ ext/openssl/ossl.h | 8 ++++++ ext/openssl/ossl_ocsp.c | 16 +++++++++-- ext/openssl/ossl_pkcs7.c | 7 +++++ ext/openssl/ossl_ssl.c | 17 ++++++++---- ext/openssl/ossl_ts.c | 6 ++++ ext/openssl/ossl_x509.h | 2 ++ ext/openssl/ossl_x509store.c | 50 +++++++++++++++++++--------------- test/openssl/test_ocsp.rb | 14 ++++++++++ test/openssl/test_pkcs7.rb | 12 ++++++++ test/openssl/test_ssl.rb | 15 ++++++---- test/openssl/test_ts.rb | 7 +++++ test/openssl/test_x509store.rb | 16 +++++++---- test/openssl/utils.rb | 10 +++++-- 14 files changed, 184 insertions(+), 42 deletions(-) diff --git a/ext/openssl/ossl.c b/ext/openssl/ossl.c index 578d0051b..64c11eed2 100644 --- a/ext/openssl/ossl.c +++ b/ext/openssl/ossl.c @@ -145,6 +145,51 @@ ossl_bin2hex(const unsigned char *in, char *out, size_t inlen) } } +static ID id_cb_state; + +int +ossl_cb_state_get(void) +{ + VALUE val = rb_thread_local_aref(rb_thread_current(), id_cb_state); + return FIXNUM_P(val) ? FIX2INT(val) : 0; +} + +static VALUE +cb_state_set_i(VALUE vstate) +{ + rb_thread_local_aset(rb_thread_current(), id_cb_state, vstate); + return Qnil; +} + +void +ossl_cb_state_set(int state) +{ + int s; + rb_protect(cb_state_set_i, state ? INT2FIX(state) : Qnil, &s); + if (s) { + /* Thread frozen or malloc failure? As a last resort */ + rb_set_errinfo(Qnil); + } +} + +void +ossl_cb_state_begin(void) +{ + if (ossl_cb_state_get()) { + rb_raise(rb_eRuntimeError, + "BUG: ossl_cb_state_begin() called while jump is pending"); + } +} + +int +ossl_cb_state_end(void) +{ + int state = ossl_cb_state_get(); + if (state) + ossl_cb_state_set(0); + return state; +} + /* * our default PEM callback */ @@ -1155,6 +1200,7 @@ Init_openssl(void) */ ossl_s_to_der = rb_intern("to_der"); id_i_errors = rb_intern("@errors"); + id_cb_state = rb_intern("__ossl_cb_state__"); /* * Init components diff --git a/ext/openssl/ossl.h b/ext/openssl/ossl.h index 7762ad237..69e334f7a 100644 --- a/ext/openssl/ossl.h +++ b/ext/openssl/ossl.h @@ -155,6 +155,14 @@ do{\ */ void ossl_bin2hex(const unsigned char *in, char *out, size_t len); +/* + * Use Fiber-local storage for rb_protect() states. This is fragile! + */ +void ossl_cb_state_begin(void); +int ossl_cb_state_end(void); +int ossl_cb_state_get(void); +void ossl_cb_state_set(int state); + /* * Our default PEM callback */ diff --git a/ext/openssl/ossl_ocsp.c b/ext/openssl/ossl_ocsp.c index 476c35742..4266b2e64 100644 --- a/ext/openssl/ossl_ocsp.c +++ b/ext/openssl/ossl_ocsp.c @@ -378,15 +378,21 @@ ossl_ocspreq_verify(int argc, VALUE *argv, VALUE self) OCSP_REQUEST *req; STACK_OF(X509) *x509s; X509_STORE *x509st; - int flg, result; + int flg, result, state; rb_scan_args(argc, argv, "21", &certs, &store, &flags); GetOCSPReq(self, req); x509st = GetX509StorePtr(store); flg = NIL_P(flags) ? 0 : NUM2INT(flags); x509s = ossl_x509_ary2sk(certs); + ossl_cb_state_begin(); result = OCSP_request_verify(req, x509s, x509st, flg); + state = ossl_cb_state_end(); sk_X509_pop_free(x509s, X509_free); + if (state) { + ossl_clear_error(); + rb_jump_tag(state); + } if (result <= 0) ossl_clear_error(); @@ -991,15 +997,21 @@ ossl_ocspbres_verify(int argc, VALUE *argv, VALUE self) OCSP_BASICRESP *bs; STACK_OF(X509) *x509s; X509_STORE *x509st; - int flg, result; + int flg, result, state; rb_scan_args(argc, argv, "21", &certs, &store, &flags); GetOCSPBasicRes(self, bs); x509st = GetX509StorePtr(store); flg = NIL_P(flags) ? 0 : NUM2INT(flags); x509s = ossl_x509_ary2sk(certs); + ossl_cb_state_begin(); result = OCSP_basic_verify(bs, x509s, x509st, flg); + state = ossl_cb_state_end(); sk_X509_pop_free(x509s, X509_free); + if (state) { + ossl_clear_error(); + rb_jump_tag(state); + } if (result <= 0) ossl_clear_error(); diff --git a/ext/openssl/ossl_pkcs7.c b/ext/openssl/ossl_pkcs7.c index e17a49410..b3c8baa5d 100644 --- a/ext/openssl/ossl_pkcs7.c +++ b/ext/openssl/ossl_pkcs7.c @@ -777,9 +777,16 @@ ossl_pkcs7_verify(int argc, VALUE *argv, VALUE self) sk_X509_pop_free(x509s, X509_free); ossl_raise(ePKCS7Error, NULL); } + ossl_cb_state_begin(); ok = PKCS7_verify(p7, x509s, x509st, in, out, flg); + status = ossl_cb_state_end(); BIO_free(in); sk_X509_pop_free(x509s, X509_free); + if (status) { + BIO_free(out); + ossl_clear_error(); + rb_jump_tag(status); + } data = ossl_membio2str(out); ossl_pkcs7_set_data(self, data); if (ok != 1) { diff --git a/ext/openssl/ossl_ssl.c b/ext/openssl/ossl_ssl.c index 848fd9fc6..d6dca599d 100644 --- a/ext/openssl/ossl_ssl.c +++ b/ext/openssl/ossl_ssl.c @@ -215,7 +215,7 @@ ossl_ssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) { VALUE cb, ssl_obj, sslctx_obj, verify_hostname, ret; SSL *ssl; - int status; + int state, ok; ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); ssl_obj = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx); @@ -225,9 +225,9 @@ ossl_ssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) if (preverify_ok && RTEST(verify_hostname) && !SSL_is_server(ssl) && !X509_STORE_CTX_get_error_depth(ctx)) { - ret = rb_protect(call_verify_certificate_identity, (VALUE)ctx, &status); - if (status) { - rb_ivar_set(ssl_obj, ID_callback_state, INT2NUM(status)); + ret = rb_protect(call_verify_certificate_identity, (VALUE)ctx, &state); + if (state) { + rb_ivar_set(ssl_obj, ID_callback_state, INT2NUM(state)); return 0; } if (ret != Qtrue) { @@ -236,7 +236,14 @@ ossl_ssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) } } - return ossl_verify_cb_call(cb, preverify_ok, ctx); + ossl_cb_state_begin(); + ok = ossl_verify_cb_call(cb, preverify_ok, ctx); + state = ossl_cb_state_end(); + if (state) { + rb_ivar_set(ssl_obj, ID_callback_state, INT2NUM(state)); + return 0; + } + return ok; } static VALUE diff --git a/ext/openssl/ossl_ts.c b/ext/openssl/ossl_ts.c index c95f47ea8..f07b3e518 100644 --- a/ext/openssl/ossl_ts.c +++ b/ext/openssl/ossl_ts.c @@ -808,9 +808,15 @@ ossl_ts_resp_verify(int argc, VALUE *argv, VALUE self) #endif TS_VERIFY_CTX_add_flags(ctx, TS_VFY_SIGNATURE); + ossl_cb_state_begin(); ok = TS_RESP_verify_response(ctx, resp); + status = ossl_cb_state_end(); TS_VERIFY_CTX_free(ctx); + if (status) { + ossl_clear_error(); + rb_jump_tag(status); + } if (!ok) ossl_raise(eTimestampError, "TS_RESP_verify_response"); diff --git a/ext/openssl/ossl_x509.h b/ext/openssl/ossl_x509.h index 71932ef1a..3bb952c25 100644 --- a/ext/openssl/ossl_x509.h +++ b/ext/openssl/ossl_x509.h @@ -90,6 +90,8 @@ void Init_ossl_x509store(void); /* * Calls the verify callback Proc (the first parameter) with given pre-verify * result and the X509_STORE_CTX. + * + * Assumes ossl_cb_state_*() is active. */ int ossl_verify_cb_call(VALUE, int, X509_STORE_CTX *); diff --git a/ext/openssl/ossl_x509store.c b/ext/openssl/ossl_x509store.c index 0352ef1eb..430bf010e 100644 --- a/ext/openssl/ossl_x509store.c +++ b/ext/openssl/ossl_x509store.c @@ -56,37 +56,34 @@ ossl_verify_cb_call(VALUE proc, int ok, X509_STORE_CTX *ctx) struct ossl_verify_cb_args args; int state; + if (ossl_cb_state_get()) + goto err; if (NIL_P(proc)) return ok; - ret = Qfalse; rctx = rb_protect(ossl_x509stctx_new_i, (VALUE)ctx, &state); if (state) { - rb_set_errinfo(Qnil); - rb_warn("StoreContext initialization failure"); + ossl_cb_state_set(state); + goto err; } - else { - args.proc = proc; - args.preverify_ok = ok ? Qtrue : Qfalse; - args.store_ctx = rctx; - ret = rb_protect(call_verify_cb_proc, (VALUE)&args, &state); - RTYPEDDATA_DATA(rctx) = NULL; - if (state) { - rb_set_errinfo(Qnil); - rb_warn("exception in verify_callback is ignored"); - } + args.proc = proc; + args.preverify_ok = ok ? Qtrue : Qfalse; + args.store_ctx = rctx; + ret = rb_protect(call_verify_cb_proc, (VALUE)&args, &state); + RTYPEDDATA_DATA(rctx) = NULL; + if (state) { + ossl_cb_state_set(state); + goto err; } if (ret == Qtrue) { X509_STORE_CTX_set_error(ctx, X509_V_OK); - ok = 1; - } - else { - if (X509_STORE_CTX_get_error(ctx) == X509_V_OK) - X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REJECTED); - ok = 0; + return 1; } - return ok; + err: + if (X509_STORE_CTX_get_error(ctx) == X509_V_OK) + X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REJECTED); + return 0; } /* @@ -677,6 +674,7 @@ static VALUE ossl_x509stctx_verify(VALUE self) { X509_STORE_CTX *ctx; + int ret, state; GetX509StCtx(self, ctx); VALUE cb = rb_iv_get(self, "@verify_callback"); @@ -684,7 +682,14 @@ ossl_x509stctx_verify(VALUE self) ossl_raise(eX509StoreError, "X509_STORE_CTX_set_ex_data"); RB_OBJ_WRITTEN(self, Qundef, cb); - switch (X509_verify_cert(ctx)) { + ossl_cb_state_begin(); + ret = X509_verify_cert(ctx); + state = ossl_cb_state_end(); + if (state) { + ossl_clear_error(); + rb_jump_tag(state); + } + switch (ret) { case 1: return Qtrue; case 0: @@ -1034,7 +1039,8 @@ Init_ossl_x509store(void) * The callback can use StoreContext#error= to change the error code as * needed. The callback must return either true or false. * - * NOTE: any exception raised within the callback will be ignored. + * Exceptions raised within the callback propagate to the caller of the + * verification method. * * See also the man page X509_STORE_CTX_set_verify_cb(3). */ diff --git a/test/openssl/test_ocsp.rb b/test/openssl/test_ocsp.rb index c43ff5cb5..44dbe6c83 100644 --- a/test/openssl/test_ocsp.rb +++ b/test/openssl/test_ocsp.rb @@ -116,6 +116,13 @@ def test_request_sign_verify req.sign(@cert, @cert_key, []) assert_equal true, req.verify([], store) + # Exceptions in verify_callback are re-raised + s = OpenSSL::X509::Store.new.tap { |s| + s.add_cert(@ca_cert) + s.verify_callback = proc { raise "verify_callback" } + } + assert_raise(RuntimeError) { req.verify([], s) } + # without signer cert req = OpenSSL::OCSP::Request.new.add_certid(cid) req.sign(@cert, @cert_key, nil) @@ -195,6 +202,13 @@ def test_basic_response_sign_verify bres.sign(@ca_cert, @ca_key, [], 0, "SHA256") assert_equal true, bres.verify([], store) + # Exceptions in verify_callback are re-raised + s = OpenSSL::X509::Store.new.tap { |s| + s.add_cert(@ca_cert) + s.verify_callback = proc { raise "verify_callback" } + } + assert_raise(RuntimeError) { bres.verify([], s) } + # signed by OCSP signer bres = OpenSSL::OCSP::BasicResponse.new cid = OpenSSL::OCSP::CertificateId.new(@cert2, @cert) diff --git a/test/openssl/test_pkcs7.rb b/test/openssl/test_pkcs7.rb index c677d8223..8beae9662 100644 --- a/test/openssl/test_pkcs7.rb +++ b/test/openssl/test_pkcs7.rb @@ -64,6 +64,18 @@ def test_signed assert_false(p7.verify([@ca_cert], OpenSSL::X509::Store.new)) end + def test_signed_verify_callback + data = "aaaaa\r\nbbbbb\r\nccccc\r\n" + tmp = OpenSSL::PKCS7.sign(@ee1_cert, @ee1_key, data) + + p7 = OpenSSL::PKCS7.new(tmp) + store = OpenSSL::X509::Store.new + store.verify_callback = proc { raise "verify_callback" } + assert_raise_with_message(RuntimeError, "verify_callback") { + p7.verify([], store) + } + end + def test_signed_flags store = OpenSSL::X509::Store.new store.add_cert(@ca_cert) diff --git a/test/openssl/test_ssl.rb b/test/openssl/test_ssl.rb index db095e178..87a491122 100644 --- a/test/openssl/test_ssl.rb +++ b/test/openssl/test_ssl.rb @@ -748,22 +748,25 @@ def test_verify_result } end - def test_exception_in_verify_callback_is_ignored + def test_exception_in_verify_callback start_server(ignore_listener_error: true) { |port| sock = TCPSocket.new("127.0.0.1", port) ctx = OpenSSL::SSL::SSLContext.new ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER + ctx.cert_store = OpenSSL::X509::Store.new.add_cert(@ca_cert) + called = [] ctx.verify_callback = Proc.new do |preverify_ok, store_ctx| store_ctx.error = OpenSSL::X509::V_OK - raise RuntimeError + called << store_ctx.current_cert + raise "in verify_callback" end ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx) ssl.sync_close = true begin - EnvUtil.suppress_warning do - # SSLError, not RuntimeError - assert_raise(OpenSSL::SSL::SSLError) { ssl.connect } - end + assert_raise_with_message(RuntimeError, "in verify_callback") { + ssl.connect + } + assert_equal([@ca_cert], called) assert_equal(OpenSSL::X509::V_ERR_CERT_REJECTED, ssl.verify_result) ensure ssl.close diff --git a/test/openssl/test_ts.rb b/test/openssl/test_ts.rb index 69780a657..4cc7e3d6d 100644 --- a/test/openssl/test_ts.rb +++ b/test/openssl/test_ts.rb @@ -407,6 +407,13 @@ def test_verify_ee_intermediate_type_error assert_raise(TypeError) { ts.verify(req, [ca_cert], 123) } end + def test_verify_with_verify_callback + ts, req = timestamp_ee + store = ca_store + store.verify_callback = proc { raise "verify callback" } + assert_raise(RuntimeError) { ts.verify(req, store) } + end + def test_verify_ee_def_policy req = OpenSSL::Timestamp::Request.new req.algorithm = "SHA1" diff --git a/test/openssl/test_x509store.rb b/test/openssl/test_x509store.rb index 7132af9f9..b2559b705 100644 --- a/test/openssl/test_x509store.rb +++ b/test/openssl/test_x509store.rb @@ -150,17 +150,23 @@ def test_verify_callback assert_equal(false, store.verify(ee1_cert, [ca2_cert])) assert_equal(OpenSSL::X509::V_ERR_APPLICATION_VERIFICATION, store.error) - # Exception raised by verify_callback is currently suppressed, and is - # treated as a non-truthy return (with warning) + # Exceptions raised in verify_callback are re-raised store = OpenSSL::X509::Store.new store.verify_callback = -> (preverify_ok, sctx) { - raise "suppressed" + raise "in verify_callback" } store.add_cert(ca1_cert) - assert_warning(/exception in verify_callback/) { - assert_equal(false, store.verify(ee1_cert, [ca2_cert])) + assert_raise_with_message(RuntimeError, "in verify_callback") { + store.verify(ee1_cert, [ca2_cert]) } + # verify_callback is nested + ret = store.verify(ca1_cert) do |preverify_ok, sctx| + assert_raise(RuntimeError) { store.verify(ca1_cert) } + preverify_ok + end + assert_true(ret) + # The block given to X509::Store#verify replaces it called = nil store = OpenSSL::X509::Store.new diff --git a/test/openssl/utils.rb b/test/openssl/utils.rb index 7dd3a719d..f18ce963a 100644 --- a/test/openssl/utils.rb +++ b/test/openssl/utils.rb @@ -136,8 +136,12 @@ def teardown if ENV["OSSL_GC_STRESS"] == "1" GC.stress = false end - # OpenSSL error stack must be empty - assert_equal([], OpenSSL.errors) + assert_clean_thread + end + + def assert_clean_thread + assert_equal([], OpenSSL.errors, "OpenSSL error queue leak") + assert_nil(Thread.current[:__ossl_cb_state__], "ossl_cb_state leak") end # Omit the tests in FIPS. @@ -223,6 +227,7 @@ def start_server_proc(server_proc, &block) Thread.current.report_on_exception = false server_proc.call(sock) + assert_clean_thread end threads << th end @@ -234,6 +239,7 @@ def start_server_proc(server_proc, &block) Thread.current.report_on_exception = false block.call(port) + assert_clean_thread ensure # Stop accepting new connection stop_pipe_w.close From d59a3a85083fde62abd7fb8e48c072a194f282da Mon Sep 17 00:00:00 2001 From: Kazuki Yamaguchi Date: Tue, 10 Nov 2026 03:19:17 +0900 Subject: [PATCH 2/2] ossl.c: fix possible exceptions in ossl_clear_error() ossl_clear_error() is often used when we are about to resume a jump with rb_jump_tag(). It should not raise an exception or clobber the current errinfo. --- ext/openssl/ossl.c | 90 +++++++++++++++++++++++++++++++--------------- ext/openssl/ossl.h | 5 +++ 2 files changed, 67 insertions(+), 28 deletions(-) diff --git a/ext/openssl/ossl.c b/ext/openssl/ossl.c index 64c11eed2..cceac44ca 100644 --- a/ext/openssl/ossl.c +++ b/ext/openssl/ossl.c @@ -190,6 +190,42 @@ ossl_cb_state_end(void) return state; } +struct suppress_args { + VALUE (*func)(VALUE args); + VALUE args; +}; + +static VALUE +do_nothing(VALUE unused) +{ + return Qnil; +} + +static VALUE +suppress_i(VALUE args_) +{ + struct suppress_args *p = (struct suppress_args *)args_; + int state; + rb_set_errinfo(Qnil); + rb_protect(p->func, p->args, &state); + /* Ignoring result and exception, if any */ + return Qnil; +} + +void +ossl_suppress(VALUE (*func)(VALUE args), VALUE args) +{ + struct suppress_args p = { func, args }; + if (ossl_cb_state_get()) { + int state = ossl_cb_state_end(); + rb_ensure(do_nothing, Qnil, suppress_i, (VALUE)&p); + ossl_cb_state_begin(); + ossl_cb_state_set(state); + return; + } + rb_ensure(do_nothing, Qnil, suppress_i, (VALUE)&p); +} + /* * our default PEM callback */ @@ -320,7 +356,7 @@ ossl_to_der_if_possible(VALUE obj) */ static ID id_i_errors; -static void collect_errors_into(VALUE ary); +static VALUE collect_errors_into(VALUE ary); VALUE ossl_make_error(VALUE exc, VALUE str) @@ -371,46 +407,44 @@ ossl_raise(VALUE exc, const char *fmt, ...) rb_exc_raise(ossl_make_error(exc, err)); } -static void +static VALUE collect_errors_into(VALUE ary) { - if (dOSSL == Qtrue || !NIL_P(ary)) { - unsigned long e; - const char *file, *data, *func, *lib, *reason; - int line, flags; + unsigned long e; + const char *file, *data, *func, *lib, *reason; + int line, flags; #ifdef HAVE_ERR_GET_ERROR_ALL - while ((e = ERR_get_error_all(&file, &line, &func, &data, &flags))) { + while ((e = ERR_get_error_all(&file, &line, &func, &data, &flags))) { #else - while ((e = ERR_get_error_line_data(&file, &line, &data, &flags))) { - func = ERR_func_error_string(e); + while ((e = ERR_get_error_line_data(&file, &line, &data, &flags))) { + func = ERR_func_error_string(e); #endif - lib = ERR_lib_error_string(e); - reason = ERR_reason_error_string(e); - - VALUE str = rb_sprintf("error:%08lX:%s:%s:%s", e, lib ? lib : "", - func ? func : "", reason ? reason : ""); - if (flags & ERR_TXT_STRING) { - if (!data) - data = "(null)"; - rb_str_catf(str, " (%s)", data); - } - - if (dOSSL == Qtrue) - rb_warn("error on stack: %"PRIsVALUE, str); - if (!NIL_P(ary)) - rb_ary_push(ary, str); + lib = ERR_lib_error_string(e); + reason = ERR_reason_error_string(e); + + VALUE str = rb_sprintf("error:%08lX:%s:%s:%s", e, lib ? lib : "", + func ? func : "", reason ? reason : ""); + if (flags & ERR_TXT_STRING) { + if (!data) + data = "(null)"; + rb_str_catf(str, " (%s)", data); } + + if (dOSSL == Qtrue) + rb_warn("error on stack: %"PRIsVALUE, str); + if (!NIL_P(ary)) + rb_ary_push(ary, str); } - else { - ERR_clear_error(); - } + return Qnil; } void ossl_clear_error(void) { - collect_errors_into(Qnil); + if (dOSSL == Qtrue) + ossl_suppress(collect_errors_into, Qnil); + ERR_clear_error(); } /* diff --git a/ext/openssl/ossl.h b/ext/openssl/ossl.h index 69e334f7a..671c0bbb5 100644 --- a/ext/openssl/ossl.h +++ b/ext/openssl/ossl.h @@ -162,6 +162,11 @@ void ossl_cb_state_begin(void); int ossl_cb_state_end(void); int ossl_cb_state_get(void); void ossl_cb_state_set(int state); +/* + * Equivalent to rb_protect(func, args, NULL) except that this restores + * errinfo to the state before the call. + */ +void ossl_suppress(VALUE (*func)(VALUE args), VALUE args); /* * Our default PEM callback