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
Provenance
- Commit
2669ab7- Tree
b847d97- Author
Nate Prewitt <Nate.Prewitt@gmail.com>- Committer
Nate Prewitt <Nate.Prewitt@gmail.com>- Parent
92fe51c
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 448 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 urlencode1096 unmodified lines1127 # we go.1128 assert 'unicode' in p.headers.keys()1129 assert 'byte' in p.headers.keys()1130 1131+ 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']1139+1140+ 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'}1147+1148+ # 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)1157+1158+ 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'}1164+1165+ # 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)1171+1172 @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 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>`_)