177
import requests
data = {'foo':'bar'}
url = 'https://foo.com/bar'
r = requests.post(url, data=data)

If the URL uses a self signed certificate, this fails with

requests.exceptions.SSLError: [Errno 1] _ssl.c:507: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

I know that I can pass False to the verify parameter, like this:

r = requests.post(url, data=data, verify=False)

However, what I would like to do is point requests to a copy of the public key on disk and tell it to trust that certificate.

frlan
  • 6,950
  • 3
  • 31
  • 72
Matthew Moisen
  • 16,701
  • 27
  • 128
  • 231
  • http://stackoverflow.com/questions/10667960/python-requests-throwing-up-sslerror?rq=1 – Ajay May 22 '15 at 21:08
  • 3
    In some scenaria (notably load tests) it is important to bypass the check altogether as opposed to supplying a valid key for successful check. That's to save CPU cycles of which verification is hungry. So `verify=False` in combination with `import urllib3; urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)` might be a better option. – wick Nov 22 '22 at 11:19

11 Answers11

115

try:

r = requests.post(url, data=data, verify='/path/to/public_key.pem')
krock
  • 28,904
  • 13
  • 79
  • 85
  • 1
    Can you do the same and use client certificates at the same time? I'm getting problems with this. – user1156544 Jun 14 '19 at 14:46
  • 43
    Note that the .pem file you pass must include the server's certificate **and any intermediate certificates**. I lost a few hours trying to figure out why it didn't work after adding the server's cert. – ChrisBob Oct 15 '19 at 12:39
  • I added self signed certificate.pem, and it worked. – H S Rathore Nov 12 '19 at 04:38
  • 14
    This technique didn't work for me. I used `ssl.get_server_certificate` to download a certificate for `(self-signed.badssl.com, 443)`, saved that certificate to `cert.pem`, and then ran `requests.get('https://self-signed.badssl.com/', verify='cert.pem')` and it still failed with an SSL error (that certificate is self-signed). – Jason R. Coombs Nov 21 '19 at 03:31
  • 3
    @ChrisBob I can't thank you enough. Your comment is much more valuable than the accepted answers to the many questions about this (which only repeat what is in requests documentation). After pulling my hair for hours, your comment put me on the right direction... – Gaëtan de Menten Jan 15 '21 at 09:19
  • 22
    For reference (possibly for my future self), I had to download the certicicate as a .pem file by clicking on the lock icon in Firefox > Show Connection details > More information > View certificate > Download **"PEM (chain)"**. The (chain) is the important part that I was missing as the alternative "PEM (cert)" will **not** work with requests. – Gaëtan de Menten Jan 15 '21 at 09:28
  • @GaëtandeMenten, @krock, @H S Rathore or whoever was able to get this working: I was able to download domain.pem and domain-chain.pem and saved these under a directory /abc/def. When I trey `verify="/abc/def/domain.pem"` or `verify="/abc/def/domain-chain.pem"` or `verify="/abc/def"` I am still getting `ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)` Can you please help me find what am I missing? Can I keep these 2 .pem files under any ordinary directory and use that directory path or something specific needs to be done after downloading 2 .pem files? – 300 Oct 04 '21 at 18:53
  • BTW updated instructions for downloading certs using Firefox (from what I saw today): Click on "Lock" icon -> Click on ">" (Show Connection Details) -> Click "More Information" at the bottom of pop up window -> Click "View Certificate" button -> Next to text "Download" click on "PEM (cert)" and then "PEM (chain)" – 300 Oct 04 '21 at 21:50
  • 1
    @300: Sorry, I have no idea what's the problem in your case. I told everything I know about this (not much) in my comment above. – Gaëtan de Menten Oct 05 '21 at 18:45
  • 1
    @300: On second thought, are you sure the certificate validates correctly otherwise? If the certificate was issued by Let's Encrypt and you are using old openssl, it might be related to https://techcrunch.com/2021/09/21/lets-encrypt-root-expiry/ – Gaëtan de Menten Oct 05 '21 at 18:51
  • Thank you @GaëtandeMenten I'll try to find what I am missing and will post here. I think root certificate is not from Let's Encrypt – 300 Oct 06 '21 at 19:27
  • 1
    For those looking for the way to properly assemble a certificate chain in a PEM-file (note the order: THE ROOT IS AT LAST): -----BEGIN CERTIFICATE----- (Your Primary SSL certificate (eg. your server, your domain)) -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- (Your Intermediate certificate) -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- (Your Root certificate) -----END CERTIFICATE----- – booFar Jun 15 '22 at 12:51
55

The easiest is to export the variable REQUESTS_CA_BUNDLE that points to your private certificate authority, or a specific certificate bundle. On the command line you can do that as follows:

export REQUESTS_CA_BUNDLE=/path/to/your/certificate.pem
python script.py

If you have your certificate authority and you don't want to type the export each time you can add the REQUESTS_CA_BUNDLE to your ~/.bash_profile as follows:

echo "export REQUESTS_CA_BUNDLE=/path/to/your/certificate.pem" >> ~/.bash_profile ; source ~/.bash_profile
Mike N
  • 6,395
  • 4
  • 24
  • 21
  • The environment variable was what I needed to get PyCharm to work with the certificates stored in the OpenSSL cert file. – Brady Aug 30 '19 at 12:04
  • I have a self-signed certificate in the chain. This solution solved my problem with boto3 library. – Ilkin Oct 12 '20 at 11:53
  • A CA bundle is not private. Anybody connecting to your server will be able to read it. The key (which is not included in the bundle) is private. So probably it is more correct to say "your own certificate authority". – sekrett Jan 13 '22 at 15:19
