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

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