From d2b8d47741820c9fb134c6731ecb40b21f3085b1 Mon Sep 17 00:00:00 2001
From: Roman Arutyunyan <arut@nginx.com>
Date: Tue, 21 Apr 2026 14:51:41 +0400
Subject: [PATCH] OCSP: resolve cleanup on connection close

Previously, when a client SSL connection was terminated (typically due to a
timeout) while resolving an OCSP responder, the OCSP context was freed, but
the resolve context was not.  This resulted in use-after-free on resolve
completion.

Reported by Leo Lin.
---
 src/event/ngx_event_openssl_stapling.c | 11 +++++++++++
 1 file changed, 11 insertions(+)

--- a/src/event/ngx_event_openssl_stapling.c
+++ b/src/event/ngx_event_openssl_stapling.c
@@ -58,6 +58,7 @@ struct ngx_ssl_ocsp_ctx_s {
 
     ngx_resolver_t              *resolver;
     ngx_msec_t                   resolver_timeout;
+    ngx_resolver_ctx_t          *resolve;
 
     ngx_msec_t                   timeout;
 
@@ -865,6 +866,10 @@ ngx_ssl_ocsp_done(ngx_ssl_ocsp_ctx_t *ct
     ngx_log_debug0(NGX_LOG_DEBUG_EVENT, ctx->log, 0,
                    "ssl ocsp done");
 
+    if (ctx->resolve) {
+        ngx_resolve_name_done(ctx->resolve);
+    }
+
     if (ctx->peer.connection) {
         ngx_close_connection(ctx->peer.connection);
     }
@@ -919,7 +924,10 @@ ngx_ssl_ocsp_request(ngx_ssl_ocsp_ctx_t
         resolve->data = ctx;
         resolve->timeout = ctx->resolver_timeout;
 
+        ctx->resolve = resolve;
+
         if (ngx_resolve_name(resolve) != NGX_OK) {
+            ctx->resolve = NULL;
             ngx_ssl_ocsp_error(ctx);
             return;
         }
@@ -1008,6 +1016,7 @@ ngx_ssl_ocsp_resolve_handler(ngx_resolve
     }
 
     ngx_resolve_name_done(resolve);
+    ctx->resolve = NULL;
 
     ngx_ssl_ocsp_connect(ctx);
     return;
@@ -1015,6 +1024,8 @@ ngx_ssl_ocsp_resolve_handler(ngx_resolve
 failed:
 
     ngx_resolve_name_done(resolve);
+    ctx->resolve = NULL;
+
     ngx_ssl_ocsp_error(ctx);
 }
 
