Skip to content

Commit 57c5ecd

Browse files
sethmlarsonjohnslaviksobolevn
committed
[3.10] gh-143919: Reject control characters in http cookies
(cherry picked from commit 95746b3) Co-authored-by: Seth Michael Larson <seth@python.org> Co-authored-by: Bartosz Sławecki <bartosz@ilikepython.com> Co-authored-by: sobolevn <mail@sobolevn.me>
1 parent f12346d commit 57c5ecd

File tree

4 files changed

+73
-9
lines changed

4 files changed

+73
-9
lines changed

Doc/library/http.cookies.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -270,9 +270,9 @@ The following example demonstrates how to use the :mod:`http.cookies` module.
270270
Set-Cookie: chips=ahoy
271271
Set-Cookie: vienna=finger
272272
>>> C = cookies.SimpleCookie()
273-
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
273+
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=;";')
274274
>>> print(C)
275-
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
275+
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=;"
276276
>>> C = cookies.SimpleCookie()
277277
>>> C["oreo"] = "doublestuff"
278278
>>> C["oreo"]["path"] = "/"

Lib/http/cookies.py

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,9 @@
8787
such trickeries do not confuse it.
8888
8989
>>> C = cookies.SimpleCookie()
90-
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
90+
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=;";')
9191
>>> print(C)
92-
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
92+
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=;"
9393
9494
Each element of the Cookie also supports all of the RFC 2109
9595
Cookie attributes. Here's an example which sets the Path
@@ -170,6 +170,15 @@ class CookieError(Exception):
170170
})
171171

172172
_is_legal_key = re.compile('[%s]+' % re.escape(_LegalChars)).fullmatch
173+
_control_character_re = re.compile(r'[\x00-\x1F\x7F]')
174+
175+
176+
def _has_control_character(*val):
177+
"""Detects control characters within a value.
178+
Supports any type, as header values can be any type.
179+
"""
180+
return any(_control_character_re.search(str(v)) for v in val)
181+
173182

174183
def _quote(str):
175184
r"""Quote a string for use in a cookie header.
@@ -292,12 +301,16 @@ def __setitem__(self, K, V):
292301
K = K.lower()
293302
if not K in self._reserved:
294303
raise CookieError("Invalid attribute %r" % (K,))
304+
if _has_control_character(K, V):
305+
raise CookieError(f"Control characters are not allowed in cookies {K!r} {V!r}")
295306
dict.__setitem__(self, K, V)
296307

297308
def setdefault(self, key, val=None):
298309
key = key.lower()
299310
if key not in self._reserved:
300311
raise CookieError("Invalid attribute %r" % (key,))
312+
if _has_control_character(key, val):
313+
raise CookieError("Control characters are not allowed in cookies %r %r" % (key, val,))
301314
return dict.setdefault(self, key, val)
302315

303316
def __eq__(self, morsel):
@@ -333,6 +346,9 @@ def set(self, key, val, coded_val):
333346
raise CookieError('Attempt to set a reserved key %r' % (key,))
334347
if not _is_legal_key(key):
335348
raise CookieError('Illegal key %r' % (key,))
349+
if _has_control_character(key, val, coded_val):
350+
raise CookieError(
351+
"Control characters are not allowed in cookies %r %r %r" % (key, val, coded_val,))
336352

337353
# It's a good key, so save it.
338354
self._key = key
@@ -484,7 +500,10 @@ def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"):
484500
result = []
485501
items = sorted(self.items())
486502
for key, value in items:
487-
result.append(value.output(attrs, header))
503+
value_output = value.output(attrs, header)
504+
if _has_control_character(value_output):
505+
raise CookieError("Control characters are not allowed in cookies")
506+
result.append(value_output)
488507
return sep.join(result)
489508

490509
__str__ = output

Lib/test/test_http_cookies.py

Lines changed: 48 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@ def test_basic(self):
1717
'repr': "<SimpleCookie: chips='ahoy' vienna='finger'>",
1818
'output': 'Set-Cookie: chips=ahoy\nSet-Cookie: vienna=finger'},
1919

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

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

520+
def test_control_characters(self):
521+
for c0 in support.control_characters_c0():
522+
morsel = cookies.Morsel()
523+
524+
# .__setitem__()
525+
with self.assertRaises(cookies.CookieError):
526+
morsel[c0] = "val"
527+
with self.assertRaises(cookies.CookieError):
528+
morsel["path"] = c0
529+
530+
# .setdefault()
531+
with self.assertRaises(cookies.CookieError):
532+
morsel.setdefault("path", c0)
533+
with self.assertRaises(cookies.CookieError):
534+
morsel.setdefault(c0, "val")
535+
536+
# .set()
537+
with self.assertRaises(cookies.CookieError):
538+
morsel.set(c0, "val", "coded-value")
539+
with self.assertRaises(cookies.CookieError):
540+
morsel.set("path", c0, "coded-value")
541+
with self.assertRaises(cookies.CookieError):
542+
morsel.set("path", "val", c0)
543+
544+
def test_control_characters_output(self):
545+
# Tests that even if the internals of Morsel are modified
546+
# that a call to .output() has control character safeguards.
547+
for c0 in support.control_characters_c0():
548+
morsel = cookies.Morsel()
549+
morsel.set("key", "value", "coded-value")
550+
morsel._key = c0 # Override private variable.
551+
cookie = cookies.SimpleCookie()
552+
cookie["cookie"] = morsel
553+
with self.assertRaises(cookies.CookieError):
554+
cookie.output()
555+
556+
morsel = cookies.Morsel()
557+
morsel.set("key", "value", "coded-value")
558+
morsel._coded_value = c0 # Override private variable.
559+
cookie = cookies.SimpleCookie()
560+
cookie["cookie"] = morsel
561+
with self.assertRaises(cookies.CookieError):
562+
cookie.output()
563+
520564
def test_main():
521565
run_unittest(CookieTests, MorselTests)
522566
run_doctest(cookies)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Reject control characters in :class:`http.cookies.Morsel` fields and values.

0 commit comments

Comments
 (0)