Merge pull request #1876 from dstufft/update-urllib3
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Update urllib3 to 9346c5c
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 2a6b835, d181577 · Browse files · 6 files·+152 added−32 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+152 added−32 removed
- other:+152 added−32 removed
Provenance
- Commit
a5b3719- Tree
712050a- Author
Kenneth Reitz <me@kennethreitz.org>- Committer
Kenneth Reitz <me@kennethreitz.org>- Parent 1
2a6b835- Parent 2
d181577
6 files changed+152 added−32 removed
modified:requests/packages/urllib3/contrib/pyopenssl.py+46 added-2 removed
1-'''SSL with SNI-support for Python 2.1+'''SSL with SNI_-support for Python 2.2 3 This needs the following packages installed:4 5 * pyOpenSSL (tested with 0.13)11 unmodified lines17 pass18 19 Now you can use :mod:`urllib3` as you normally would, and it will support SNI20 when the required modules are installed.21+22+Activating this module also has the positive side effect of disabling SSL/TLS23+encryption in Python 2 (see `CRIME attack`_).24+25+If you want to configure the default list of supported cipher suites, you can26+set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable.27+28+Module Variables29+----------------30+31+:var DEFAULT_SSL_CIPHER_LIST: The list of supported SSL/TLS cipher suites.32+ Default: ``EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA25633+ EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EDH+aRSA EECDH RC4 !aNULL !eNULL !LOW !3DES34+ !MD5 !EXP !PSK !SRP !DSS'``35+36+.. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication37+.. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)38+39 '''40 41 from ndg.httpsclient.ssl_peer_verification import SUBJ_ALT_NAME_SUPPORT24-from ndg.httpsclient.subj_alt_name import SubjectAltName42+from ndg.httpsclient.subj_alt_name import SubjectAltName as BaseSubjectAltName43 import OpenSSL.SSL44 from pyasn1.codec.der import decoder as der_decoder45+from pyasn1.type import univ, constraint46 from socket import _fileobject47 import ssl48 import select49 from cStringIO import StringIO18 unmodified lines68 ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER69 + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,70 }71 72+# Default SSL/TLS cipher list.73+# Recommendation by https://community.qualys.com/blogs/securitylabs/2013/08/05/74+# configuring-apache-nginx-and-openssl-for-forward-secrecy75+DEFAULT_SSL_CIPHER_LIST = 'EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM ' + \76+ 'EECDH+ECDSA+SHA256 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EDH+aRSA ' + \77+ 'EECDH RC4 !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS'78 79+80 orig_util_HAS_SNI = util.HAS_SNI81 orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket82 83 11 unmodified lines95 util.HAS_SNI = orig_util_HAS_SNI96 97 98 ### Note: This is a slightly bug-fixed version of same from ndg-httpsclient.99+class SubjectAltName(BaseSubjectAltName):100+ '''ASN.1 implementation for subjectAltNames support'''101+102+ # There is no limit to how many SAN certificates a certificate may have,103+ # however this needs to have some limit so we'll set an arbitrarily high104+ # limit.105+ sizeSpec = univ.SequenceOf.sizeSpec + \106+ constraint.ValueSizeConstraint(1, 1024)107+108+109+### Note: This is a slightly bug-fixed version of same from ndg-httpsclient.110 def get_subj_alt_name(peer_cert):111 # Search through extensions112 dns_name = []113 if not SUBJ_ALT_NAME_SUPPORT:252 unmodified lines366 ctx.load_verify_locations(ca_certs, None)367 except OpenSSL.SSL.Error as e:368 raise ssl.SSLError('bad ca_certs: %r' % ca_certs, e)369 370+ # Disable TLS compression to migitate CRIME attack (issue #309)371+ OP_NO_COMPRESSION = 0x20000372+ ctx.set_options(OP_NO_COMPRESSION)373+374+ # Set list of supported ciphersuites.375+ ctx.set_cipher_list(DEFAULT_SSL_CIPHER_LIST)376+377 cnx = OpenSSL.SSL.Connection(ctx, sock)378 cnx.set_tlsext_host_name(server_hostname)379 cnx.set_connect_state()380 while True:10 unmodified linesmodified:requests/packages/urllib3/connection.py+75 added-7 removed
6 unmodified lines7 import socket8 from socket import timeout as SocketTimeout9 10 try: # Python 311- from http.client import HTTPConnection, HTTPException11+ from http.client import HTTPConnection as _HTTPConnection, HTTPException12 except ImportError:13- from httplib import HTTPConnection, HTTPException13+ from httplib import HTTPConnection as _HTTPConnection, HTTPException14 15 class DummyConnection(object):16 "Used to detect a failed ConnectionCls import."17 pass5 unmodified lines23 class BaseSSLError(BaseException):24 pass25 26 try: # Python 327- from http.client import HTTPSConnection27+ from http.client import HTTPSConnection as _HTTPSConnection28 except ImportError:29- from httplib import HTTPSConnection29+ from httplib import HTTPSConnection as _HTTPSConnection30 31 import ssl32 BaseSSLError = ssl.SSLError33 10 unmodified lines44 resolve_ssl_version,45 ssl_wrap_socket,46 )47 48+49+port_by_scheme = {50+ 'http': 80,51+ 'https': 443,52+}53+54+55+class HTTPConnection(_HTTPConnection, object):56+ default_port = port_by_scheme['http']57+58+ # By default, disable Nagle's Algorithm.59+ tcp_nodelay = 160+61+ def _new_conn(self):62+ """ Establish a socket connection and set nodelay settings on it63+64+ :return: a new socket connection65+ """66+ try:67+ conn = socket.create_connection(68+ (self.host, self.port),69+ self.timeout,70+ self.source_address,71+ )72+ except AttributeError: # Python 2.673+ conn = socket.create_connection(74+ (self.host, self.port),75+ self.timeout,76+ )77+ conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY,78+ self.tcp_nodelay)79+ return conn80+81+ def _prepare_conn(self, conn):82+ self.sock = conn83+ if self._tunnel_host:84+ # TODO: Fix tunnel so it doesn't depend on self.sock state.85+ self._tunnel()86+87+ def connect(self):88+ conn = self._new_conn()89+ self._prepare_conn(conn)90+91+92+class HTTPSConnection(HTTPConnection):93+ default_port = port_by_scheme['https']94+95+ def __init__(self, host, port=None, key_file=None, cert_file=None,96+ strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,97+ source_address=None):98+ try:99+ HTTPConnection.__init__(self, host, port, strict, timeout, source_address)100+ except TypeError: # Python 2.6101+ HTTPConnection.__init__(self, host, port, strict, timeout)102+ self.key_file = key_file103+ self.cert_file = cert_file104+105+ def connect(self):106+ conn = self._new_conn()107+ self._prepare_conn(conn)108+ self.sock = ssl.wrap_socket(conn, self.key_file, self.cert_file)109+110+111 class VerifiedHTTPSConnection(HTTPSConnection):112 """113 Based on httplib.HTTPSConnection but wraps the socket with114 SSL certification.20 unmodified lines135 address=(self.host, self.port),136 timeout=self.timeout,137 )138 except SocketTimeout:76- raise ConnectTimeoutError(77- self, "Connection to %s timed out. (connect timeout=%s)" %78- (self.host, self.timeout))139+ raise ConnectTimeoutError(140+ self, "Connection to %s timed out. (connect timeout=%s)" %141+ (self.host, self.timeout))142 143+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY,144+ self.tcp_nodelay)145+146 resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs)147 resolved_ssl_version = resolve_ssl_version(self.ssl_version)148 149 # the _tunnel_host attribute was added in python 2.6.3 (via22 unmodified lines172 self.assert_hostname or self.host)173 174 175 if ssl:176+ # Make a copy for testing.177+ UnverifiedHTTPSConnection = HTTPSConnection178 HTTPSConnection = VerifiedHTTPSConnectionmodified:requests/packages/urllib3/connectionpool.py+19 added-15 removed
29 unmodified lines30 )31 from .packages.ssl_match_hostname import CertificateError32 from .packages import six33 from .connection import (34+ port_by_scheme,35 DummyConnection,36 HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,37 HTTPException, BaseSSLError,38 )12 unmodified lines51 log = logging.getLogger(__name__)52 53 _Default = object()54 54-port_by_scheme = {55- 'http': 80,56- 'https': 443,57-}58-59-55 ## Pool objects56 57 class ConnectionPool(object):58 """104 unmodified lines163 self.num_requests = 0164 165 def _new_conn(self):166 """172- Return a fresh :class:`httplib.HTTPConnection`.167+ Return a fresh :class:`HTTPConnection`.168 """169 self.num_connections += 1170 log.info("Starting new HTTP connection (%d): %s" %171 (self.num_connections, self.host))1 unmodified line173 extra_params = {}174 if not six.PY3: # Python 2175 extra_params['strict'] = self.strict176 182- return self.ConnectionCls(host=self.host, port=self.port,177+ conn = self.ConnectionCls(host=self.host, port=self.port,178 timeout=self.timeout.connect_timeout,179 **extra_params)180+ if self.proxy is not None:181+ # Enable Nagle's algorithm for proxies, to avoid packet182+ # fragmentation.183+ conn.tcp_nodelay = 0184+ return conn185 186 def _get_conn(self, timeout=None):187 """188 Get a connection. Will return a pooled connection if one is available.70 unmodified lines259 260 def _make_request(self, conn, method, url, timeout=_Default,261 **httplib_request_kw):262 """263- Perform a request on a given httplib connection object taken from our263+ Perform a request on a given urllib connection object taken from our264 pool.265 266 :param conn:267 a connection from one of our connection pools248 unmodified lines516 if retries == 0:517 raise518 519 except (HTTPException, SocketError) as e:520- if isinstance(e, SocketError) and self.proxy is not None:521- raise ProxyError('Cannot connect to proxy. '522- 'Socket error: %s.' % e)523-520 # Connection broken, discard. It will be replaced next _get_conn().521 conn = None522 # This is necessary so we can access e below523 err = e524 525 if retries == 0:526+ if isinstance(e, SocketError) and self.proxy is not None:527+ raise ProxyError('Cannot connect to proxy. '528+ 'Socket error: %s.' % e)529+ else:530- raise MaxRetryError(self, url, e)530+ raise MaxRetryError(self, url, e)531 532 finally:533 if release_conn:534 # Put the connection back to be reused. If the connection is29 unmodified lines564 Same as :class:`.HTTPConnectionPool`, but HTTPS.565 566 When Python is compiled with the :mod:`ssl` module, then567 :class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates,568- instead of :class:`httplib.HTTPSConnection`.568+ instead of :class:`.HTTPSConnection`.569 570 :class:`.VerifiedHTTPSConnection` uses one of ``assert_fingerprint``,571 ``assert_hostname`` and ``host`` in this order to verify connections.572 If ``assert_hostname`` is False, no verification is done.78 unmodified lines651 652 conn = self.ConnectionCls(host=actual_host, port=actual_port,653 timeout=self.timeout.connect_timeout,654 **extra_params)655+ if self.proxy is not None:656+ # Enable Nagle's algorithm for proxies, to avoid packet657+ # fragmentation.658+ conn.tcp_nodelay = 0659 660 return self._prepare_conn(conn)661 662 25 unmodified linesmodified:requests/packages/urllib3/filepost.py+5 added-6 removed
44 unmodified lines45 46 47 def iter_fields(fields):48 """49+ .. deprecated:: 1.650+51 Iterate over fields.52 51- .. deprecated ::53+ The addition of :class:`~urllib3.fields.RequestField` makes this function54+ obsolete. Instead, use :func:`iter_field_objects`, which returns55+ :class:`~urllib3.fields.RequestField` objects.56 53- The addition of `~urllib3.fields.RequestField` makes this function54- obsolete. Instead, use :func:`iter_field_objects`, which returns55- `~urllib3.fields.RequestField` objects, instead.56-57 Supports list of (k, v) tuples and dicts.58-58 """59 if isinstance(fields, dict):60 return ((k, v) for k, v in six.iteritems(fields))61 39 unmodified linesmodified:requests/packages/urllib3/poolmanager.py+2 added-2 removed
1 # urllib3/poolmanager.py2-# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)2+# Copyright 2008-2014 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 168 unmodified lines175 """176 Behaves just like :class:`PoolManager`, but sends all requests through177 the defined proxy, using the CONNECT method for HTTPS URLs.178 179- :param poxy_url:179+ :param proxy_url:180 The URL of the proxy to be used.181 182 :param proxy_headers:183 A dictionary contaning headers that will be sent to the proxy. In case75 unmodified linesmodified:requests/packages/urllib3/util.py+5 added
618 unmodified lines619 Hostname of the expected certificate620 """621 context = SSLContext(ssl_version)622 context.verify_mode = cert_reqs623+624+ # Disable TLS compression to migitate CRIME attack (issue #309)625+ OP_NO_COMPRESSION = 0x20000626+ context.options |= OP_NO_COMPRESSION627+628 if ca_certs:629 try:630 context.load_verify_locations(ca_certs)631 # Py32 raises IOError17 unmodified lines