iniparser: prevent signed integer underflow in line length calculation
Subsystems (2)
PATCH 1/1 iniparser: prevent signed integer underflow in line length calculation
In iniparser_load_file(), the code computed:
len = (int)strlen(line) - 1;
If the input line was empty (e.g. started with a null byte), strlen() returned 0, leading to len = -1. This caused:
- A signed integer underflow (detected by static analyzers)
- Potential out-of-bounds access when checking line[len]
Fix by:
- Using size_t for strlen() result
- Checking for zero length before subtraction
- Computing len as (int)(line_len - 1) only when safe
--- lib/libiniparser.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
lib/libiniparser.c +7 -1
@@ -697,7 +697,13 @@ dictionary * iniparser_load_file(FILE * in, const char * ininame)while (fgets (line+last,ASCIILINESZ -last, in)!=NULL ) { lineno++ ; - len = (int )strlen (line)-1 ; +size_t line_len =strlen (line); +if (line_len ==0 ) { +memset (line,0 ,ASCIILINESZ ); + last =0 ; +continue ; + } + len = (int )(line_len -1 );if (len<=0 )continue ;/* Safety check against buffer overflows */
Signature · 6 lines
2.39.2 ______________________________________________________ Linux MTD discussion mailing list http://lists.infradead.org/mailman/listinfo/linux-mtd/
Hi,
according to your description, this was found by static analysis? I'm a little confused how it should be possible to trigger this bug:
Quoted 4 lines · Anton Moryakov
while (fgets(line+last, ASCIILINESZ-last, in)!=NULL) { lineno++ ;- len = (int)strlen(line)-1;
The return value of strlen is cast to an int, which AFAIK has higher precedence than the following subtraction of 1 (also, by default, an integer).
The variable len is declared as an int at the beginning of the function, it is signed and *can* be negative, there is no underflow here.
Directly after the code you inserted is this:
Quoted 2 lines
if (len<=0)
continue;which should catch that exact case you are trying to fix, no?
Greetings,
David
______________________________________________________
Linux MTD discussion mailing list
http://lists.infradead.org/mailman/listinfo/linux-mtd/