Blame SOURCES/00346-CVE-2020-8492.patch

3d909f
diff --git a/Lib/test/test_urllib2.py b/Lib/test/test_urllib2.py
3d909f
index 876fcd4..fe9a32b 100644
3d909f
--- a/Lib/test/test_urllib2.py
3d909f
+++ b/Lib/test/test_urllib2.py
3d909f
@@ -1445,40 +1445,64 @@ class HandlerTests(unittest.TestCase):
3d909f
         bypass = {'exclude_simple': True, 'exceptions': []}
3d909f
         self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
3d909f
 
3d909f
-    def test_basic_auth(self, quote_char='"'):
3d909f
-        opener = OpenerDirector()
3d909f
-        password_manager = MockPasswordManager()
3d909f
-        auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
3d909f
-        realm = "ACME Widget Store"
3d909f
-        http_handler = MockHTTPHandler(
3d909f
-            401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' %
3d909f
-            (quote_char, realm, quote_char))
3d909f
-        opener.add_handler(auth_handler)
3d909f
-        opener.add_handler(http_handler)
3d909f
-        self._test_basic_auth(opener, auth_handler, "Authorization",
3d909f
-                              realm, http_handler, password_manager,
3d909f
-                              "http://acme.example.com/protected",
3d909f
-                              "http://acme.example.com/protected",
3d909f
-                              )
3d909f
-
3d909f
-    def test_basic_auth_with_single_quoted_realm(self):
3d909f
-        self.test_basic_auth(quote_char="'")
3d909f
-
3d909f
-    def test_basic_auth_with_unquoted_realm(self):
3d909f
-        opener = OpenerDirector()
3d909f
-        password_manager = MockPasswordManager()
3d909f
-        auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
3d909f
-        realm = "ACME Widget Store"
3d909f
-        http_handler = MockHTTPHandler(
3d909f
-            401, 'WWW-Authenticate: Basic realm=%s\r\n\r\n' % realm)
3d909f
-        opener.add_handler(auth_handler)
3d909f
-        opener.add_handler(http_handler)
3d909f
-        with self.assertWarns(UserWarning):
3d909f
+    def check_basic_auth(self, headers, realm):
3d909f
+        with self.subTest(realm=realm, headers=headers):
3d909f
+            opener = OpenerDirector()
3d909f
+            password_manager = MockPasswordManager()
3d909f
+            auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
3d909f
+            body = '\r\n'.join(headers) + '\r\n\r\n'
3d909f
+            http_handler = MockHTTPHandler(401, body)
3d909f
+            opener.add_handler(auth_handler)
3d909f
+            opener.add_handler(http_handler)
3d909f
             self._test_basic_auth(opener, auth_handler, "Authorization",
3d909f
-                                realm, http_handler, password_manager,
3d909f
-                                "http://acme.example.com/protected",
3d909f
-                                "http://acme.example.com/protected",
3d909f
-                                )
3d909f
+                                  realm, http_handler, password_manager,
3d909f
+                                  "http://acme.example.com/protected",
3d909f
+                                  "http://acme.example.com/protected")
3d909f
+
3d909f
+    def test_basic_auth(self):
3d909f
+        realm = "realm2@example.com"
3d909f
+        realm2 = "realm2@example.com"
3d909f
+        basic = f'Basic realm="{realm}"'
3d909f
+        basic2 = f'Basic realm="{realm2}"'
3d909f
+        other_no_realm = 'Otherscheme xxx'
3d909f
+        digest = (f'Digest realm="{realm2}", '
3d909f
+                  f'qop="auth, auth-int", '
3d909f
+                  f'nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", '
3d909f
+                  f'opaque="5ccc069c403ebaf9f0171e9517f40e41"')
3d909f
+        for realm_str in (
3d909f
+            # test "quote" and 'quote'
3d909f
+            f'Basic realm="{realm}"',
3d909f
+            f"Basic realm='{realm}'",
3d909f
+
3d909f
+            # charset is ignored
3d909f
+            f'Basic realm="{realm}", charset="UTF-8"',
3d909f
+
3d909f
+            # Multiple challenges per header
3d909f
+            f'{basic}, {basic2}',
3d909f
+            f'{basic}, {other_no_realm}',
3d909f
+            f'{other_no_realm}, {basic}',
3d909f
+            f'{basic}, {digest}',
3d909f
+            f'{digest}, {basic}',
3d909f
+        ):
3d909f
+            headers = [f'WWW-Authenticate: {realm_str}']
3d909f
+            self.check_basic_auth(headers, realm)
3d909f
+
3d909f
+        # no quote: expect a warning
3d909f
+        with support.check_warnings(("Basic Auth Realm was unquoted",
3d909f
+                                     UserWarning)):
3d909f
+            headers = [f'WWW-Authenticate: Basic realm={realm}']
3d909f
+            self.check_basic_auth(headers, realm)
3d909f
+
3d909f
+        # Multiple headers: one challenge per header.
3d909f
+        # Use the first Basic realm.
3d909f
+        for challenges in (
3d909f
+            [basic,  basic2],
3d909f
+            [basic,  digest],
3d909f
+            [digest, basic],
3d909f
+        ):
3d909f
+            headers = [f'WWW-Authenticate: {challenge}'
3d909f
+                       for challenge in challenges]
3d909f
+            self.check_basic_auth(headers, realm)
3d909f
 
