security: add missing NULL checks after strdup/strndup in pw_split_strv

Memory Safety: Medium

In pw_split_strv(), the return values of strndup() and strdup() were
passed directly to pw_array_add_ptr() without checking for NULL. If
memory allocation fails, NULL pointers would be stored in the string
array and later dereferenced by callers iterating the result.

The return value of pw_array_add_ptr() was also not checked, which
could lead to silently dropped strings.

Fix by checking both allocation and array insertion return values,
and properly cleaning up all previously allocated strings on failure.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Wim Taymans 2026-04-28 13:23:42 +02:00
parent ec04c4bf9a
commit e474303991

View file

@ -68,20 +68,37 @@ char **pw_split_strv(const char *str, const char *delimiter, int max_tokens, int
s = pw_split_walk(str, delimiter, &len, &state);
while (s && n + 1 < max_tokens) {
pw_array_add_ptr(&arr, strndup(s, len));
char *t = strndup(s, len);
if (t == NULL || pw_array_add_ptr(&arr, t) < 0) {
free(t);
goto error;
}
s = pw_split_walk(str, delimiter, &len, &state);
n++;
}
if (s) {
pw_array_add_ptr(&arr, strdup(s));
char *t = strdup(s);
if (t == NULL || pw_array_add_ptr(&arr, t) < 0) {
free(t);
goto error;
}
n++;
}
pw_array_add_ptr(&arr, NULL);
if (pw_array_add_ptr(&arr, NULL) < 0)
goto error;
if (n_tokens != NULL)
*n_tokens = n;
return arr.data;
error:
{
char **p;
pw_array_for_each(p, &arr) free(*p);
pw_array_clear(&arr);
return NULL;
}
}
/** Split a string in-place based on delimiters