05a38dc
From daad2c482c91de32d8305abbccc76a5de8b3a8be Mon Sep 17 00:00:00 2001
05a38dc
From: Steve Dower <steve.dower@microsoft.com>
05a38dc
Date: Thu, 7 Mar 2019 09:08:18 -0800
05a38dc
Subject: [PATCH] bpo-36216: Add check for characters in netloc that normalize
05a38dc
 to separators (GH-12201)
05a38dc
05a38dc
---
05a38dc
 Doc/library/urllib.parse.rst                  | 18 +++++++++++++++
05a38dc
 Lib/test/test_urlparse.py                     | 23 +++++++++++++++++++
05a38dc
 Lib/urllib/parse.py                           | 17 ++++++++++++++
05a38dc
 .../2019-03-06-09-38-40.bpo-36216.6q1m4a.rst  |  3 +++
05a38dc
 4 files changed, 61 insertions(+)
05a38dc
 create mode 100644 Misc/NEWS.d/next/Security/2019-03-06-09-38-40.bpo-36216.6q1m4a.rst
05a38dc
05a38dc
diff --git a/Doc/library/urllib.parse.rst b/Doc/library/urllib.parse.rst
05a38dc
index 0c8f0f607314..b565e1edd321 100644
05a38dc
--- a/Doc/library/urllib.parse.rst
05a38dc
+++ b/Doc/library/urllib.parse.rst
05a38dc
@@ -124,6 +124,11 @@ or on combining URL components into a URL string.
05a38dc
    Unmatched square brackets in the :attr:`netloc` attribute will raise a
05a38dc
    :exc:`ValueError`.
05a38dc
 
05a38dc
+   Characters in the :attr:`netloc` attribute that decompose under NFKC
05a38dc
+   normalization (as used by the IDNA encoding) into any of ``/``, ``?``,
05a38dc
+   ``#``, ``@``, or ``:`` will raise a :exc:`ValueError`. If the URL is
05a38dc
+   decomposed before parsing, no error will be raised.
05a38dc
+
05a38dc
    .. versionchanged:: 3.2
05a38dc
       Added IPv6 URL parsing capabilities.
05a38dc
 
05a38dc
@@ -136,6 +141,10 @@ or on combining URL components into a URL string.
05a38dc
       Out-of-range port numbers now raise :exc:`ValueError`, instead of
05a38dc
       returning :const:`None`.
05a38dc
 
05a38dc
+   .. versionchanged:: 3.7.3
05a38dc
+      Characters that affect netloc parsing under NFKC normalization will
05a38dc
+      now raise :exc:`ValueError`.
05a38dc
+
05a38dc
 
