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
Provenance
- Commit
bd9e8f2- Tree
8ea4d16- Author
Cory Benfield <lukasaoz@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
ebadf81- Parent 2
2669ab7
5 files changed+75 added−7 removed
modified:requests/exceptions.py+5 added-1 removed
78 unmodified lines79 """See defaults.py for valid schemas."""80 81 82 class InvalidURL(RequestException, ValueError):83- """ The URL provided was somehow invalid. """83+ """The URL provided was somehow invalid."""84 85 86+class InvalidHeader(RequestException, ValueError):87+ """The header value provided was somehow invalid."""88+89+90 class ChunkedEncodingError(RequestException):91 """The server declared chunked encoding but sent an invalid chunk."""92 93 25 unmodified linesmodified:requests/models.py+8 added-4 removed
25 unmodified lines26 ContentDecodingError, ConnectionError, StreamConsumedError)27 from .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)32 from .compat import (33 cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,34 is_py2, chardet, builtin_str, basestring)35 from .compat import json as complexjson367 unmodified lines403 404 def prepare_headers(self, headers):405 """Prepares the given HTTP headers."""406 407+ 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)] = value414 415 def prepare_body(self, data, files, json=None):416 """Prepares the given HTTP body data."""417 454 unmodified linesmodified:requests/utils.py+19 added-1 removed
25 unmodified lines26 builtin_str, getproxies, proxy_bypass, urlunparse,27 basestring)28 from .cookies import RequestsCookieJar, cookiejar_from_dict29 from .structures import CaseInsensitiveDict30-from .exceptions import InvalidURL, FileModeWarning30+from .exceptions import InvalidURL, InvalidHeader, FileModeWarning31 32 _hush_pyflakes = (RequestsCookieJar,)33 34 NETRC_FILES = ('.netrc', '_netrc')696 unmodified lines731 out = string.decode(encoding)732 733 return out734 735+# 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]*$|^$')738 739+def check_header_validity(header):740+ """Verifies that header value doesn't contain leading whitespace or741+ return characters. This prevents unintended header injection.742+743+ :param header: tuple, in the format (name, value).744+ """745+ name, value = header746+747+ 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)753+754 def urldefragauth(url):755 """756 Given a url remove the fragment and the authentication part757 """9 unmodified linesmodified:tests/test_requests.py+42 added-1 removed
21 unmodified lines22 from requests.cookies import cookiejar_from_dict, morsel_to_cookie23 from requests.exceptions import (24 ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,25 MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,26- ProxyError)26+ ProxyError, InvalidHeader)27 from requests.models import PreparedRequest28 from requests.structures import CaseInsensitiveDict29 from requests.sessions import SessionRedirectMixin30 from requests.models import urlencode1101 unmodified lines1132 # we go.1133 assert 'unicode' in p.headers.keys()1134 assert 'byte' in p.headers.keys()1135 1136+ 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']1144+1145+ 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'}1152+1153+ # 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)1162+1163+ 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'}1169+1170+ # 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)1176+1177 @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 linesmodified:AUTHORS.rst+1 added
164 unmodified lines165 - 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>`_)