Ignore certificate validation with urllib3

前端 未结 3 888
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 07:14

I\'m using urllib3 against private services that have self signed certificates. Is there any way to have urllib3 ignore the certificate errors and make the request anyways?<

相关标签:
3条回答
  • 2020-12-06 07:39

    Try following code:

    import urllib3
    c = urllib3.HTTPSConnectionPool('10.0.3.168', port=9001, cert_reqs='CERT_NONE',
                                    assert_hostname=False)
    c.request('GET', '/')
    

    See Setting assert_hostname to False will disable SSL hostname verification

    0 讨论(0)
  • 2020-12-06 07:41

    Try to instanciate your connection pool this way:

    HTTPSConnectionPool(self.host, self.port, cert_reqs=ssl.CERT_NONE)
    

    or this way:

    HTTPSConnectionPool(self.host, self.port, cert_reqs='CERT_NONE')
    

    Source: https://github.com/shazow/urllib3/blob/master/test/with_dummyserver/test_https.py


    EDIT (after seeing your edit):

    It looks like the remote host didn't send a certificate (is it possible?). This is the code (from urllib3) which raised an exception:

    def match_hostname(cert, hostname):
        """Verify that *cert* (in decoded format as returned by
    SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
    are mostly followed, but IP addresses are not accepted for *hostname*.
    
    CertificateError is raised on failure. On success, the function
    returns nothing.
    """
        if not cert:
            raise ValueError("empty or no certificate")
    

    So it looks like cert is empty, which means that self.sock.getpeercert() returned an empty string.

    0 讨论(0)
  • 2020-12-06 07:51

    I found the answer to my problem. The urllib3 documentation does not, in fact, completely explain how to suppress SSL certificate validation. What is missing is a reference to ssl.CERT_NONE.

    My code has a boolean, ssl_verify, to indicate whether or not I want SSL validation. The code now looks like this:

    import ssl
    import urllib3
    
    #
    #
    #
        if (ssl_verify):
            cert_reqs = ssl.CERT_REQUIRED
        else:
            cert_reqs = ssl.CERT_NONE
            urllib3.disable_warnings()
    
        http = urllib3.PoolManager(cert_reqs = cert_reqs)
    
        auth_url = f'https://{fmc_ip}/api/fmc_platform/v1/auth/generatetoken'
        type = {'Content-Type': 'application/json'}
    
        auth = urllib3.make_headers(basic_auth=f'{username}:{password}')
        headers = { **type, **auth }
    
        resp = http.request('POST',
                        auth_url,
                        headers=headers,
                        timeout=10.0)
    
    0 讨论(0)
提交回复
热议问题