From edff0b04f0195332bbdc859ec2816b75fec1df8a Mon Sep 17 00:00:00 2001 From: YQ Date: Wed, 17 Feb 2021 21:52:34 +0800 Subject: [PATCH] Update host_header_ssl.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. This also works for CNAME 2. I think host_header = request.headers.get('Host',None) is enouth,because request.headers is a CaseInsensitiveDict 3. I found that "server_hostname" must be set to make it work 4. Only ”https“ url need to do this --- requests_toolbelt/adapters/host_header_ssl.py | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/requests_toolbelt/adapters/host_header_ssl.py b/requests_toolbelt/adapters/host_header_ssl.py index f34ed1aa..23d615a3 100644 --- a/requests_toolbelt/adapters/host_header_ssl.py +++ b/requests_toolbelt/adapters/host_header_ssl.py @@ -14,30 +14,29 @@ class HostHeaderSSLAdapter(HTTPAdapter): A HTTPS Adapter for Python Requests that sets the hostname for certificate verification based on the Host header. - This allows requesting the IP address directly via HTTPS without getting + This allows requesting the IP address or CNAME directly via HTTPS without getting a "hostname doesn't match" exception. Example usage: >>> s.mount('https://', HostHeaderSSLAdapter()) - >>> s.get("https://93.184.216.34", headers={"Host": "example.org"}) - + >>> s.get("https://93.184.216.34/", headers={"Host": "example.org"}) + >>> s.get("https://cname.example.org/", headers={"Host": "example.org"}) """ def send(self, request, **kwargs): # HTTP headers are case-insensitive (RFC 7230) - host_header = None - for header in request.headers: - if header.lower() == "host": - host_header = request.headers[header] - break + # request.headers is a CaseInsensitiveDict + host_header = request.headers.get('Host',None) connection_pool_kwargs = self.poolmanager.connection_pool_kw - if host_header: + if request.url[:5] == "https" and host_header: connection_pool_kwargs["assert_hostname"] = host_header - elif "assert_hostname" in connection_pool_kwargs: + connection_pool_kwargs["server_hostname"] = host_header # SNI + else: # an assert_hostname from a previous request may have been left connection_pool_kwargs.pop("assert_hostname", None) + connection_pool_kwargs.pop("server_hostname", None) # SNI return super(HostHeaderSSLAdapter, self).send(request, **kwargs)