54

With the verify parameter you can provide a custom certificate authority bundle

requests.get(url, verify=path_to_bundle_file)

From the docs:

You can pass verify the path to a CA_BUNDLE file with certificates of trusted CAs. This list of trusted CAs can also be specified through the REQUESTS_CA_BUNDLE environment variable.

Dr. Jan-Philip Gehrcke
  • 33,287
  • 14
  • 85
  • 130
15

All of the answers to this question point to the same path: get the PEM file, but they don't tell you how to get it from the website itself.

Getting the PEM file from the website itself is a valid option if you trust the site, such as on an internal corporate server. If you trust the site, why should you do this? You should do this because it helps protect yourself and others from inadvertently re-using your code on a site that isn't safe.

Here is how you can get the PEM file.

  1. Click on the lock next to the url. Click on the lock

  2. Navigate to where you can see the certificates and open the certificates. Navigate to view certificate

  3. Download the PEM CERT chain. Download the PEM chain

  4. Put the .PEM file somewhere you script can access it and try verify=r"path\to\pem_chain.pem" within your requests call.

r = requests.get(url, verify='\path\to\public_key.pem')

Foggy
  • 383
  • 2
  • 12
  • 1
    echo | openssl s_client -servername NAME -connect HOST:PORT |\ sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > certificate.crt – musterjunk Jun 29 '22 at 19:34
  • Yup, this worked for me as I was able to visit my corporate website through my browser, but not through code. This fixed it, thanks! – JoshuaHew Nov 02 '22 at 15:37
  • Foggy, thank you very much for showing people how to acquire the .pem file. It's this kind of thoroughness that makes this place awesome. – alexGIS Nov 21 '22 at 20:04
14

Case where multiple certificates are needed was solved as follows: Concatenate the multiple root pem files, myCert-A-Root.pem and myCert-B-Root.pem, to a file. Then set the requests REQUESTS_CA_BUNDLE var to that file in my ./.bash_profile.

$ cp myCert-A-Root.pem ca_roots.pem
$ cat myCert-B-Root.pem >> ca_roots.pem
$ echo "export REQUESTS_CA_BUNDLE=~/PATH_TO/CA_CHAIN/ca_roots.pem" >> ~/.bash_profile ; source ~/.bash_profile
Halbert Stone
  • 141
  • 1
  • 4
  • 2
    That was my "ahhh" moment of the day... Thanks a lot... With this hint I got my self signed jira certificate to work... ;-) I know there are maybe hundrets of sites and answers who describe this, but I found yours, so you get my credit for helping me solve my probelm... d – alexrjs Mar 13 '19 at 09:04
12

Setting export SSL_CERT_FILE=/path/file.crt should do the job.

gizzmole
  • 1,437
  • 18
  • 26
9

If you're behind a corporate network firewall like I was, ask your network admin where your corporate certificates are, then:

import os
os.environ["REQUESTS_CA_BUNDLE"] = 'path/to/corporate/cert.pem'
os.environ["SSL_CERT_FILE"] = 'path/to/corporate/cert.pem'

This fixed issues I had with requests and openssl.

Jordan M
  • 143
  • 2
  • 7
  • If I also need to use public domains (e.g., google.com), will it still work after setting this in the script? In other words, does this trust this CA bundle additionally, or does it trust this one instead of the default one? – Bolong Jul 03 '23 at 18:51
7

In a dev environment, using Poetry as virtual env provider on a Mac with Python 3.8 I used this answer https://stackoverflow.com/a/42982144/15484549 as base and appended the content of my self-signed root certificate to the certifi cacert.pem file.

The steps in detail:

cd project_folder
poetry add requests
# or if you use something else, make sure certifi is among the dependencies
poetry shell
python
>>> import certifi
>>> certifi.where()
/path/to/the/certifi/cacert.pem
>>> exit()
cat /path/to/self-signed-root-cert.pem >> /path/to/the/certifi/cacert.pem
python the_script_you_want_to_run.py
Alex
  • 185
  • 2
  • 5
3

I know it is an old thread. However, I run into this issue recently. My python requests code does not accept the self-signed certificate but curl does. It turns out python requests are very strict on the self-signed certificate. It needs to be a root CA certificate. In other words,

Basic Constraints: CA:TRUE

Key Usage: Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign

Yufeng
  • 51
  • 1
  • 3
0

Incase anyone happens to land here (like I did) looking to add a CA (in my case Charles Proxy) for httplib2, it looks like you can append it to the cacerts.txt file included with the python package.

For example:

cat ~/Desktop/charles-ssl-proxying-certificate.pem >> /usr/local/google-cloud-sdk/lib/third_party/httplib2/cacerts.txt

The environment variables referenced in other solutions appear to be requests-specific and were not picked up by httplib2 in my testing.

Mat Schaffer
  • 1,634
  • 1
  • 15
  • 24
0

You may try:

settings = s.merge_environment_settings(prepped.url, None, None, None, None)

You can read more here: http://docs.python-requests.org/en/master/user/advanced/

Peter Tretyakov
  • 3,380
  • 6
  • 38
  • 54
gan
  • 11
  • 1
  • 1
    Oh yeah that old readthedocs maze link as of today : https://requests.readthedocs.io/en/latest/user/advanced/ – Boop Sep 10 '20 at 07:57