From 6e26c4b9ce250dea74ceebebff5dfac1b95881f9 Mon Sep 17 00:00:00 2001 From: Albert Koczy Date: Mon, 15 Apr 2024 08:55:54 +0200 Subject: [PATCH] fix: Buffer overflow in string.format when called with malformed args (#419) The current format specifier is stored in a small buffer on the stack, but the maxium length was not enforced, so a buffer overflow was possible. Added a check to actually limit it's length. Added a test case to verify an ASAN crash does not occur. --- src/be_strlib.c | 13 +++++++++---- tests/string.be | 3 +++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/be_strlib.c b/src/be_strlib.c index 6743c21..2ce5609 100644 --- a/src/be_strlib.c +++ b/src/be_strlib.c @@ -549,7 +549,7 @@ static const char* skip2dig(const char *s) return s; } -static const char* get_mode(const char *str, char *buf) +static const char* get_mode(const char *str, char *buf, size_t buf_len) { const char *p = str; while (*p && strchr(FLAGES, *p)) { /* skip flags */ @@ -560,8 +560,13 @@ static const char* get_mode(const char *str, char *buf) p = skip2dig(++p); /* skip width (2 digits at most) */ } *(buf++) = '%'; - strncpy(buf, str, p - str + 1); - buf[p - str + 1] = '\0'; + size_t mode_size = p - str + 1; + /* Leave 2 bytes for the leading % and the trailing '\0' */ + if (mode_size > buf_len - 2) { + mode_size = buf_len - 2; + } + strncpy(buf, str, mode_size); + buf[mode_size] = '\0'; return p; } @@ -632,7 +637,7 @@ int be_str_format(bvm *vm) } pushstr(vm, format, p - format); concat2(vm); - p = get_mode(p + 1, mode); + p = get_mode(p + 1, mode, sizeof(mode)); buf[0] = '\0'; if (index > top && *p != '%') { be_raise(vm, "runtime_error", be_pushfstring(vm, diff --git a/tests/string.be b/tests/string.be index 15b403b..448ca52 100644 --- a/tests/string.be +++ b/tests/string.be @@ -149,6 +149,9 @@ assert(string.format("%s", false) == 'false') assert(string.format("%q", "\ntest") == '\'\\ntest\'') +# corrupt format string should not crash the VM +string.format("%0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f", 3.5) + # format is now synonym to string.format assert(format == string.format) assert(format("%.1f", 3) == '3.0')