Skip to content
Myr

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

6 files+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.23This needs the following packages installed:45* pyOpenSSL (tested with 0.13)
11 unmodified lines
17 pass1819Now you can use :mod:`urllib3` as you normally would, and it will support SNI20when the required modules are installed.2122Activating this module also has the positive side effect of disabling SSL/TLS23encryption in Python 2 (see `CRIME attack`_).2425If you want to configure the default list of supported cipher suites, you can26set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable.2728Module Variables29----------------3031: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'``3536.. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication37.. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)3839'''4041from ndg.httpsclient.ssl_peer_verification import SUBJ_ALT_NAME_SUPPORT24from ndg.httpsclient.subj_alt_name import SubjectAltName42from ndg.httpsclient.subj_alt_name import SubjectAltName as BaseSubjectAltName43import OpenSSL.SSL44from pyasn1.codec.der import decoder as der_decoder45from pyasn1.type import univ, constraint46from socket import _fileobject47import ssl48import select49from cStringIO import StringIO
18 unmodified lines
68 ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER69 + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,70}7172# 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-secrecy75DEFAULT_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'787980orig_util_HAS_SNI = util.HAS_SNI81orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket8283
11 unmodified lines
95 util.HAS_SNI = orig_util_HAS_SNI969798### Note: This is a slightly bug-fixed version of same from ndg-httpsclient.99class SubjectAltName(BaseSubjectAltName):100 '''ASN.1 implementation for subjectAltNames support'''101102 # 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)107108109### Note: This is a slightly bug-fixed version of same from ndg-httpsclient.110def get_subj_alt_name(peer_cert):111 # Search through extensions112 dns_name = []113 if not SUBJ_ALT_NAME_SUPPORT:
252 unmodified lines
366 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)369370 # Disable TLS compression to migitate CRIME attack (issue #309)371 OP_NO_COMPRESSION = 0x20000372 ctx.set_options(OP_NO_COMPRESSION)373374 # Set list of supported ciphersuites.375 ctx.set_cipher_list(DEFAULT_SSL_CIPHER_LIST)376377 cnx = OpenSSL.SSL.Connection(ctx, sock)378 cnx.set_tlsext_host_name(server_hostname)379 cnx.set_connect_state()380 while True:
10 unmodified lines
modified:requests/packages/urllib3/connection.py+75 added-7 removed
6 unmodified lines
7import socket8from socket import timeout as SocketTimeout910try: # Python 311 from http.client import HTTPConnection, HTTPException11 from http.client import HTTPConnection as _HTTPConnection, HTTPException12except ImportError:13 from httplib import HTTPConnection, HTTPException13 from httplib import HTTPConnection as _HTTPConnection, HTTPException1415class DummyConnection(object):16 "Used to detect a failed ConnectionCls import."17 pass
5 unmodified lines
23 class BaseSSLError(BaseException):24 pass2526 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 _HTTPSConnection3031 import ssl32 BaseSSLError = ssl.SSLError33
10 unmodified lines
44 resolve_ssl_version,45 ssl_wrap_socket,46)474849port_by_scheme = {50 'http': 80,51 'https': 443,52}535455class HTTPConnection(_HTTPConnection, object):56 default_port = port_by_scheme['http']5758 # By default, disable Nagle's Algorithm.59 tcp_nodelay = 16061 def _new_conn(self):62 """ Establish a socket connection and set nodelay settings on it6364 :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 conn8081 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()8687 def connect(self):88 conn = self._new_conn()89 self._prepare_conn(conn)909192class HTTPSConnection(HTTPConnection):93 default_port = port_by_scheme['https']9495 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_file104105 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)109110111class VerifiedHTTPSConnection(HTTPSConnection):112 """113 Based on httplib.HTTPSConnection but wraps the socket with114 SSL certification.
20 unmodified lines
135 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))142143 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY,144 self.tcp_nodelay)145146 resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs)147 resolved_ssl_version = resolve_ssl_version(self.ssl_version)148149 # the _tunnel_host attribute was added in python 2.6.3 (via
22 unmodified lines
172 self.assert_hostname or self.host)173174175if ssl:176 # Make a copy for testing.177 UnverifiedHTTPSConnection = HTTPSConnection178 HTTPSConnection = VerifiedHTTPSConnection
modified:requests/packages/urllib3/connectionpool.py+19 added-15 removed
29 unmodified lines
30)31from .packages.ssl_match_hostname import CertificateError32from .packages import six33from .connection import (34 port_by_scheme,35 DummyConnection,36 HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,37 HTTPException, BaseSSLError,38)
12 unmodified lines
51log = logging.getLogger(__name__)5253_Default = object()5454port_by_scheme = {55 'http': 80,56 'https': 443,57}585955## Pool objects5657class ConnectionPool(object):58 """
104 unmodified lines
163 self.num_requests = 0164165 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 line
173 extra_params = {}174 if not six.PY3: # Python 2175 extra_params['strict'] = self.strict176182 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 conn185186 def _get_conn(self, timeout=None):187 """188 Get a connection. Will return a pooled connection if one is available.
70 unmodified lines
259260 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.265266 :param conn:267 a connection from one of our connection pools
248 unmodified lines
516 if retries == 0:517 raise518519 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)523520 # Connection broken, discard. It will be replaced next _get_conn().521 conn = None522 # This is necessary so we can access e below523 err = e524525 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)531532 finally:533 if release_conn:534 # Put the connection back to be reused. If the connection is
29 unmodified lines
564 Same as :class:`.HTTPConnectionPool`, but HTTPS.565566 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`.569570 :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 lines
651652 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 = 0659660 return self._prepare_conn(conn)661662
25 unmodified lines
modified:requests/packages/urllib3/filepost.py+5 added-6 removed
44 unmodified lines
454647def iter_fields(fields):48 """49 .. deprecated:: 1.65051 Iterate over fields.5251 .. 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.5653 The addition of `~urllib3.fields.RequestField` makes this function54 obsolete. Instead, use :func:`iter_field_objects`, which returns55 `~urllib3.fields.RequestField` objects, instead.5657 Supports list of (k, v) tuples and dicts.5858 """59 if isinstance(fields, dict):60 return ((k, v) for k, v in six.iteritems(fields))61
39 unmodified lines
modified: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 lines
175 """176 Behaves just like :class:`PoolManager`, but sends all requests through177 the defined proxy, using the CONNECT method for HTTPS URLs.178179 :param poxy_url:179 :param proxy_url:180 The URL of the proxy to be used.181182 :param proxy_headers:183 A dictionary contaning headers that will be sent to the proxy. In case
75 unmodified lines
modified:requests/packages/urllib3/util.py+5 added
618 unmodified lines
619 Hostname of the expected certificate620 """621 context = SSLContext(ssl_version)622 context.verify_mode = cert_reqs623624 # Disable TLS compression to migitate CRIME attack (issue #309)625 OP_NO_COMPRESSION = 0x20000626 context.options |= OP_NO_COMPRESSION627628 if ca_certs:629 try:630 context.load_verify_locations(ca_certs)631 # Py32 raises IOError
17 unmodified lines