helpers: fix fgetval() crash on empty value

getty crashes reading /etc/os-release when a key it looks for has no
value, e.g.:

    VERSION=

initctl crashes the same way reading .initrc, and so does the
modules-load plugin on a bare 'set' or 'set index=', which takes down
PID 1.

The loop skipping separators calls strchr(sep, str[0]), which matches
the NUL terminator at the end of the string.  strsep() then sets str to
NULL and the next iteration dereferences it.  A line with no separator
at all dereferences NULL right away.

Return NULL when there is no separator, and skip separators with
strspn() instead.

Reported-by: Tobias Waldekranz <tobias@waldekranz.com>
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
This commit is contained in:
Joachim Wiberg committed 2026-11-20 17:16:15 +01:00
1 parent 8a5102e714
commit f8c2927672
1 file changed
+3 -12
+3 -12
View File
@@ -123,22 +123,13 @@ static inline char *fgetval(const char *line, const char *key, char *sep)
return NULL;
ptr = strsep(&str, sep);
if (ptr && strcmp(ptr, key)) {
fail:
if (!str || strcmp(ptr, key)) {
free(copy);
return NULL;
}
/*
* Check if we should strip optional separator, e.g.,
* 'foo = bar' => '= bar' should be stripped to 'bar'
*/
while (strchr(sep, str[0])) {
ptr = strsep(&str, sep);
if (!ptr)
goto fail;
}
ptr = str;
/* strip optional separators, e.g., 'foo = bar' => 'bar' */
ptr = str + strspn(str, sep);
if (*ptr == '"' || *ptr == '\'') {
char *end = &ptr[strlen(ptr) - 1];