Check bounds in command line parser

This commit is contained in:
Alex Kotov 2020-12-02 02:54:18 +05:00
parent 058658768f
commit 2707c56c27
Signed by: kotovalexarian
GPG Key ID: 553C0EBBEB5D5F08
2 changed files with 24 additions and 2 deletions

View File

@ -44,7 +44,15 @@ kernaux_bool kernaux_cmdline_parse(
if ((cur == ' ' || cur == '\0') && prev != ' ') {
const unsigned size = index - start + 1;
// TODO: check size
if (*argc >= argv_count_max) {
kernaux_strncpy(error_msg, "too many args", 13);
goto fail;
}
if (size > arg_size_max) {
kernaux_strncpy(error_msg, "arg too long", 12);
goto fail;
}
argv[(*argc)++] = buffer;
kernaux_strncpy(buffer, &cmdline[start], size - 1);
@ -61,4 +69,15 @@ kernaux_bool kernaux_cmdline_parse(
}
return KERNAUX_TRUE;
fail:
*argc = 0;
for (unsigned int index = 0; index < argv_count_max; ++index) {
argv[index] = KERNAUX_NULL;
}
kernaux_memset(buffer, '\0', argv_count_max * arg_size_max);
return KERNAUX_FALSE;
}

View File

@ -41,6 +41,9 @@ int main()
test(" foo bar ", 0, 0, true, "", 2, argv_foo_bar);
test("foo bar car", 0, 0, true, "", 3, argv_foo_bar_car);
test("foo bar car", 2, 0, false, "too many args", 0, argv0);
test("foo bar car", 0, 2, false, "arg too long", 0, argv0);
return 0;
}
@ -86,7 +89,7 @@ void test(
assert(strcmp(argv[index], expected_argv[index]) == 0);
}
for (unsigned int index = argc; index < ARGV_COUNT_MAX; ++index) {
for (unsigned int index = argc; index < argv_count_max; ++index) {
assert(argv[index] == KERNAUX_NULL);
}
}