Mail: updated ngx_mail_send() to set handlers on s->quit.

Most notably, this fixes potential issues when a fatal error message is
sent with ngx_mail_send() with s->quit set, but the read handler is not
updated.  Despite s->quit, ngx_mail_send() might not be able to send the
error message immediately, and the read handler might be called on read
events.  In particular, in ngx_mail_auth_http_block_read() and in
ngx_mail_proxy_block_read() this could potentially cause accesses to
freed memory or already closed connections in ngx_handle_read_event()
error handling code paths.

Reported by Evan Hellman,
https://github.com/freenginx/nginx/issues/23
https://github.com/freenginx/nginx/issues/24

Signed-off-by: Vadim Zhestikov <v.zhestikov@f5.com>
Origin: <https://freenginx.org/hg/nginx/rev/87725983f346>
This commit is contained in:
Maxim Dounin 2026-06-20 05:04:41 +03:00 • committed by Roman Arutyunyan
parent e27f5fa84f
commit e505109a3f

View file

@ -14,6 +14,7 @@
static void ngx_mail_proxy_protocol_handler(ngx_event_t *rev);
static void ngx_mail_init_session_handler(ngx_event_t *rev);
static void ngx_mail_init_session(ngx_connection_t *c);
static void ngx_mail_block_read(ngx_event_t *rev);
#if (NGX_MAIL_SSL)
static void ngx_mail_ssl_init_connection(ngx_ssl_t *ssl, ngx_connection_t *c);
@ -413,8 +414,6 @@ ngx_mail_verify_cert(ngx_mail_session_t *s, ngx_connection_t *c)
s->out = cscf->protocol->cert_error;
s->quit = 1;
c->write->handler = ngx_mail_send;
ngx_mail_send(s->connection->write);
return NGX_ERROR;
}
@ -434,8 +433,6 @@ ngx_mail_verify_cert(ngx_mail_session_t *s, ngx_connection_t *c)
s->out = cscf->protocol->no_cert;
s->quit = 1;
c->write->handler = ngx_mail_send;
ngx_mail_send(s->connection->write);
return NGX_ERROR;
}
@ -822,6 +819,11 @@ again:
ngx_add_timer(c->write, cscf->timeout);
if (s->quit) {
c->read->handler = ngx_mail_block_read;
c->write->handler = ngx_mail_send;
}
if (ngx_handle_write_event(c->write, 0) != NGX_OK) {
ngx_mail_close_connection(c);
return;
@ -940,6 +942,17 @@ ngx_mail_session_internal_server_error(ngx_mail_session_t *s)
}
static void
ngx_mail_block_read(ngx_event_t *rev)
{
ngx_log_debug0(NGX_LOG_DEBUG_MAIL, rev->log, 0, "mail block read");
if (ngx_handle_read_event(rev, 0) != NGX_OK) {
ngx_mail_close_connection(rev->data);
}
}
void
ngx_mail_close_connection(ngx_connection_t *c)
{