Skip to content
Myr

check and test for headers containing return characters or leading whitespace

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Nate Prewitt · committed by Nate Prewitt · parent 92fe51c · Browse files · 5 files+75 added−7 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+75 added−7 removed

  • tests:+42 added−1 removed
  • other:+33 added−6 removed

5 files+75 added−7 removed

modified:requests/exceptions.py+5 added-1 removed
78 unmodified lines
79 """See defaults.py for valid schemas."""808182class InvalidURL(RequestException, ValueError):83 """ The URL provided was somehow invalid. """83 """The URL provided was somehow invalid."""848586class InvalidHeader(RequestException, ValueError):87 """The header value provided was somehow invalid."""888990class ChunkedEncodingError(RequestException):91 """The server declared chunked encoding but sent an invalid chunk."""9293
25 unmodified lines
modified:requests/models.py+8 added-4 removed
25 unmodified lines
26 ContentDecodingError, ConnectionError, StreamConsumedError)27from .utils import (28 guess_filename, get_auth_from_url, requote_uri,29 stream_decode_response_unicode, to_key_val_list, parse_header_links,30 iter_slices, guess_json_utf, super_len, to_native_string)30 iter_slices, guess_json_utf, super_len, to_native_string, 31 check_header_validity)32from .compat import (33 cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,34 is_py2, chardet, builtin_str, basestring)35from .compat import json as complexjson
367 unmodified lines
403404 def prepare_headers(self, headers):405 """Prepares the given HTTP headers."""406407 self.headers = CaseInsensitiveDict()408 if headers:407 self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items())408 else:409 self.headers = CaseInsensitiveDict()409 for header in headers.items():410 # Raise exception on invalid header value.411 check_header_validity(header)412 name, value = header413 self.headers[to_native_string(name)] = value414415 def prepare_body(self, data, files, json=None):416 """Prepares the given HTTP body data."""417
448 unmodified lines
modified:requests/utils.py+19 added-1 removed
25 unmodified lines
26 builtin_str, getproxies, proxy_bypass, urlunparse,27 basestring)28from .cookies import RequestsCookieJar, cookiejar_from_dict29from .structures import CaseInsensitiveDict30from .exceptions import InvalidURL, FileModeWarning30from .exceptions import InvalidURL, InvalidHeader, FileModeWarning3132_hush_pyflakes = (RequestsCookieJar,)3334NETRC_FILES = ('.netrc', '_netrc')
696 unmodified lines
731 out = string.decode(encoding)732733 return out734735# Moved outside of function to avoid recompile every call736_CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$')737_CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$')738739def check_header_validity(header):740 """Verifies that header value doesn't contain leading whitespace or741 return characters. This prevents unintended header injection.742743 :param header: tuple, in the format (name, value).744 """745 name, value = header746747 if isinstance(value, bytes):748 pat = _CLEAN_HEADER_REGEX_BYTE749 else:750 pat = _CLEAN_HEADER_REGEX_STR751 if not pat.match(value):752 raise InvalidHeader("Invalid return character or leading space in header: %s" % name)753754def urldefragauth(url):755 """756 Given a url remove the fragment and the authentication part757 """
9 unmodified lines
modified:tests/test_requests.py+42 added-1 removed
21 unmodified lines
22from requests.cookies import cookiejar_from_dict, morsel_to_cookie23from requests.exceptions import (24 ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,25 MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,26 ProxyError)26 ProxyError, InvalidHeader)27from requests.models import PreparedRequest28from requests.structures import CaseInsensitiveDict29from requests.sessions import SessionRedirectMixin30from requests.models import urlencode
1096 unmodified lines
1127 # we go.1128 assert 'unicode' in p.headers.keys()1129 assert 'byte' in p.headers.keys()11301131 def test_header_validation(self,httpbin):1132 """Ensure prepare_headers regex isn't flagging valid header contents."""1133 headers_ok = {'foo': 'bar baz qux',1134 'bar': '1',1135 'baz': '',1136 'qux': str.encode(u'fbbq')}1137 r = requests.get(httpbin('get'), headers=headers_ok)1138 assert r.request.headers['foo'] == headers_ok['foo']11391140 def test_header_no_return_chars(self, httpbin):1141 """Ensure that a header containing return character sequences raise an1142 exception. Otherwise, multiple headers are created from single string.1143 """1144 headers_ret = {'foo': 'bar\r\nbaz: qux'}1145 headers_lf = {'foo': 'bar\nbaz: qux'}1146 headers_cr = {'foo': 'bar\rbaz: qux'}11471148 # Test for newline1149 with pytest.raises(InvalidHeader):1150 r = requests.get(httpbin('get'), headers=headers_ret)1151 # Test for line feed1152 with pytest.raises(InvalidHeader):1153 r = requests.get(httpbin('get'), headers=headers_lf)1154 # Test for carriage return1155 with pytest.raises(InvalidHeader):1156 r = requests.get(httpbin('get'), headers=headers_cr)11571158 def test_header_no_leading_space(self, httpbin):1159 """Ensure headers containing leading whitespace raise1160 InvalidHeader Error before sending.1161 """1162 headers_space = {'foo': ' bar'}1163 headers_tab = {'foo': ' bar'}11641165 # Test for whitespace1166 with pytest.raises(InvalidHeader):1167 r = requests.get(httpbin('get'), headers=headers_space)1168 # Test for tab1169 with pytest.raises(InvalidHeader):1170 r = requests.get(httpbin('get'), headers=headers_tab)11711172 @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))1173 def test_can_send_objects_with_files(self, httpbin, files):1174 data = {'a': 'this is a string'}1175 files = {'b': files}
584 unmodified lines
modified:AUTHORS.rst+1 added
164 unmodified lines
165- Brian Samek (`@bsamek <https://github.com/bsamek>`_)166- Dmitry Dygalo (`@Stranger6667 <https://github.com/Stranger6667>`_)167- piotrjurkiewicz168- Jesse Shapiro <jesse@jesseshapiro.net> (`@haikuginger <https://github.com/haikuginger>`_)169- Nate Prewitt <nate.prewitt@gmail.com> (`@nateprewitt <https://github.com/nateprewitt>`_)