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