From 19ff18b806c0051ea2dffdd2c6eae61f2a04e761 Mon Sep 17 00:00:00 2001 From: Matthew Wild Date: Mon, 8 Jul 2024 11:18:31 +0100 Subject: [PATCH] Fix use-after-free in error message construction Calling ERR_clear_error() releases the buffers that hold the path/filename, so we need to push those to Lua (which will copy them) before they are released. The problem can be verified with valgrind, or indeed just by running it on my machine which shows random memory contents prefixed to the error message string. --- src/openssl.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/openssl.c b/src/openssl.c index db64d03..34cbedf 100644 --- a/src/openssl.c +++ b/src/openssl.c @@ -1487,15 +1487,17 @@ static const char *auxL_pusherror(lua_State *L, int error, const char *fun) { file = path; } - ERR_clear_error(); - ERR_error_string_n(code, txt, sizeof txt); if (fun) { - return lua_pushfstring(L, "%s: %s:%d:%s", fun, file, line, txt); + lua_pushfstring(L, "%s: %s:%d:%s", fun, file, line, txt); } else { - return lua_pushfstring(L, "%s:%d:%s", file, line, txt); + lua_pushfstring(L, "%s:%d:%s", file, line, txt); } + + ERR_clear_error(); + + return 1; #if HAVE_DLADDR } else if (error == auxL_EDYLD) { const char *const fmt = (fun)? "%s: %s" : "%.0s%s";