From cda6c9b6e8bc9cc8dd62af52f69ed1db6e9ef91d Mon Sep 17 00:00:00 2001 From: Maxim Biro Date: Tue, 1 Feb 2022 22:20:02 -0500 Subject: [PATCH] Fix potential freeing of an immutable static buffer strerror_r() has two versions: GNU-specific and XSI-compliant. The XSI version always stores the string in the provided buffer, but the GNU version might store it in the provided buffer or it might use some immutable static buffer instead. Since we always free the error string, we might end up freeing the immutable static buffer. --- .../docker/tox-bootstrapd.sha256 | 2 +- toxcore/network.c | 26 ++++++++++++++++--- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/other/bootstrap_daemon/docker/tox-bootstrapd.sha256 b/other/bootstrap_daemon/docker/tox-bootstrapd.sha256 index bbb8cd8f16..2bd4d47712 100644 --- a/other/bootstrap_daemon/docker/tox-bootstrapd.sha256 +++ b/other/bootstrap_daemon/docker/tox-bootstrapd.sha256 @@ -1 +1 @@ -de00572e0a22b67defb05759a4d5aac6bf0e107bfd6834a1edc20ffb0379528d /usr/local/bin/tox-bootstrapd +746158481ebd16d70aadc0bf4d2dc6da6a2f3ac4eb12d219b49fc6fd7e60d149 /usr/local/bin/tox-bootstrapd diff --git a/toxcore/network.c b/toxcore/network.c index 17aa6b3af1..3532a94ca6 100644 --- a/toxcore/network.c +++ b/toxcore/network.c @@ -1746,18 +1746,36 @@ char *net_new_strerror(int error) error, 0, (char *)&str, 0, nullptr); return str; #else - char *str = (char *)malloc(256); + char tmp[256]; + + errno = 0; + #ifdef _GNU_SOURCE - str = strerror_r(error, str, 256); + const char *retstr = strerror_r(error, tmp, sizeof(tmp)); + + if (errno != 0) { + snprintf(tmp, sizeof(tmp), "error %d (strerror_r failed with errno %d)", error, errno); + } + #else - const int fmt_error = strerror_r(error, str, 256); + const int fmt_error = strerror_r(error, tmp, sizeof(tmp)); if (fmt_error != 0) { - snprintf(str, 256, "error %d (strerror failed with error %d)", error, fmt_error); + snprintf(tmp, sizeof(tmp), "error %d (strerror_r failed with error %d, errno %d)", error, fmt_error, errno); } + const char *retstr = tmp; #endif + const size_t retstr_len = strlen(retstr); + char *str = (char *)malloc(retstr_len + 1); + + if (str == nullptr) { + return nullptr; + } + + memcpy(str, retstr, retstr_len + 1); + return str; #endif }