Python: fix CERTIFICATE_VERIFY_FAILED properly

Python often ships its own CA certificates and does not look into the operating system’s store. A company CA that works in the browser is therefore unknown to Python.

The message

ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed:
  unable to get local issuer certificate (_ssl.c:1006)

The suffix gives away the cause: unable to get local issuer certificate means the CA is unknown or an intermediate is missing. self-signed certificate in certificate chain points to a company CA or a TLS proxy. certificate has expired is an expired certificate.

Where Python gets its CAs

Check the server first

If the server does not deliver an intermediate, every client without a download function fails. Python downloads nothing. Check the site in the SSL check; if the chain is missing, it belongs on the server.

Solutions

1. Use the system store (recommended). If the company CA is distributed to the operating system, use the truststore package (Python 3.10+):

pip install truststore

import truststore
truststore.inject_into_ssl()   # before the first requests/urllib call
import requests
requests.get("https://intranet.example.com")

2. Point to a CA file. For scripts and containers without code changes:

# requests
export REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt
# urllib, ssl, httpx
export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
# pip
pip config set global.cert /etc/ssl/certs/ca-certificates.crt

The file must contain all required CAs, not just the company CA. On Debian and Ubuntu /etc/ssl/certs/ca-certificates.crt is the system store including CAs you added with update-ca-certificates. On RHEL it is /etc/pki/tls/certs/ca-bundle.crt.

3. macOS with the python.org installer: run “Install Certificates.command” once in the /Applications/Python 3.x folder.

4. Outdated certifi: pip install --upgrade certifi if a newer public root is missing.

Not: verify=False

requests.get(url, verify=False) or PYTHONHTTPSVERIFY=0 switch validation off. Anyone on the network can then impersonate the server, credentials and tokens included. Acceptable for a quick test, not in code.

FAQ

Why does it work with curl but not with Python?

On Linux curl uses the system store, requests the bundled certifi. With truststore or REQUESTS_CA_BUNDLE both use the same CAs.

Can I just append the company CA to certifi?

Yes, to the file shown by python -m certifi. But every certifi update removes the change. A separate file with REQUESTS_CA_BUNDLE lasts longer.

Does this apply in Docker too?

Yes. Copy the CA to /usr/local/share/ca-certificates in the image, run update-ca-certificates and set REQUESTS_CA_BUNDLE to /etc/ssl/certs/ca-certificates.crt.

Sources and documentation