Skip to content

Instantly share code, notes, and snippets.

@qlixed
Last active August 19, 2021 19:02
Show Gist options
  • Save qlixed/d3d2cd54299bfd39f1fabefd68743889 to your computer and use it in GitHub Desktop.
Save qlixed/d3d2cd54299bfd39f1fabefd68743889 to your computer and use it in GitHub Desktop.
A python requests HTTPS Adapter that load the default system certificates to authenticate connections
import ssl
from requests.adapters import HTTPAdapter
"""
HTTPSWithSysCerts:
Allows the validation of a https connection with the System installed CAs.
This help you to avoid the "verify=False" option and allows to check any
Local installed certificates, including the manually installed ones, like
tipical internal corporate CA.
Usage:
from https_with_syscerts import HTTPSWithSysCerts
import requests
s = requests.Session()
s.mount('https://', HTTPSWithSysCerts())
You can add any particual option to limit the negotiations using specific
TLS Versions and all that stuff like the example in:
https://docs.python-requests.org/en/master/user/advanced/#example-specific-ssl-version
I think that is a better alternative to the usage of certifi module as with
this Adapter:
- BAU: You don't need to update certifi or add it as an extra dependency
- You forget about to ship or download a custom CA when your clients run
this scripts in a environment that already have the cert installed. Super
useful for internal corporate CAs.
- Let you enjoy (?) the benefit of the usage of a HTTPS connection: Validate the
Server certificate to ensure that you're not connected to a "malicious" site.
- Works in any platform: Linux, Mac, Windows, etc. I Personally test it on Linux
and Windows.
Yeah the name is horrible, I know.
"""
class HTTPSWithSysCerts(HTTPAdapter):
"""
HTTPSWithSysCerts: An HTTPS adapter that uses the local installed certificates
to validate connections.
It uses the default ssl context that loads the system default certificates from
the system certificate store.
"""
def init_poolmanager(self, *args, **kwargs):
"""
Add a ssl_context with the system default certificates
to the HTTPAdapter that allow to check server certificates.
"""
# Create a default context:
context = ssl.create_default_context()
# Load the system certificates:
context.load_default_certs()
# Customize the ssl_context of the connection pool:
kwargs["ssl_context"] = context
# Contine with the Adaptor initizliation.
super().init_poolmanager(*args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment