stream-lua-nginx-module icon indicating copy to clipboard operation
stream-lua-nginx-module copied to clipboard

Potential `NULL` dereference issue in the function ngx_stream_lua_ngx_flush (ngx_stream_lua_output.c)

Open hpkit opened this issue 8 months ago • 0 comments

Hello! I analyzed Nginx modules with Svace static analyzer. It found a potential problem in the code in /stream-lua-nginx-module/src/ngx_stream_lua_output.c

Brief Description

There is a potential NULL dereference issue in the function ngx_stream_lua_ngx_flush. Specifically, the return value of the function ngx_stream_lua_get_req(L) is used without checking for NULL. If ngx_stream_lua_get_req(L) returns NULL, subsequent operations on the pointer r will result in undefined behavior, likely causing a segmentation fault or crash.

The problematic code snippet is as follows:

r = ngx_stream_lua_get_req(L);
ctx = ngx_stream_lua_get_module_ctx(r, ngx_stream_lua_module);

Here, r is dereferenced without verifying that it is not NULL.

Solution

To address this issue, we need to add a check for NULL after calling ngx_stream_lua_get_req(L). If r is NULL, the function should return an appropriate error message using luaL_error.


Patch

Below is the patch to fix the issue:

diff --git a/src/ngx_stream_lua_ngx_flush.c b/src/ngx_stream_lua_ngx_flush.c
--- a/src/ngx_stream_lua_ngx_flush.c
+++ b/src/ngx_stream_lua_ngx_flush.c
@@ -16,6 +16,9 @@ ngx_stream_lua_ngx_flush(lua_State *L)
     r = ngx_stream_lua_get_req(L);
 
+    if (r == NULL) {
+        return luaL_error(L, "no request found");
+    }
     ctx = ngx_stream_lua_get_module_ctx(r, ngx_stream_lua_module);
     if (ctx == NULL) {
         return luaL_error(L, "no request ctx found");

Explanation of the Patch

  1. Check for NULL: After calling ngx_stream_lua_get_req(L), the patch adds a check to ensure that r is not NULL.
    if (r == NULL) {
        return luaL_error(L, "no request found");
    }
    
  2. Error Handling: If r is NULL, the function immediately returns an error message ("no request found") using luaL_error. This prevents further execution and avoids dereferencing a NULL pointer.

Found by Linux Verification Center (linuxtesting.org) with SVACE.

hpkit avatar Mar 25 '25 07:03 hpkit