Skip to content

Commit

Permalink
Fix use-after-free of pointer after realloc(3)
Browse files Browse the repository at this point in the history
We can't use a pointer that was input to realloc(3), nor any pointers
that point to reallocated memory, without making sure that the memory
wasn't moved.  If we do, the Behavior is Undefined.

Signed-off-by: Alejandro Colomar <alx@kernel.org>
  • Loading branch information
alejandro-colomar committed Feb 23, 2023
1 parent 5282a36 commit edf3a6a
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions libmisc/env.c
Original file line number Diff line number Diff line change
Expand Up @@ -128,12 +128,14 @@ void addenv (const char *string, /*@null@*/const char *value)
*/

if ((newenvc & (NEWENVP_STEP - 1)) == 0) {
char **__newenvp;
bool update_environ;
char **__newenvp;

/*
* If the resize operation succeeds we can
* happily go on, else print a message.
*/
update_environ = (environ == newenvp);

__newenvp = REALLOCARRAY(newenvp, newenvc + NEWENVP_STEP, char *);

Expand All @@ -143,9 +145,8 @@ void addenv (const char *string, /*@null@*/const char *value)
* environ so that it doesn't point to some
* free memory area (realloc() could move it).
*/
if (environ == newenvp) {
if (update_environ)
environ = __newenvp;
}
newenvp = __newenvp;
} else {
(void) fputs (_("Environment overflow\n"), log_get_logfd());
Expand Down

0 comments on commit edf3a6a

Please sign in to comment.