Skip to content

Commit d958dcf

Browse files
authored
Merge pull request #33 from ActiveState/BE-3128-cve-2023-24329
Be 3128 CVE 2023 24329
2 parents dd087fa + 602846a commit d958dcf

File tree

4 files changed

+142
-8
lines changed

4 files changed

+142
-8
lines changed

Doc/library/urlparse.rst

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,11 @@ The :mod:`urlparse` module defines the following functions:
125125
decomposed before parsing, or is not a Unicode string, no error will be
126126
raised.
127127

128+
.. warning::
129+
130+
:func:`urlparse` does not perform validation. See :ref:`URL parsing
131+
security <url-parsing-security>` for details.
132+
128133
.. versionchanged:: 2.5
129134
Added attributes to return value.
130135

@@ -248,6 +253,10 @@ The :mod:`urlparse` module defines the following functions:
248253
decomposed before parsing, or is not a Unicode string, no error will be
249254
raised.
250255

256+
Following some of the `WHATWG spec`_ that updates RFC 3986, leading C0
257+
control and space characters are stripped from the URL. ``\n``,
258+
``\r`` and tab ``\t`` characters are removed from the URL at any position.
259+
251260
.. versionadded:: 2.2
252261

253262
.. versionchanged:: 2.5
@@ -257,6 +266,9 @@ The :mod:`urlparse` module defines the following functions:
257266
Characters that affect netloc parsing under NFKC normalization will
258267
now raise :exc:`ValueError`.
259268

269+
.. versionchanged:: 2.7.17.8
270+
Leading WHATWG C0 control and space characters are stripped from the URL.
271+
260272

261273
.. function:: urlunsplit(parts)
262274

@@ -378,3 +390,14 @@ The following classes provide the implementations of the parse results:
378390

379391
Concrete class for :func:`urlsplit` results.
380392

393+
.. _url-parsing-security:
394+
395+
URL parsing security
396+
--------------------
397+
398+
The :func:`urlsplit` and :func:`urlparse` APIs do not perform **validation** of
399+
inputs. They may not raise errors on inputs that other applications consider
400+
invalid. They may also succeed on some inputs that might not be considered
401+
URLs elsewhere. Their purpose is for practical functionality rather than
402+
purity.
403+

Lib/test/test_urlparse.py

Lines changed: 102 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# -*- coding: utf-8 -*-
12
# Copyright (C) 2022 ActiveState Software Inc.
23
# test_urlparse.py is licensed under the PSFLv2 License.
34
# See the file LICENSE for details.
@@ -8,6 +9,23 @@
89
import unittest
910
import urlparse
1011

12+
# Add ability to run sub-tests
13+
def sub_test(param_list):
14+
"""Decorates a test case to run it as a set of subtests."""
15+
16+
def decorator(f):
17+
18+
@functools.wraps(f)
19+
def wrapped(self):
20+
for param in param_list:
21+
with self.subTest(**param):
22+
f(self, **param)
23+
24+
return wrapped
25+
26+
return decorator
27+
28+
1129
RFC1808_BASE = "http://a/b/c/d;p?q#f"
1230
RFC2396_BASE = "http://a/b/c/d;p?q"
1331
RFC3986_BASE = 'http://a/b/c/d;p?q'
@@ -602,16 +620,92 @@ def test_urlsplit_remove_unsafe_bytes(self):
602620
self.assertEqual(p.port, None)
603621
self.assertEqual(p.geturl(), u"http://www.python.org/javascript:alert('msg')/#frag")
604622

623+
def test_urlsplit_strip_url(self):
624+
noise = bytes(bytearray(range(0, 0x20 + 1)))
625+
base_url = "http://User:[email protected]:080/doc/?query=yes#frag"
605626

606-
def test_attributes_bad_port(self):
607-
"""Check handling of non-integer ports."""
608-
p = urlparse.urlsplit("http://www.example.net:foo")
609-
self.assertEqual(p.netloc, "www.example.net:foo")
610-
self.assertRaises(ValueError, lambda: p.port)
627+
url = noise.decode("utf-8") + base_url
628+
p = urlparse.urlsplit(url)
629+
self.assertEqual(p.scheme, "http")
630+
self.assertEqual(p.netloc, "User:[email protected]:080")
631+
self.assertEqual(p.path, "/doc/")
632+
self.assertEqual(p.query, "query=yes")
633+
self.assertEqual(p.fragment, "frag")
634+
self.assertEqual(p.username, "User")
635+
self.assertEqual(p.password, "Pass")
636+
self.assertEqual(p.hostname, "www.python.org")
637+
self.assertEqual(p.port, 80)
638+
self.assertEqual(p.geturl(), base_url)
611639

