Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Doc/library/http.cookies.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -292,9 +292,9 @@ The following example demonstrates how to use the :mod:`http.cookies` module.
Set-Cookie: chips=ahoy
Set-Cookie: vienna=finger
>>> C = cookies.SimpleCookie()
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=;";')
>>> print(C)
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=;"
>>> C = cookies.SimpleCookie()
>>> C["oreo"] ="doublestuff"
>>> C["oreo"]["path"] ="/"
Expand Down
25 changes: 22 additions & 3 deletions Lib/http/cookies.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -87,9 +87,9 @@
such trickeries do not confuse it.
>>> C = cookies.SimpleCookie()
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=;";')
>>> print(C)
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=;"
Each element of the Cookie also supports all of the RFC 2109
Cookie attributes. Here's an example which sets the Path
Expand DownExpand Up@@ -170,6 +170,15 @@ class CookieError(Exception):
})

_is_legal_key=re.compile('[%s]+'%re.escape(_LegalChars)).fullmatch
_control_character_re=re.compile(r'[\x00-\x1F\x7F]')


def_has_control_character(*val):
"""Detects control characters within a value.
Supports any type, as header values can be any type.
"""
returnany(_control_character_re.search(str(v)) forvinval)


def_quote(str):
r"""Quote a string for use in a cookie header.
Expand DownExpand Up@@ -294,12 +303,16 @@ def __setitem__(self, K, V):
K=K.lower()
ifnotKinself._reserved:
raiseCookieError("Invalid attribute %r"% (K,))
if_has_control_character(K, V):
raiseCookieError(f"Control characters are not allowed in cookies {K!r}{V!r}")
dict.__setitem__(self, K, V)

defsetdefault(self, key, val=None):
key=key.lower()
ifkeynotinself._reserved:
raiseCookieError("Invalid attribute %r"% (key,))
if_has_control_character(key, val):
raiseCookieError("Control characters are not allowed in cookies %r %r"% (key, val,))
returndict.setdefault(self, key, val)

def__eq__(self, morsel):
Expand DownExpand Up@@ -335,6 +348,9 @@ def set(self, key, val, coded_val):
raiseCookieError('Attempt to set a reserved key %r'% (key,))
ifnot_is_legal_key(key):
raiseCookieError('Illegal key %r'% (key,))
if_has_control_character(key, val, coded_val):
raiseCookieError(
"Control characters are not allowed in cookies %r %r %r"% (key, val, coded_val,))

# It's a good key, so save it.
self._key=key
Expand DownExpand Up@@ -488,7 +504,10 @@ def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"):
result= []
items=sorted(self.items())
forkey, valueinitems:
result.append(value.output(attrs, header))
value_output=value.output(attrs, header)
if_has_control_character(value_output):
raiseCookieError("Control characters are not allowed in cookies")
result.append(value_output)
returnsep.join(result)

__str__=output
Expand Down
52 changes: 48 additions & 4 deletions Lib/test/test_http_cookies.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,10 +17,10 @@ def test_basic(self):
'repr': "<SimpleCookie: chips='ahoy' vienna='finger'>",
'output': 'Set-Cookie: chips=ahoy\nSet-Cookie: vienna=finger'},

{'data': 'keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"',
'dict':{'keebler' : 'E=mc2; L="Loves"; fudge=\012;'},
'repr': '''<SimpleCookie: keebler='E=mc2; L="Loves"; fudge=\\n;'>''',
'output': 'Set-Cookie: keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"'},
{'data': 'keebler="E=mc2; L=\\"Loves\\"; fudge=;"',
'dict':{'keebler' : 'E=mc2; L="Loves"; fudge=;'},
'repr': '''<SimpleCookie: keebler='E=mc2; L="Loves"; fudge=;'>''',
'output': 'Set-Cookie: keebler="E=mc2; L=\\"Loves\\"; fudge=;"'},

# Check illegal cookies that have an '=' char in an unquoted value
{'data': 'keebler=E=mc2',
Expand DownExpand Up@@ -571,6 +571,50 @@ def test_repr(self):
r'Set-Cookie: key=coded_val; '
r'expires=\w+, \d+ \w+ \d+ \d+:\d+:\d+ \w+')

deftest_control_characters(self):
forc0insupport.control_characters_c0():
morsel=cookies.Morsel()

# .__setitem__()
withself.assertRaises(cookies.CookieError):
morsel[c0] ="val"
withself.assertRaises(cookies.CookieError):
morsel["path"] =c0

# .setdefault()
withself.assertRaises(cookies.CookieError):
morsel.setdefault("path", c0)
withself.assertRaises(cookies.CookieError):
morsel.setdefault(c0, "val")

# .set()
withself.assertRaises(cookies.CookieError):
morsel.set(c0, "val", "coded-value")
withself.assertRaises(cookies.CookieError):
morsel.set("path", c0, "coded-value")
withself.assertRaises(cookies.CookieError):
morsel.set("path", "val", c0)

deftest_control_characters_output(self):
# Tests that even if the internals of Morsel are modified
# that a call to .output() has control character safeguards.
forc0insupport.control_characters_c0():
morsel=cookies.Morsel()
morsel.set("key", "value", "coded-value")
morsel._key=c0# Override private variable.
cookie=cookies.SimpleCookie()
cookie["cookie"] =morsel
withself.assertRaises(cookies.CookieError):
cookie.output()

morsel=cookies.Morsel()
morsel.set("key", "value", "coded-value")
morsel._coded_value=c0# Override private variable.
cookie=cookies.SimpleCookie()
cookie["cookie"] =morsel
withself.assertRaises(cookies.CookieError):
cookie.output()


defload_tests(loader, tests, pattern):
tests.addTest(doctest.DocTestSuite(cookies))
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
Reject control characters in :class:`http.cookies.Morsel` fields and values.
Loading