Skip to content
Myr

Merge pull request #1268 from t-8ch/update_urllib3

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

update vendored urllib3

authored by Kenneth Reitz · committed by Kenneth Reitz · parents 75703d5, d7908a9 · Browse files · 4 files+248 added−16 removed
This commit

State

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

Diff stats

4 files+248 added−16 removed

  • other:+248 added−16 removed

4 files+248 added−16 removed

added:requests/packages/urllib3/contrib/pyopenssl.py+167 added
1'''SSL with SNI-support for Python 2.23This needs the following packages installed:45* pyOpenSSL (tested with 0.13)6* ndg-httpsclient (tested with 0.3.2)7* pyasn1 (tested with 0.1.6)89To activate it call :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3`.10This can be done in a ``sitecustomize`` module, or at any other time before11your application begins using ``urllib3``, like this::1213 try:14 import urllib3.contrib.pyopenssl15 urllib3.contrib.pyopenssl.inject_into_urllib3()16 except ImportError:17 pass1819Now you can use :mod:`urllib3` as you normally would, and it will support SNI20when the required modules are installed.21'''2223from ndg.httpsclient.ssl_peer_verification import (ServerSSLCertVerification,24 SUBJ_ALT_NAME_SUPPORT)25from ndg.httpsclient.subj_alt_name import SubjectAltName26import OpenSSL.SSL27from pyasn1.codec.der import decoder as der_decoder28from socket import _fileobject29import ssl3031from .. import connectionpool32from .. import util3334__all__ = ['inject_into_urllib3', 'extract_from_urllib3']3536# SNI only *really* works if we can read the subjectAltName of certificates.37HAS_SNI = SUBJ_ALT_NAME_SUPPORT3839# Map from urllib3 to PyOpenSSL compatible parameter-values.40_openssl_versions = {41 ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD,42 ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD,43 ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,44}45_openssl_verify = {46 ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,47 ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,48 ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER49 + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,50}515253orig_util_HAS_SNI = util.HAS_SNI54orig_connectionpool_ssl_wrap_socket = connectionpool.ssl_wrap_socket555657def inject_into_urllib3():58 'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.'5960 connectionpool.ssl_wrap_socket = ssl_wrap_socket61 util.HAS_SNI = HAS_SNI626364def extract_from_urllib3():65 'Undo monkey-patching by :func:`inject_into_urllib3`.'6667 connectionpool.ssl_wrap_socket = orig_connectionpool_ssl_wrap_socket68 util.HAS_SNI = orig_util_HAS_SNI697071### Note: This is a slightly bug-fixed version of same from ndg-httpsclient.72def get_subj_alt_name(peer_cert):73 # Search through extensions74 dns_name = []75 if not SUBJ_ALT_NAME_SUPPORT:76 return dns_name7778 general_names = SubjectAltName()79 for i in range(peer_cert.get_extension_count()):80 ext = peer_cert.get_extension(i)81 ext_name = ext.get_short_name()82 if ext_name != 'subjectAltName':83 continue8485 # PyOpenSSL returns extension data in ASN.1 encoded form86 ext_dat = ext.get_data()87 decoded_dat = der_decoder.decode(ext_dat,88 asn1Spec=general_names)8990 for name in decoded_dat:91 if not isinstance(name, SubjectAltName):92 continue93 for entry in range(len(name)):94 component = name.getComponentByPosition(entry)95 if component.getName() != 'dNSName':96 continue97 dns_name.append(str(component.getComponent()))9899 return dns_name100101102class WrappedSocket(object):103 '''API-compatibility wrapper for Python OpenSSL's Connection-class.'''104105 def __init__(self, connection, socket):106 self.connection = connection107 self.socket = socket108109 def makefile(self, mode, bufsize=-1):110 return _fileobject(self.connection, mode, bufsize)111112 def settimeout(self, timeout):113 return self.socket.settimeout(timeout)114115 def sendall(self, data):116 return self.connection.sendall(data)117118 def getpeercert(self, binary_form=False):119 x509 = self.connection.get_peer_certificate()120 if not x509:121 raise ssl.SSLError('')122123 if binary_form:124 return OpenSSL.crypto.dump_certificate(125 OpenSSL.crypto.FILETYPE_ASN1,126 x509)127128 return {129 'subject': (130 (('commonName', x509.get_subject().CN),),131 ),132 'subjectAltName': [133 ('DNS', value)134 for value in get_subj_alt_name(x509)135 ]136 }137138139def _verify_callback(cnx, x509, err_no, err_depth, return_code):140 return err_no == 0141142143def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,144 ca_certs=None, server_hostname=None,145 ssl_version=None):146 ctx = OpenSSL.SSL.Context(_openssl_versions[ssl_version])147 if certfile:148 ctx.use_certificate_file(certfile)149 if keyfile:150 ctx.use_privatekey_file(keyfile)151 if cert_reqs != ssl.CERT_NONE:152 ctx.set_verify(_openssl_verify[cert_reqs], _verify_callback)153 if ca_certs:154 try:155 ctx.load_verify_locations(ca_certs, None)156 except OpenSSL.SSL.Error as e:157 raise ssl.SSLError('bad ca_certs: %r' % ca_certs, e)158159 cnx = OpenSSL.SSL.Connection(ctx, sock)160 cnx.set_tlsext_host_name(server_hostname)161 cnx.set_connect_state()162 try:163 cnx.do_handshake()164 except OpenSSL.SSL.Error as e:165 raise ssl.SSLError('bad handshake', e)166167 return WrappedSocket(cnx, sock)
modified:requests/packages/urllib3/connectionpool.py+27 added-11 removed
7 unmodified lines
8import socket9import errno1011from socket import error as SocketError, timeout as SocketTimeout12from .util import resolve_cert_reqs, resolve_ssl_version12from .util import resolve_cert_reqs, resolve_ssl_version, assert_fingerprint1314try: # Python 315 from http.client import HTTPConnection, HTTPException16 from http.client import HTTP_PORT, HTTPS_PORT
63 unmodified lines
80 ca_certs = None81 ssl_version = None8283 def set_cert(self, key_file=None, cert_file=None,84 cert_reqs=None, ca_certs=None):84 cert_reqs=None, ca_certs=None,85 assert_hostname=None, assert_fingerprint=None):8687 self.key_file = key_file88 self.cert_file = cert_file89 self.cert_reqs = cert_reqs90 self.ca_certs = ca_certs91 self.assert_hostname = assert_hostname92 self.assert_fingerprint = assert_fingerprint9394 def connect(self):95 # Add certificate verification96 sock = socket.create_connection((self.host, self.port), self.timeout)
9 unmodified lines
106 server_hostname=self.host,107 ssl_version=resolved_ssl_version)108109 if resolved_cert_reqs != ssl.CERT_NONE:110 if self.assert_fingerprint:111 assert_fingerprint(self.sock.getpeercert(binary_form=True),112 self.assert_fingerprint)113 else:107 match_hostname(self.sock.getpeercert(), self.host)114 match_hostname(self.sock.getpeercert(),115 self.assert_hostname or self.host)116109117## Pool objects118119class ConnectionPool(object):120 """
387 unmodified lines
508 When Python is compiled with the :mod:`ssl` module, then509 :class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates,510 instead of :class:`httplib.HTTPSConnection`.511512 :class:`.VerifiedHTTPSConnection` uses one of ``assert_fingerprint``,513 ``assert_hostname`` and ``host`` in this order to verify connections.514505 The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``, and ``ssl_version``506 are only used if :mod:`ssl` is available and are fed into507 :meth:`urllib3.util.ssl_wrap_socket` to upgrade the connection socket into an SSL socket.515 The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs`` and516 ``ssl_version`` are only used if :mod:`ssl` is available and are fed into517 :meth:`urllib3.util.ssl_wrap_socket` to upgrade the connection socket518 into an SSL socket.519 """520521 scheme = 'https'522523 def __init__(self, host, port=None,524 strict=False, timeout=None, maxsize=1,525 block=False, headers=None,515 key_file=None, cert_file=None,516 cert_reqs=None, ca_certs=None, ssl_version=None):526 key_file=None, cert_file=None, cert_reqs=None,527 ca_certs=None, ssl_version=None,528 assert_hostname=None, assert_fingerprint=None):529530 HTTPConnectionPool.__init__(self, host, port,531 strict, timeout, maxsize,532 block, headers)
1 unmodified line
534 self.cert_file = cert_file535 self.cert_reqs = cert_reqs536 self.ca_certs = ca_certs537 self.ssl_version = ssl_version538 self.assert_hostname = assert_hostname539 self.assert_fingerprint = assert_fingerprint540541 def _new_conn(self):542 """543 Return a fresh :class:`httplib.HTTPSConnection`.
1 unmodified line
545 self.num_connections += 1546 log.info("Starting new HTTPS connection (%d): %s"547 % (self.num_connections, self.host))548535 if not ssl: # Platform-specific: Python compiled without +ssl549 if not ssl: # Platform-specific: Python compiled without +ssl550 if not HTTPSConnection or HTTPSConnection is object:551 raise SSLError("Can't connect to HTTPS URL because the SSL "552 "module is not available.")553
4 unmodified lines
558 connection = VerifiedHTTPSConnection(host=self.host,559 port=self.port,560 strict=self.strict)561 connection.set_cert(key_file=self.key_file, cert_file=self.cert_file,548 cert_reqs=self.cert_reqs, ca_certs=self.ca_certs)562 cert_reqs=self.cert_reqs, ca_certs=self.ca_certs,563 assert_hostname=self.assert_hostname,564 assert_fingerprint=self.assert_fingerprint)565566 connection.ssl_version = self.ssl_version567568 return connection
27 unmodified lines
modified:requests/packages/urllib3/poolmanager.py+10 added-1 removed
21 unmodified lines
22}2324log = logging.getLogger(__name__)2526SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',27 'ssl_version')282930class PoolManager(RequestMethods):31 """32 Allows for arbitrary requests while transparently keeping track of33 necessary connection pools for you.
35 unmodified lines
69 by :meth:`connection_from_url` and companion methods. It is intended70 to be overridden for customization.71 """72 pool_cls = pool_classes_by_scheme[scheme]70 return pool_cls(host, port, **self.connection_pool_kw)73 kwargs = self.connection_pool_kw74 if scheme == 'http':75 kwargs = self.connection_pool_kw.copy()76 for kw in SSL_KEYWORDS:77 kwargs.pop(kw, None)7879 return pool_cls(host, port, **kwargs)8081 def clear(self):82 """83 Empty our store of pools and direct them all to close.84
107 unmodified lines
modified:requests/packages/urllib3/util.py+44 added-4 removed
6 unmodified lines
78from base64 import b64encode9from collections import namedtuple10from socket import error as SocketError11from hashlib import md5, sha112from binascii import hexlify, unhexlify1314try:15 from select import poll, POLLIN16except ImportError: # `poll` doesn't exist on OSX and other platforms
7 unmodified lines
24 SSLContext = None25 HAS_SNI = False2627 import ssl26 from ssl import wrap_socket, CERT_NONE, SSLError, PROTOCOL_SSLv2328 from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv2329 from ssl import SSLContext # Modern SSL?30 from ssl import HAS_SNI # Has SNI?31except ImportError:32 pass333435from .packages import six34from .exceptions import LocationParseError36from .exceptions import LocationParseError, SSLError373839class Url(namedtuple('Url', ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'])):40 """
192 unmodified lines
233234 return headers235236235def is_connection_dropped(conn):237def is_connection_dropped(conn): # Platform-specific238 """239 Returns True if the connection is dropped and should be closed.240241 :param conn:
5 unmodified lines
247 sock = getattr(conn, 'sock', False)248 if not sock: # Platform-specific: AppEngine249 return False250249 if not poll: # Platform-specific251 if not poll:252 if not select: # Platform-specific: AppEngine253 return False254255 try:
47 unmodified lines
303 return res304305 return candidate306307308def assert_fingerprint(cert, fingerprint):309 """310 Checks if given fingerprint matches the supplied certificate.311312 :param cert:313 Certificate as bytes object.314 :param fingerprint:315 Fingerprint as string of hexdigits, can be interspersed by colons.316 """317318 # Maps the length of a digest to a possible hash function producing319 # this digest.320 hashfunc_map = {321 16: md5,322 20: sha1323 }324325 fingerprint = fingerprint.replace(':', '').lower()326327 digest_length, rest = divmod(len(fingerprint), 2)328329 if rest or digest_length not in hashfunc_map:330 raise SSLError('Fingerprint is of invalid length.')331332 # We need encode() here for py32; works on py2 and p33.333 fingerprint_bytes = unhexlify(fingerprint.encode())334335 hashfunc = hashfunc_map[digest_length]336337 cert_digest = hashfunc(cert).digest()338339 if not cert_digest == fingerprint_bytes:340 raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'341 .format(hexlify(fingerprint_bytes),342 hexlify(cert_digest)))343344345if SSLContext is not None: # Python 3.2+346 def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,347 ca_certs=None, server_hostname=None,348 ssl_version=None):
30 unmodified lines