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
Provenance
- Commit
5b5ffc9- Tree
53973e0- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
75703d5- Parent 2
d7908a9
4 files changed+248 added−16 removed
added:requests/packages/urllib3/contrib/pyopenssl.py+167 added
1+'''SSL with SNI-support for Python 2.2+3+This needs the following packages installed:4+5+* pyOpenSSL (tested with 0.13)6+* ndg-httpsclient (tested with 0.3.2)7+* pyasn1 (tested with 0.1.6)8+9+To activate it call :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3`.10+This can be done in a ``sitecustomize`` module, or at any other time before11+your application begins using ``urllib3``, like this::12+13+ try:14+ import urllib3.contrib.pyopenssl15+ urllib3.contrib.pyopenssl.inject_into_urllib3()16+ except ImportError:17+ 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+23+from ndg.httpsclient.ssl_peer_verification import (ServerSSLCertVerification,24+ SUBJ_ALT_NAME_SUPPORT)25+from ndg.httpsclient.subj_alt_name import SubjectAltName26+import OpenSSL.SSL27+from pyasn1.codec.der import decoder as der_decoder28+from socket import _fileobject29+import ssl30+31+from .. import connectionpool32+from .. import util33+34+__all__ = ['inject_into_urllib3', 'extract_from_urllib3']35+36+# SNI only *really* works if we can read the subjectAltName of certificates.37+HAS_SNI = SUBJ_ALT_NAME_SUPPORT38+39+# 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+}51+52+53+orig_util_HAS_SNI = util.HAS_SNI54+orig_connectionpool_ssl_wrap_socket = connectionpool.ssl_wrap_socket55+56+57+def inject_into_urllib3():58+ 'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.'59+60+ connectionpool.ssl_wrap_socket = ssl_wrap_socket61+ util.HAS_SNI = HAS_SNI62+63+64+def extract_from_urllib3():65+ 'Undo monkey-patching by :func:`inject_into_urllib3`.'66+67+ connectionpool.ssl_wrap_socket = orig_connectionpool_ssl_wrap_socket68+ util.HAS_SNI = orig_util_HAS_SNI69+70+71+### Note: This is a slightly bug-fixed version of same from ndg-httpsclient.72+def get_subj_alt_name(peer_cert):73+ # Search through extensions74+ dns_name = []75+ if not SUBJ_ALT_NAME_SUPPORT:76+ return dns_name77+78+ 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+ continue84+85+ # 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)89+90+ 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()))98+99+ return dns_name100+101+102+class WrappedSocket(object):103+ '''API-compatibility wrapper for Python OpenSSL's Connection-class.'''104+105+ def __init__(self, connection, socket):106+ self.connection = connection107+ self.socket = socket108+109+ def makefile(self, mode, bufsize=-1):110+ return _fileobject(self.connection, mode, bufsize)111+112+ def settimeout(self, timeout):113+ return self.socket.settimeout(timeout)114+115+ def sendall(self, data):116+ return self.connection.sendall(data)117+118+ def getpeercert(self, binary_form=False):119+ x509 = self.connection.get_peer_certificate()120+ if not x509:121+ raise ssl.SSLError('')122+123+ if binary_form:124+ return OpenSSL.crypto.dump_certificate(125+ OpenSSL.crypto.FILETYPE_ASN1,126+ x509)127+128+ 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+ }137+138+139+def _verify_callback(cnx, x509, err_no, err_depth, return_code):140+ return err_no == 0141+142+143+def 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)158+159+ 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)166+167+ return WrappedSocket(cnx, sock)modified:requests/packages/urllib3/connectionpool.py+27 added-11 removed
7 unmodified lines8 import socket9 import errno10 11 from socket import error as SocketError, timeout as SocketTimeout12-from .util import resolve_cert_reqs, resolve_ssl_version12+from .util import resolve_cert_reqs, resolve_ssl_version, assert_fingerprint13 14 try: # Python 315 from http.client import HTTPConnection, HTTPException16 from http.client import HTTP_PORT, HTTPS_PORT63 unmodified lines80 ca_certs = None81 ssl_version = None82 83 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):86 87 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_fingerprint93 94 def connect(self):95 # Add certificate verification96 sock = socket.create_connection((self.host, self.port), self.timeout)9 unmodified lines106 server_hostname=self.host,107 ssl_version=resolved_ssl_version)108 109 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)116 109-117 ## Pool objects118 119 class ConnectionPool(object):120 """387 unmodified lines508 When Python is compiled with the :mod:`ssl` module, then509 :class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates,510 instead of :class:`httplib.HTTPSConnection`.511 512+ :class:`.VerifiedHTTPSConnection` uses one of ``assert_fingerprint``,513+ ``assert_hostname`` and ``host`` in this order to verify connections.514+505- 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 """520 521 scheme = 'https'522 523 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):529 530 HTTPConnectionPool.__init__(self, host, port,531 strict, timeout, maxsize,532 block, headers)1 unmodified line534 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_fingerprint540 541 def _new_conn(self):542 """543 Return a fresh :class:`httplib.HTTPSConnection`.1 unmodified line545 self.num_connections += 1546 log.info("Starting new HTTPS connection (%d): %s"547 % (self.num_connections, self.host))548 535- 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 lines558 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)565 566 connection.ssl_version = self.ssl_version567 568 return connection27 unmodified linesmodified:requests/packages/urllib3/poolmanager.py+10 added-1 removed
21 unmodified lines22 }23 24 log = logging.getLogger(__name__)25 26+SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',27+ 'ssl_version')28 29+30 class PoolManager(RequestMethods):31 """32 Allows for arbitrary requests while transparently keeping track of33 necessary connection pools for you.35 unmodified lines69 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)78 79+ return pool_cls(host, port, **kwargs)80+81 def clear(self):82 """83 Empty our store of pools and direct them all to close.84 107 unmodified linesmodified:requests/packages/urllib3/util.py+44 added-4 removed
6 unmodified lines7 8 from base64 import b64encode9 from collections import namedtuple10 from socket import error as SocketError11+from hashlib import md5, sha112+from binascii import hexlify, unhexlify13 14 try:15 from select import poll, POLLIN16 except ImportError: # `poll` doesn't exist on OSX and other platforms7 unmodified lines24 SSLContext = None25 HAS_SNI = False26 27 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?31 except ImportError:32 pass33 34 35 from .packages import six34-from .exceptions import LocationParseError36+from .exceptions import LocationParseError, SSLError37 38 39 class Url(namedtuple('Url', ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'])):40 """192 unmodified lines233 234 return headers235 236 235-def is_connection_dropped(conn):237+def is_connection_dropped(conn): # Platform-specific238 """239 Returns True if the connection is dropped and should be closed.240 241 :param conn:5 unmodified lines247 sock = getattr(conn, 'sock', False)248 if not sock: # Platform-specific: AppEngine249 return False250 249- if not poll: # Platform-specific251+ if not poll:252 if not select: # Platform-specific: AppEngine253 return False254 255 try:47 unmodified lines303 return res304 305 return candidate306 307+308+def assert_fingerprint(cert, fingerprint):309+ """310+ Checks if given fingerprint matches the supplied certificate.311+312+ :param cert:313+ Certificate as bytes object.314+ :param fingerprint:315+ Fingerprint as string of hexdigits, can be interspersed by colons.316+ """317+318+ # Maps the length of a digest to a possible hash function producing319+ # this digest.320+ hashfunc_map = {321+ 16: md5,322+ 20: sha1323+ }324+325+ fingerprint = fingerprint.replace(':', '').lower()326+327+ digest_length, rest = divmod(len(fingerprint), 2)328+329+ if rest or digest_length not in hashfunc_map:330+ raise SSLError('Fingerprint is of invalid length.')331+332+ # We need encode() here for py32; works on py2 and p33.333+ fingerprint_bytes = unhexlify(fingerprint.encode())334+335+ hashfunc = hashfunc_map[digest_length]336+337+ cert_digest = hashfunc(cert).digest()338+339+ 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)))343+344+345 if 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