textfile: Fix possible bad memory access in find_key
authorYun-Hao Chung <howardchung@google.com>
Fri, 1 Nov 2024 07:19:39 +0000 (15:19 +0800)
committerWootak Jung <wootak.jung@samsung.com>
Thu, 20 Feb 2025 07:43:24 +0000 (16:43 +0900)
If the searched key is a prefix of the first key in the textfile,
the code will assume it's not the first line which is wrong.

The issue can be reproduced by a fuzzer. More context can be found in
https://issues.oss-fuzz.com/issues/42515619

To reproduce the issue, please kindly follow the instructions in
https://google.github.io/oss-fuzz/advanced-topics/reproducing/

Stack trace:
    #0 0x55e1c450e7ce in find_key /src/bluez/src/textfile.c:133:9
    #1 0x55e1c450e7ce in write_key /src/bluez/src/textfile.c:244:8
    #2 0x55e1c450dc33 in LLVMFuzzerTestOneInput /src/fuzz_textfile.c:61:3
    (...trace in fuzzer)

Signed-off-by: Anuj Jain <anuj01.jain@samsung.com>
src/textfile.c

index a56aa2bd2bedc5d57776ac1959f14fab16b3608c..167368daf7b39d4f9560811772761da5d4d6bee6 100755 (executable)
@@ -126,10 +126,10 @@ static inline char *find_key(char *map, size_t size, const char *key, size_t len
        while (ptrlen > len + 1) {
                int cmp = (icase) ? strncasecmp(ptr, key, len) : strncmp(ptr, key, len);
                if (cmp == 0) {
-                       if (ptr == map && *(ptr + len) == ' ')
-                               return ptr;
-
-                       if ((*(ptr - 1) == '\r' || *(ptr - 1) == '\n') &&
+                       if (ptr == map) {
+                               if (*(ptr + len) == ' ')
+                                       return ptr;
+                       } else if ((*(ptr - 1) == '\r' || *(ptr - 1) == '\n') &&
                                                        *(ptr + len) == ' ')
                                return ptr;
                }