Open
Description
Hello! I analyzed Nginx with Svace static analyzer. It found a potential problem in the code in /src/os/unix/ngx_time.c
Problem Description
The function ngx_timezone_update
contains a potential runtime error when using the localtime
function. Specifically:
-
Potential NULL Pointer Dereference:
- The
localtime
function may returnNULL
if an error occurs or if the input pointer (&s
) is invalid. - In the original code, there is no check for whether
localtime
returnsNULL
. As a result, passing the returned value (t
) directly tostrftime
could lead to a dereference of aNULL
pointer, causing undefined behavior or a program crash.
- The
-
Buffer Size Issue:
- The
buf
array is defined with a size of 4 bytes, but the%H
format instrftime
generates a string like"HH"
(e.g.,"12"
) plus a null terminator (\0
). This requires at least 3 bytes for the string and 1 byte for the null terminator, totaling 4 bytes. However, it is safer to allocate one extra byte to prevent potential overflow issues.
- The
-
Use of
0
Instead ofNULL
:- While
time(0)
works because0
is interpreted as a null pointer in this context, it is less clear and less portable than explicitly usingNULL
. Modern coding standards recommend usingNULL
for better readability and compatibility.
- While
Solution
To address these issues, the following changes were made:
-
Check for
NULL
Return fromlocaltime
:- Added a check after calling
localtime
to ensure that the returned pointer (t
) is notNULL
. - If
t
isNULL
, log an error message usingngx_log_error
and exit the function early to prevent further execution with invalid data.
- Added a check after calling
-
Increase Buffer Size:
- Changed the size of the
buf
array from4
to5
to ensure there is enough space for the formatted string and the null terminator.
- Changed the size of the
-
Replace
0
withNULL
:- Replaced
time(0)
withtime(NULL)
for better clarity and adherence to modern coding standards.
- Replaced
Impact of the Fix
These changes improve the robustness and safety of the code by:
- Preventing potential crashes caused by dereferencing a
NULL
pointer. - Ensuring proper handling of edge cases where
localtime
might fail. - Enhancing code readability and maintainability by adhering to best practices.
This patch ensures that the function behaves correctly even in unexpected scenarios, making it more reliable for production use.
--- ngx_time.c 2025-02-05 14:07:30.000000000 +0300
+++ ngx_time.c.patched 2025-03-07 09:31:55.362193539 +0300
@@ -41,13 +41,19 @@
#elif (NGX_LINUX)
time_t s;
struct tm *t;
- char buf[4];
+ char buf[5];
- s = time(0);
+ s = time(NULL);
t = localtime(&s);
+
+ if (t == NULL) {
+ // Handle error: localtime failed.
+ ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "localtime() failed");
+ return;
+ }
- strftime(buf, 4, "%H", t);
+ strftime(buf, sizeof(buf), "%H", t)
#endif
}
Found by Linux Verification Center (linuxtesting.org) with SVACE.
Metadata
Metadata
Assignees
Labels
No labels