1From 9903253c347f9e0bffd285ae3829aef251cc852d Mon Sep 17 00:00:00 2001 2From: hopper-vul <118949689+hopper-vul@users.noreply.github.com> 3Date: Wed, 18 Jan 2023 22:14:26 +0800 4Subject: [PATCH] Add str len check in config_sortlist to avoid stack overflow 5 (#497) 6 7In ares_set_sortlist, it calls config_sortlist(..., sortstr) to parse 8the input str and initialize a sortlist configuration. 9 10However, ares_set_sortlist has not any checks about the validity of the input str. 11It is very easy to create an arbitrary length stack overflow with the unchecked 12`memcpy(ipbuf, str, q-str);` and `memcpy(ipbufpfx, str, q-str);` 13statements in the config_sortlist call, which could potentially cause severe 14security impact in practical programs. 15 16This commit add necessary check for `ipbuf` and `ipbufpfx` which avoid the 17potential stack overflows. 18 19fixes #496 20 21Fix By: @hopper-vul 22 23CVE: CVE-2022-4415 24Upstream-Status: Backport [https://github.com/c-ares/c-ares/commit/9903253c347f9e0bffd285ae3829aef251cc852d] 25 26Signed-off-by: Peter Marko <peter.marko@siemens.com> 27--- 28 src/lib/ares_init.c | 4 ++++ 29 test/ares-test-init.cc | 2 ++ 30 2 files changed, 6 insertions(+) 31 32diff --git a/src/lib/ares_init.c b/src/lib/ares_init.c 33index 51668a5c..3f9cec65 100644 34--- a/src/lib/ares_init.c 35+++ b/src/lib/ares_init.c 36@@ -1913,6 +1913,8 @@ static int config_sortlist(struct apattern **sortlist, int *nsort, 37 q = str; 38 while (*q && *q != '/' && *q != ';' && !ISSPACE(*q)) 39 q++; 40+ if (q-str >= 16) 41+ return ARES_EBADSTR; 42 memcpy(ipbuf, str, q-str); 43 ipbuf[q-str] = '\0'; 44 /* Find the prefix */ 45@@ -1921,6 +1923,8 @@ static int config_sortlist(struct apattern **sortlist, int *nsort, 46 const char *str2 = q+1; 47 while (*q && *q != ';' && !ISSPACE(*q)) 48 q++; 49+ if (q-str >= 32) 50+ return ARES_EBADSTR; 51 memcpy(ipbufpfx, str, q-str); 52 ipbufpfx[q-str] = '\0'; 53 str = str2; 54diff --git a/test/ares-test-init.cc b/test/ares-test-init.cc 55index 63c6a228..ee845181 100644 56--- a/test/ares-test-init.cc 57+++ b/test/ares-test-init.cc 58@@ -275,6 +275,8 @@ TEST_F(DefaultChannelTest, SetAddresses) { 59 60 TEST_F(DefaultChannelTest, SetSortlistFailures) { 61 EXPECT_EQ(ARES_ENODATA, ares_set_sortlist(nullptr, "1.2.3.4")); 62+ EXPECT_EQ(ARES_EBADSTR, ares_set_sortlist(channel_, "111.111.111.111*/16")); 63+ EXPECT_EQ(ARES_EBADSTR, ares_set_sortlist(channel_, "111.111.111.111/255.255.255.240*")); 64 EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "xyzzy ; lwk")); 65 EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "xyzzy ; 0x123")); 66 } 67