I ran the Fortify Static Code Analyzer on the ossec-hids repo and it reported the following Buffer Overflow: Format String
finding for src/analysisd/stats.c:415:
The format string argument to fscanf() at stats.c line 415 does not properly limit the amount of data the function can write, which allows the program to write outside the bounds of allocated memory. This behavior could corrupt data, crash the program, or lead to the execution of malicious code
The line of code in question is like this:
if (fscanf(fp, "%d", &_RWHour[i][j]) <= 0) {
_RWHour
is declared as
static int _RWHour[7][25];
on line 33 of the same file. I believe there is no shadowing of _RWHour
between this declaration on line 33 and its use on line 415, as when I select the declaration on line 33, my IDE (Visual Studio 2019) highlights _RWHour
in 415.
When I look at the cppreference documentation for fscanf
, it says the following:
d matches a decimal integer. The format of the number is the same as expected by
strtol
with the value10
for the base argument
The table I took the quote above from also shows that when no length modifier is used for %d
(as is the case for the fscanf
call in question), the argument type should be signed int*
or unsigned int*
.
My question is this:
Is it possible for the Fortify finding to be a false positive in this instance? Or is it possible to write to memory outside an int
when you pass the address of an int
to fscanf
?
If it is possible to write outside the memory of an int
when using %d
with fscanf
, how can this be safely avoided?
Prevent conversion overflow
fscanf(fp, "%d", &_RWHour[i][j])
is undefined behavior (UB)*1 if the numeric text attempts to convert to a value outside theint
range.A quick fix to prevent UB is to limit the number of characters read with a width:
A more robust solution reads in the text and uses
strtol()
to convert.I recommend creating a helper function to handle reading in the
int
.This level of checking kinda stinks, doesn't it?
i, j
in rangeReview of OP's referenced code looks OK, yet analysis tool may be whining about that.
*1
With UB, it is "possible to write to memory outside an int".