From a8b8514272ca1c0360b78bf194a585f811f52d62 Mon Sep 17 00:00:00 2001 From: Jonas 'Sortie' Termansen Date: Sat, 26 Jul 2014 16:24:12 +0200 Subject: [PATCH] Fix clearenv(3) leaving internal pointer alive after free. This causes use-after-free and double-free bugs when other environment functions are subsequently called. --- libc/stdlib/clearenv.cpp | 1 + libc/stdlib/setenv.cpp | 7 +++++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/libc/stdlib/clearenv.cpp b/libc/stdlib/clearenv.cpp index 015d1e54..f8660835 100644 --- a/libc/stdlib/clearenv.cpp +++ b/libc/stdlib/clearenv.cpp @@ -32,6 +32,7 @@ extern "C" int clearenv() for ( size_t i = 0; environ[i]; i++ ) free(environ[i]); free(environ); + __environ_malloced = NULL; } environ = NULL; return 0; diff --git a/libc/stdlib/setenv.cpp b/libc/stdlib/setenv.cpp index b4b6fe26..2fad106b 100644 --- a/libc/stdlib/setenv.cpp +++ b/libc/stdlib/setenv.cpp @@ -42,7 +42,10 @@ static char* create_entry(const char* name, size_t name_length, char* result = (char*) malloc(result_size); if ( !result ) return NULL; - stpcpy(stpcpy(stpcpy(result, name), "="), value); + memcpy(result, name, name_length); + result[name_length] = '='; + memcpy(result + name_length + 1, value, value_length); + result[name_length + 1 + value_length] = '\0'; return result; } @@ -73,7 +76,7 @@ static bool recover_environment() for ( size_t i = 0; i < __environ_used; i++ ) free(__environ_malloced[i]); free(__environ_malloced); - __environ_malloced = 0; + __environ_malloced = NULL; __environ_length = 0; __environ_used = 0; }