Skip to content

Commit

Permalink
Be more strict in parsing Content-Length
Browse files Browse the repository at this point in the history
Validate that we are only parsing digits and nothing else. RFC7230 is
explicit in that the Content-Length can only exist of 1*DIGIT and may
not include any additional sign information.

The Python int() function parses `+10` as `10` which means we were more
lenient than the standard intended.
  • Loading branch information
digitalresistor committed Mar 13, 2022
1 parent e75b0d9 commit 1f6059f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
12 changes: 6 additions & 6 deletions src/waitress/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

from waitress.buffers import OverflowableBuffer
from waitress.receiver import ChunkedReceiver, FixedStreamReceiver
from waitress.rfc7230 import HEADER_FIELD_RE, ONLY_DIGIT_RE
from waitress.utilities import (
BadRequest,
RequestEntityTooLarge,
Expand All @@ -31,8 +32,6 @@
find_double_newline,
)

from .rfc7230 import HEADER_FIELD


def unquote_bytes_to_wsgi(bytestring):
return unquote_to_bytes(bytestring).decode("latin-1")
Expand Down Expand Up @@ -221,7 +220,7 @@ def parse_header(self, header_plus):
headers = self.headers

for line in lines:
header = HEADER_FIELD.match(line)
header = HEADER_FIELD_RE.match(line)

if not header:
raise ParsingError("Invalid header")
Expand Down Expand Up @@ -317,11 +316,12 @@ def parse_header(self, header_plus):
self.connection_close = True

if not self.chunked:
try:
cl = int(headers.get("CONTENT_LENGTH", 0))
except ValueError:
cl = headers.get("CONTENT_LENGTH", "0")

if not ONLY_DIGIT_RE.match(cl.encode("latin-1")):
raise ParsingError("Content-Length is invalid")

cl = int(cl)
self.content_length = cl

if cl > 0:
Expand Down
20 changes: 20 additions & 0 deletions tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,26 @@ def test_parse_header_bad_content_length(self):
else: # pragma: nocover
self.assertTrue(False)

def test_parse_header_bad_content_length_plus(self):
data = b"GET /foobar HTTP/8.4\r\ncontent-length: +10\r\n"

try:
self.parser.parse_header(data)
except ParsingError as e:
self.assertIn("Content-Length is invalid", e.args[0])
else: # pragma: nocover
self.assertTrue(False)

def test_parse_header_bad_content_length_minus(self):
data = b"GET /foobar HTTP/8.4\r\ncontent-length: -10\r\n"

try:
self.parser.parse_header(data)
except ParsingError as e:
self.assertIn("Content-Length is invalid", e.args[0])
else: # pragma: nocover
self.assertTrue(False)

def test_parse_header_multiple_content_length(self):
data = b"GET /foobar HTTP/8.4\r\ncontent-length: 10\r\ncontent-length: 20\r\n"

Expand Down

0 comments on commit 1f6059f

Please sign in to comment.