Skip to content

Commit

Permalink
Prevent use-after-free when adding subcommand aliases
Browse files Browse the repository at this point in the history
The add_subcommand_alias routine contained a use-after-free bug
which was discovered by valgrind. I actually used the AddressSanitizer
to track down this bug - it is much more useful.

The actual bug is that old_sc saved a reference to the old array
that was realloc-ed and then the function pointer from out the now
free'ed array was copied over.

Fix this by storing the function pointer into a temporary, then
realloc-ing the array and then copy the temporary value into the
new array entry.

Github-Issue: #122
Reported-By: Mikael Fangel (https://github.com/MikaelFangel)
  • Loading branch information
herrhotzenplotz committed Nov 27, 2023
1 parent 35a058d commit 9f60585
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/cmd/gcli.c
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,7 @@ add_subcommand_alias(char const *alias_name, char const *alias_for)
char *docstring;
struct subcommand const *old_sc;
struct subcommand *new_sc;
int (*old_fn)(int, char **);

old_sc = find_subcommand(alias_for, NULL);
if (old_sc == NULL) {
Expand All @@ -277,14 +278,15 @@ add_subcommand_alias(char const *alias_name, char const *alias_for)
exit(EXIT_FAILURE);
}

old_fn = old_sc->fn;
docstring = sn_asprintf("Alias for %s", alias_for);
subcommands = realloc(subcommands, (subcommands_size + 1) * sizeof(*subcommands));

/* Copy in data */
new_sc = &subcommands[subcommands_size++];

new_sc->cmd_name = alias_name;
new_sc->fn = old_sc->fn;
new_sc->fn = old_fn;
new_sc->docstring = docstring;
}

Expand Down

0 comments on commit 9f60585

Please sign in to comment.