612-
p = urlparse.urlparse("http://www.example.net:foo")
613-
self.assertEqual(p.netloc, "www.example.net:foo")
614-
self.assertRaises(ValueError, lambda: p.port)
640+
url = noise + base_url.encode("utf-8")
641+
p = urlparse.urlsplit(url)
642+
self.assertEqual(p.scheme, b"http")
643+
self.assertEqual(p.netloc, b"User:[email protected]:080")
644+
self.assertEqual(p.path, b"/doc/")
645+
self.assertEqual(p.query, b"query=yes")
646+
self.assertEqual(p.fragment, b"frag")
647+
self.assertEqual(p.username, b"User")
648+
self.assertEqual(p.password, b"Pass")
649+
self.assertEqual(p.hostname, b"www.python.org")
650+
self.assertEqual(p.port, 80)
651+
self.assertEqual(p.geturl(), base_url.encode("utf-8"))
652+
653+
# Test that trailing space is preserved as some applications rely on
654+
# this within query strings.
655+
query_spaces_url = "https://www.python.org:88/doc/?query= "
656+
p = urlparse.urlsplit(noise.decode("utf-8") + query_spaces_url)
657+
self.assertEqual(p.scheme, "https")
658+
self.assertEqual(p.netloc, "www.python.org:88")
659+
self.assertEqual(p.path, "/doc/")
660+
self.assertEqual(p.query, "query= ")
661+
self.assertEqual(p.port, 88)
662+
self.assertEqual(p.geturl(), query_spaces_url)
663+
664+
p = urlparse.urlsplit("www.pypi.org ")
665+
# That "hostname" gets considered a "path" due to the
666+
# trailing space and our existing logic... YUCK...
667+
# and re-assembles via geturl aka unurlsplit into the original.
668+
# django.core.validators.URLValidator (at least through v3.2) relies on
669+
# this, for better or worse, to catch it in a ValidationError via its
670+
# regular expressions.
671+
# Here we test the basic round trip concept of such a trailing space.
672+
self.assertEqual(urlparse.urlunsplit(p), "www.pypi.org ")
673+
674+
# with scheme as cache-key
675+
url = "//www.python.org/"
676+
scheme = noise.decode("utf-8") + "https" + noise.decode("utf-8")
677+
for _ in range(2):
678+
p = urlparse.urlsplit(url, scheme=scheme)
679+
self.assertEqual(p.scheme, "https")
680+
self.assertEqual(p.geturl(), "https://www.python.org/")
681+
682+
def test_attributes_bad_port_a(self):
683+
"""Check handling of invalid ports."""
684+
for bytes in (False, True):
685+
for parse in (urlparse.urlsplit, urlparse.urlparse):
686+
# Spaces and invalid characters are stripped now, so the missing one's can't cause issues
687+
# for port in ("foo", "1.5", "-1", "0x10", "-0", "1_1", " 1", "1 ", "६"):
688+
for port in ("foo", "1.5", "0x10", "1_1"):
689+
netloc = "www.example.net:" + port
690+
url = "http://" + netloc + "/"
691+
if bytes:
692+
netloc = netloc.encode("ascii")
693+
url = url.encode("ascii")
694+
p = parse(url)
695+
self.assertEqual(p.netloc, netloc)
696+
with self.assertRaises(ValueError):
697+
p.port
698+
699+
def test_attributes_bad_port_b(self):
700+
"""Check handling of invalid ports."""
701+
for parse in (urlparse.urlsplit, urlparse.urlparse):
702+
for port in ("६"):
703+
netloc = "www.example.net:" + port
704+
url = "http://" + netloc + "/"
705+
p = parse(url)
706+
self.assertEqual(p.netloc, netloc)
707+
with self.assertRaises(ValueError):
708+
p.port
615709

616710
def test_attributes_without_netloc(self):
617711
# This example is straight from RFC 3261. It looks like it

Lib/urlparse.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@
3030
parsing quirks from older RFCs are retained. The testcases in
3131
test_urlparse.py provides a good indicator of parsing behavior.
3232
33+
The WHATWG URL Parser spec should also be considered. We are not compliant with
34+
it either due to existing user code API behavior expectations (Hyrum's Law).
35+
It serves as a useful guide when making changes.
3336
"""
3437

3538
import re
@@ -66,6 +69,10 @@
6669
'0123456789'
6770
'+-.')
6871

72+
# Leading and trailing C0 control and space to be stripped per WHATWG spec.
73+
# == "".join([chr(i) for i in range(0, 0x20 + 1)])
74+
_WHATWG_C0_CONTROL_OR_SPACE = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f '
75+
6976
# Unsafe bytes to be removed per WHATWG spec
7077
_UNSAFE_URL_BYTES_TO_REMOVE = ['\t', '\r', '\n']
7178

@@ -197,13 +204,20 @@ def urlsplit(url, scheme='', allow_fragments=True):
197204
Return a 5-tuple: (scheme, netloc, path, query, fragment).
198205
Note that we don't break the components up in smaller bits
199206
(e.g. netloc is a single string) and we don't expand % escapes."""
207+
200208
allow_fragments = bool(allow_fragments)
201209
key = url, scheme, allow_fragments, type(url), type(scheme)
202210
cached = _parse_cache.get(key, None)
203211
if cached:
204212
return cached
205213
if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth
206214
clear_cache()
215+
216+
# Only lstrip url as some applications rely on preserving trailing space.
217+
# (https://url.spec.whatwg.org/#concept-basic-url-parser would strip both)
218+
url = url.lstrip(_WHATWG_C0_CONTROL_OR_SPACE)
219+
scheme = scheme.strip(_WHATWG_C0_CONTROL_OR_SPACE)
220+
207221
netloc = query = fragment = ''
208222
i = url.find(':')
209223
if i > 0:
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:func:`urllib.parse.urlsplit` now strips leading C0 control and space
2+
characters following the specification for URLs defined by WHATWG in
3+
response to CVE-2023-24329. Patch by Illia Volochii.

0 commit comments

Comments
 (0)