Skip to content
Myr

Merge pull request #3366 from nateprewitt/2947-no-returns-in-header

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

check for headers containing return characters

authored by Cory Benfield · committed by GitHub · parents ebadf81, 2669ab7 · 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
454 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
1101 unmodified lines
1132 # we go.1133 assert 'unicode' in p.headers.keys()1134 assert 'byte' in p.headers.keys()11351136 def test_header_validation(self,httpbin):1137 """Ensure prepare_headers regex isn't flagging valid header contents."""1138 headers_ok = {'foo': 'bar baz qux',1139 'bar': '1',1140 'baz': '',1141 'qux': str.encode(u'fbbq')}1142 r = requests.get(httpbin('get'), headers=headers_ok)1143 assert r.request.headers['foo'] == headers_ok['foo']11441145 def test_header_no_return_chars(self, httpbin):1146 """Ensure that a header containing return character sequences raise an1147 exception. Otherwise, multiple headers are created from single string.1148 """1149 headers_ret = {'foo': 'bar\r\nbaz: qux'}1150 headers_lf = {'foo': 'bar\nbaz: qux'}1151 headers_cr = {'foo': 'bar\rbaz: qux'}11521153 # Test for newline1154 with pytest.raises(InvalidHeader):1155 r = requests.get(httpbin('get'), headers=headers_ret)1156 # Test for line feed1157 with pytest.raises(InvalidHeader):1158 r = requests.get(httpbin('get'), headers=headers_lf)1159 # Test for carriage return1160 with pytest.raises(InvalidHeader):1161 r = requests.get(httpbin('get'), headers=headers_cr)11621163 def test_header_no_leading_space(self, httpbin):1164 """Ensure headers containing leading whitespace raise1165 InvalidHeader Error before sending.1166 """1167 headers_space = {'foo': ' bar'}1168 headers_tab = {'foo': ' bar'}11691170 # Test for whitespace1171 with pytest.raises(InvalidHeader):1172 r = requests.get(httpbin('get'), headers=headers_space)1173 # Test for tab1174 with pytest.raises(InvalidHeader):1175 r = requests.get(httpbin('get'), headers=headers_tab)11761177 @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))1178 def test_can_send_objects_with_files(self, httpbin, files):1179 data = {'a': 'this is a string'}1180 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>`_)