requests icon indicating copy to clipboard operation
requests copied to clipboard

python context.verify_mode is ignored by requests module

Open revit13 opened this issue 3 years ago • 1 comments
trafficstars

In the following code the response contains ssl error SSL: CERTIFICATE_VERIFY_FAILED although the default verify_mode ssl.CERT_NONE is set in the context by calling context=create_ssl_context() as hown below. I expected that I to get no ssl error.

It seems that verify_mode in the context is ignored by the requests module. It is not clear to me what attributes from the context are not ignored by the requests module? will it take context.minimum_version? Thanks

Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)')))

def create_ssl_context(verify_mode=ssl.CERT_NONE,
                   key_file=None, cert_file=None,
                   cafile=None,
                   tls_min_version=None):
    context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    context.verify_mode = verify_mode
    if tls_min_version:
        context.minimum_version = tls_min_version
    if key_file or cert_file:
        context.load_cert_chain(cert_file, key_file)
    if cafile:
        context.load_verify_locations(cafile)
    else:
        context.set_default_verify_paths()
    return context

class SSLContextAdapter(requests.adapters.HTTPAdapter):
   def __init__(self, ssl_context=None, **kwargs):
      self.ssl_context = ssl_context
      super().__init__(**kwargs)

   def init_poolmanager(self, *args, **kwargs):
      kwargs['ssl_context'] = self.ssl_context
      return super(SSLContextAdapter, self).init_poolmanager(*args, **kwargs)


def client_side(context, hostname, data, headers):
  s = requests.Session()
  context = create_ssl_context()
  s.mount('https://', SSLContextAdapter(context))
  s.mount('http://', SSLContextAdapter(context))
  print(context.verify_mode)
  response = s.post(hostname, data=data, headers=headers)
  print(response.text)

revit13 avatar Oct 06 '22 19:10 revit13

I identified the issue it is that the kwargs argument sends verify as True despite the adapter's verify_mode is is set to None. The solution was to add a check to disable SSL certificate verification when the adapter's ssl_context.verify_mode is set to ssl.CERT_NONE, by setting the verify parameter to False in the kwargs argument. Check the following branch.

eth7 avatar Apr 14 '23 18:04 eth7