Backport from HEAD:

* uri/apr_uri.c (apr_parse_uri): Fix input validation to avoid
passing negative length to memcpy for malformed IPv6 literal
addresses.

* test/testuri.c: Add tests for such malformed URIs.

Reviewed by: trawick, madhum


git-svn-id: https://svn.apache.org/repos/asf/apr/apr-util/branches/APU_0_9_BRANCH@59133 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/CHANGES b/CHANGES
index b534aa0..fcbaeef 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,5 +1,10 @@
 Changes with APR-util 0.9.5
 
+  *) SECURITY: CAN-2004-0786 (cve.mitre.org)
+     Fix input validation in apr_uri_parse() to avoid passing negative
+     length to memcpy for malformed IPv6 literal addresses.
+     [Joe Orton]
+
   *) Fix build issues in paths containing symlinks.  PR 8867.
      [Joe Orton]
 
diff --git a/test/testuri.c b/test/testuri.c
index 0f74119..0e363ad 100644
--- a/test/testuri.c
+++ b/test/testuri.c
@@ -36,6 +36,11 @@
 
 struct aup_test aup_tests[] =
 {
+    { "http://[/::1]/index.html", APR_EGENERAL },
+    { "http://[", APR_EGENERAL },
+    { "http://[?::1]/index.html", APR_EGENERAL },
+
+
     {
         "http://127.0.0.1:9999/asdf.html",
         0, "http", "127.0.0.1:9999", NULL, NULL, "127.0.0.1", "9999", "/asdf.html", NULL, NULL, 9999
diff --git a/uri/apr_uri.c b/uri/apr_uri.c
index 1a304b0..1a00ef6 100644
--- a/uri/apr_uri.c
+++ b/uri/apr_uri.c
@@ -307,11 +307,11 @@
         if (*hostinfo == '[') {
             v6_offset1 = 1;
             v6_offset2 = 2;
-            s = uri;
-            do {
-                --s;
-            } while (s >= hostinfo && *s != ':' && *s != ']');
-            if (s < hostinfo || *s == ']') {
+            s = memchr(hostinfo, ']', uri - hostinfo);
+            if (s == NULL) {
+                return APR_EGENERAL;
+            }
+            if (*++s != ':') {
                 s = NULL; /* no port */
             }
         }