3d909f
     def test_proxy_basic_auth(self):
3d909f
         opener = OpenerDirector()
3d909f
diff --git a/Lib/urllib/request.py b/Lib/urllib/request.py
3d909f
index c9945d9..6624e04 100644
3d909f
--- a/Lib/urllib/request.py
3d909f
+++ b/Lib/urllib/request.py
3d909f
@@ -945,8 +945,15 @@ class AbstractBasicAuthHandler:
3d909f
 
3d909f
     # allow for double- and single-quoted realm values
3d909f
     # (single quotes are a violation of the RFC, but appear in the wild)
3d909f
-    rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
3d909f
-                    'realm=(["\']?)([^"\']*)\\2', re.I)
3d909f
+    rx = re.compile('(?:^|,)'   # start of the string or ','
3d909f
+                    '[ \t]*'    # optional whitespaces
3d909f
+                    '([^ \t]+)' # scheme like "Basic"
3d909f
+                    '[ \t]+'    # mandatory whitespaces
3d909f
+                    # realm=xxx
3d909f
+                    # realm='xxx'
3d909f
+                    # realm="xxx"
3d909f
+                    'realm=(["\']?)([^"\']*)\\2',
3d909f
+                    re.I)
3d909f
 
3d909f
     # XXX could pre-emptively send auth info already accepted (RFC 2617,
3d909f
     # end of section 2, and section 1.2 immediately after "credentials"
3d909f
@@ -958,27 +965,51 @@ class AbstractBasicAuthHandler:
3d909f
         self.passwd = password_mgr
3d909f
         self.add_password = self.passwd.add_password
3d909f
 
3d909f
+    def _parse_realm(self, header):
3d909f
+        # parse WWW-Authenticate header: accept multiple challenges per header
3d909f
+        found_challenge = False
3d909f
+        for mo in AbstractBasicAuthHandler.rx.finditer(header):
3d909f
+            scheme, quote, realm = mo.groups()
3d909f
+            if quote not in ['"', "'"]:
3d909f
+                warnings.warn("Basic Auth Realm was unquoted",
3d909f
+                              UserWarning, 3)
3d909f
+
3d909f
+            yield (scheme, realm)
3d909f
+
3d909f
+            found_challenge = True
3d909f
+
3d909f
+        if not found_challenge:
3d909f
+            if header:
3d909f
+                scheme = header.split()[0]
3d909f
+            else:
3d909f
+                scheme = ''
3d909f
+            yield (scheme, None)
3d909f
+
3d909f
     def http_error_auth_reqed(self, authreq, host, req, headers):
3d909f
         # host may be an authority (without userinfo) or a URL with an
3d909f
         # authority
3d909f
-        # XXX could be multiple headers
3d909f
-        authreq = headers.get(authreq, None)
3d909f
+        headers = headers.get_all(authreq)
3d909f
+        if not headers:
3d909f
+            # no header found
3d909f
+            return
3d909f
 
3d909f
-        if authreq:
3d909f
-            scheme = authreq.split()[0]
3d909f
-            if scheme.lower() != 'basic':
3d909f
-                raise ValueError("AbstractBasicAuthHandler does not"
3d909f
-                                 " support the following scheme: '%s'" %
3d909f
-                                 scheme)
3d909f
-            else:
3d909f
-                mo = AbstractBasicAuthHandler.rx.search(authreq)
3d909f
-                if mo:
3d909f
-                    scheme, quote, realm = mo.groups()
3d909f
-                    if quote not in ['"',"'"]:
3d909f
-                        warnings.warn("Basic Auth Realm was unquoted",
3d909f
-                                      UserWarning, 2)
3d909f
-                    if scheme.lower() == 'basic':
3d909f
-                        return self.retry_http_basic_auth(host, req, realm)
3d909f
+        unsupported = None
3d909f
+        for header in headers:
3d909f
+            for scheme, realm in self._parse_realm(header):
3d909f
+                if scheme.lower() != 'basic':
3d909f
+                    unsupported = scheme
3d909f
+                    continue
3d909f
+
3d909f
+                if realm is not None:
3d909f
+                    # Use the first matching Basic challenge.
3d909f
+                    # Ignore following challenges even if they use the Basic
3d909f
+                    # scheme.
3d909f
+                    return self.retry_http_basic_auth(host, req, realm)
3d909f
+
3d909f
+        if unsupported is not None:
3d909f
+            raise ValueError("AbstractBasicAuthHandler does not "
3d909f
+                             "support the following scheme: %r"
3d909f
+                             % (scheme,))
3d909f
 
3d909f
     def retry_http_basic_auth(self, host, req, realm):
3d909f
         user, pw = self.passwd.find_user_password(realm, host)