05a38dc
 .. function:: parse_qs(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace', max_num_fields=None)
05a38dc
 
05a38dc
@@ -257,10 +266,19 @@ or on combining URL components into a URL string.
05a38dc
    Unmatched square brackets in the :attr:`netloc` attribute will raise a
05a38dc
    :exc:`ValueError`.
05a38dc
 
05a38dc
+   Characters in the :attr:`netloc` attribute that decompose under NFKC
05a38dc
+   normalization (as used by the IDNA encoding) into any of ``/``, ``?``,
05a38dc
+   ``#``, ``@``, or ``:`` will raise a :exc:`ValueError`. If the URL is
05a38dc
+   decomposed before parsing, no error will be raised.
05a38dc
+
05a38dc
    .. versionchanged:: 3.6
05a38dc
       Out-of-range port numbers now raise :exc:`ValueError`, instead of
05a38dc
       returning :const:`None`.
05a38dc
 
05a38dc
+   .. versionchanged:: 3.7.3
05a38dc
+      Characters that affect netloc parsing under NFKC normalization will
05a38dc
+      now raise :exc:`ValueError`.
05a38dc
+
05a38dc
 
05a38dc
 .. function:: urlunsplit(parts)
05a38dc
 
05a38dc
diff --git a/Lib/test/test_urlparse.py b/Lib/test/test_urlparse.py
05a38dc
index be50b47603aa..e6638aee2244 100644
05a38dc
--- a/Lib/test/test_urlparse.py
05a38dc
+++ b/Lib/test/test_urlparse.py
05a38dc
@@ -1,3 +1,5 @@
05a38dc
+import sys
05a38dc
+import unicodedata
05a38dc
 import unittest
05a38dc
 import urllib.parse
05a38dc
 
05a38dc
@@ -984,6 +986,27 @@ def test_all(self):
05a38dc
                 expected.append(name)
05a38dc
         self.assertCountEqual(urllib.parse.__all__, expected)
05a38dc
 
05a38dc
+    def test_urlsplit_normalization(self):
05a38dc
+        # Certain characters should never occur in the netloc,
05a38dc
+        # including under normalization.
05a38dc
+        # Ensure that ALL of them are detected and cause an error
05a38dc
+        illegal_chars = '/:#?@'
05a38dc
+        hex_chars = {'{:04X}'.format(ord(c)) for c in illegal_chars}
05a38dc
+        denorm_chars = [
05a38dc
+            c for c in map(chr, range(128, sys.maxunicode))
05a38dc
+            if (hex_chars & set(unicodedata.decomposition(c).split()))
05a38dc
+            and c not in illegal_chars
05a38dc
+        ]
05a38dc
+        # Sanity check that we found at least one such character
05a38dc
+        self.assertIn('\u2100', denorm_chars)
05a38dc
+        self.assertIn('\uFF03', denorm_chars)
05a38dc
+
05a38dc
+        for scheme in ["http", "https", "ftp"]:
05a38dc
+            for c in denorm_chars:
05a38dc
+                url = "{}://netloc{}false.netloc/path".format(scheme, c)
05a38dc
+                with self.subTest(url=url, char='{:04X}'.format(ord(c))):
05a38dc
+                    with self.assertRaises(ValueError):
05a38dc
+                        urllib.parse.urlsplit(url)
05a38dc
 
05a38dc
 class Utility_Tests(unittest.TestCase):
05a38dc
     """Testcase to test the various utility functions in the urllib."""
05a38dc
diff --git a/Lib/urllib/parse.py b/Lib/urllib/parse.py
05a38dc
index f691ab74f87f..39c5d6a80824 100644
05a38dc
--- a/Lib/urllib/parse.py
05a38dc
+++ b/Lib/urllib/parse.py
05a38dc
@@ -391,6 +391,21 @@ def _splitnetloc(url, start=0):
05a38dc
             delim = min(delim, wdelim)     # use earliest delim position
05a38dc
     return url[start:delim], url[delim:]   # return (domain, rest)
05a38dc
 
05a38dc
+def _checknetloc(netloc):
05a38dc
+    if not netloc or netloc.isascii():
05a38dc
+        return
05a38dc
+    # looking for characters like \u2100 that expand to 'a/c'
05a38dc
+    # IDNA uses NFKC equivalence, so normalize for this check
05a38dc
+    import unicodedata
05a38dc
+    netloc2 = unicodedata.normalize('NFKC', netloc)
05a38dc
+    if netloc == netloc2:
05a38dc
+        return
05a38dc
+    _, _, netloc = netloc.rpartition('@') # anything to the left of '@' is okay
05a38dc
+    for c in '/?#@:':
05a38dc
+        if c in netloc2:
05a38dc
+            raise ValueError("netloc '" + netloc2 + "' contains invalid " +
05a38dc
+                             "characters under NFKC normalization")
05a38dc
+
05a38dc
 def urlsplit(url, scheme='', allow_fragments=True):
05a38dc
     """Parse a URL into 5 components:
05a38dc
     <scheme>://<netloc>/<path>?<query>#<fragment>
05a38dc
@@ -419,6 +434,7 @@ def urlsplit(url, scheme='', allow_fragments=True):
05a38dc
                 url, fragment = url.split('#', 1)
05a38dc
             if '?' in url:
05a38dc
                 url, query = url.split('?', 1)
05a38dc
+            _checknetloc(netloc)
05a38dc
             v = SplitResult('http', netloc, url, query, fragment)
05a38dc
             _parse_cache[key] = v
05a38dc
             return _coerce_result(v)
05a38dc
@@ -442,6 +458,7 @@ def urlsplit(url, scheme='', allow_fragments=True):
05a38dc
         url, fragment = url.split('#', 1)
05a38dc
     if '?' in url:
05a38dc
         url, query = url.split('?', 1)
05a38dc
+    _checknetloc(netloc)
05a38dc
     v = SplitResult(scheme, netloc, url, query, fragment)
05a38dc
     _parse_cache[key] = v
05a38dc
     return _coerce_result(v)
05a38dc
diff --git a/Misc/NEWS.d/next/Security/2019-03-06-09-38-40.bpo-36216.6q1m4a.rst b/Misc/NEWS.d/next/Security/2019-03-06-09-38-40.bpo-36216.6q1m4a.rst
05a38dc
new file mode 100644
05a38dc
index 000000000000..5546394157f9
05a38dc
--- /dev/null
05a38dc
+++ b/Misc/NEWS.d/next/Security/2019-03-06-09-38-40.bpo-36216.6q1m4a.rst
05a38dc
@@ -0,0 +1,3 @@
05a38dc
+Changes urlsplit() to raise ValueError when the URL contains characters that
05a38dc
+decompose under IDNA encoding (NFKC-normalization) into characters that
05a38dc
+affect how the URL is parsed.