Browse Source

Fix out-of-bounds acces in url_decode()

Sergey Lyubka 12 years ago
parent
commit
fbf1ccee45
2 changed files with 12 additions and 1 deletions
  1. 1 1
      mongoose.c
  2. 11 0
      test/unit_test.c

+ 1 - 1
mongoose.c

@@ -1646,7 +1646,7 @@ static int url_decode(const char *src, int src_len, char *dst,
 #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
 
   for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
-    if (src[i] == '%' &&
+    if (src[i] == '%' && i < src_len - 2 &&
         isxdigit(* (const unsigned char *) (src + i + 1)) &&
         isxdigit(* (const unsigned char *) (src + i + 2))) {
       a = tolower(* (const unsigned char *) (src + i + 1));

+ 11 - 0
test/unit_test.c

@@ -583,10 +583,21 @@ static void test_url_decode(void) {
   ASSERT(url_decode("foo", 3, buf, 3, 0) == -1);  // No space for terminating \0
   ASSERT(url_decode("foo", 3, buf, 4, 0) == 3);
   ASSERT(strcmp(buf, "foo") == 0);
+
   ASSERT(url_decode("a+", 2, buf, sizeof(buf), 0) == 2);
   ASSERT(strcmp(buf, "a+") == 0);
+
   ASSERT(url_decode("a+", 2, buf, sizeof(buf), 1) == 2);
   ASSERT(strcmp(buf, "a ") == 0);
+
+  ASSERT(url_decode("%61", 1, buf, sizeof(buf), 1) == 1);
+  ASSERT(strcmp(buf, "%") == 0);
+
+  ASSERT(url_decode("%61", 2, buf, sizeof(buf), 1) == 2);
+  ASSERT(strcmp(buf, "%6") == 0);
+
+  ASSERT(url_decode("%61", 3, buf, sizeof(buf), 1) == 1);
+  ASSERT(strcmp(buf, "a") == 0);
 }
 
 static void test_mg_strcasestr(void) {