Manage Private CA file in Python


The private CA signed certificate can cause SSL error in Python if the it is not trusted. How to manage it? Well, it really depends on the Python module that you use. I will give a few examples that I have seen so far.

pip

Pip is the popular python package manage tool. To check which CA file it uses:

$ pip config list
global.cert='/Users/jackie/certs/ca-certs.pem'

Or check the pip.config file directly.

So that is the file you need to append to your private CA file, something like:

Corp Private Root CA
================
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----

And you also can change setting by doing:

$ pip config set global.cert <new_ca_file_path>

Ansible uri module

Ansible uri module is a handy module that allows you to make http calls. Currently it does not support self-defined CA file. But if you read the source code, underlying it uses the urllib to send the requests.

pip uses the default ca file, which can be found by using the ssl module.

$ python -c "import ssl; print(ssl.get_default_verify_paths())"

DefaultVerifyPaths(cafile='/Users/jackie/anaconda3/ssl/cert.pem', capath=None, openssl_cafile_env='SSL_CERT_FILE', openssl_cafile='/Users/jackie/anaconda3/ssl/cert.pem', openssl_capath_env='SSL_CERT_DIR', openssl_capath='/Users/jackie/anaconda3/ssl/certs')

In my case, /Users/jackie/anaconda3/ssl/cert.pem is the default CA file on my machine. So it is file I need to add the private CA .pem file to.

Also, you can change the default ca file by setting the system environment variable SSL_CERT_FILE

Requests module

Requests is an elegant and simple HTTP library for Python, built for human beings. It uses certifi to manage the certificates. And certifi has its own CA file, so if you use requests module. The private CA file has to be added into the CA file that is defined the certifi. Here is a example:

$ python -c "import certifi; print(certifi.where())"

/Users/jackie/anaconda3/lib/python3.7/site-packages/certifi/cacert.pem

So /Users/jackie/anaconda3/lib/python3.7/site-packages/certifi/cacert.pem is the file that I need to append my private CA .pem file to. Or just tell Requests to use the CA file that you define in the system environment variable REQUESTS_CA_BUNDLE

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s