hlua_applet_http_status() stored the result of luaL_optlstring()
directly in http_ctx->reason. The pointer references Lua-managed
string storage which is only guaranteed valid until the C function
returns to Lua. If the GC runs between applet:set_status(200, str)
and applet:start_response(), the pointer dangles.
hlua_applet_http_send_response() then calls ist(http_ctx->reason)
which does strlen() on freed memory, followed by memcpy into the
HTX status line. The freed-and-reallocated chunk contents are sent
verbatim to the HTTP client.
Trigger:
applet:set_status(200, table.concat({"Reason ", str:rep(50)}))
collectgarbage("collect"); collectgarbage("collect")
applet:start_response()
With heap grooming, adjacent allocation contents (session data, TLS
material from the same thread) leak into the response status line.
Anchor the Lua string in the registry keyed by the http_ctx field
address so it survives until the applet is done with it. The
registry entry is overwritten on each call (handles repeated
set_status) and naturally cleaned up when the lua_State is closed.
---
src/hlua.c | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/src/hlua.c b/src/hlua.c
index c66849c48e8f..d692457a359d 100644
--- a/src/hlua.c
+++ b/src/hlua.c
@@ -6147,6 +6147,17 @@ __LJMP static int hlua_applet_http_status(lua_State *L)
}
http_ctx->status = status;
+ /* Anchor the reason string in the registry so the Lua GC can't
+ * collect it before start_response() reads it back. The previous
+ * direct pointer assignment was a use-after-free if a GC ran
+ * between set_status() and start_response().
+ */
+ lua_pushlightuserdata(L, &http_ctx->reason);
+ if (reason)
+ lua_pushvalue(L, 3);
+ else
+ lua_pushnil(L);
+ lua_settable(L, LUA_REGISTRYINDEX);
http_ctx->reason = reason;
lua_pushboolean(L, 1);
return 1;
--
2.53.0