From a373a141afbf997811de92cb4bce81622ccc2444 Mon Sep 17 00:00:00 2001 From: Thierry Bultel Date: Wed, 22 Aug 2018 08:48:46 +0200 Subject: ctl-lua: Fixed memory corruption fixed a malloc random crash when loading the configuration files. A write of one byte was done outside of an allocated area. Namely, strncat always writes n+1 bytes, thus a best practice is to always calculate n as this: buffer_size-strlen(s)-1 Change-Id: Icb568f324d466fc6eef40c3e251ce6b8a7006d95 Signed-off-by: Thierry Bultel --- ctl-lib/ctl-lua.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/ctl-lib/ctl-lua.c b/ctl-lib/ctl-lua.c index 87e27d0..1a2554c 100644 --- a/ctl-lib/ctl-lua.c +++ b/ctl-lib/ctl-lua.c @@ -1352,15 +1352,16 @@ int LuaConfigLoad(AFB_ApiT apiHandle, const char *prefix) { sep++; } - total_len = base_len + spath_len + token_nb * strlen(LUA_GLOB_PATTERN) + 1; - lua_str = malloc(total_len + 1); + /* allocate 2 extra bytes for the ending single quote + NULL char */ + total_len = base_len + spath_len + token_nb * strlen(LUA_GLOB_PATTERN) + 2; + lua_str = malloc(total_len); strncpy(lua_str, LUA_PATH_VALUE, total_len); for (i = 0; i < token_nb; i++) { sep = strsep(&spath, ":"); - strncat(lua_str, sep, total_len - strlen(lua_str)); - strncat(lua_str, LUA_GLOB_PATTERN, total_len - strlen(lua_str)); + strncat(lua_str, sep, total_len - strlen(lua_str) - 1); + strncat(lua_str, LUA_GLOB_PATTERN, total_len - strlen(lua_str) -1); } - strncat(lua_str, "'", 2); + strncat(lua_str, "'", total_len - strlen(lua_str) - 1); if(luaL_dostring(luaState, lua_str)) printf("Fail change package.path error=%s", lua_tostring(luaState, -1)); -- cgit 1.2.3-korg