Python Requests - How to use system ca-certificates (debian/ubuntu)?

前端 未结 3 647
我寻月下人不归
我寻月下人不归 2020-11-27 03:07

I\'ve installed a self-signed root ca cert into debian\'s /usr/share/ca-certificates/local and installed them with sudo dpkg-reconfigure ca-certificates

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 03:38

    I struggled with this for a week or so recently. I finally found that the way to verify a self-signed, or privately signed, certificate in Python. You need to create your own certificate bundle file. No need to update obscure certificate bundles every time you update a library, or add anything to the system certificate store.

    Start by running the openssl command that you ran before, but add -showcerts. openssl s_client -connect mysite.local:443 -showcerts This will give you a long output, and at the top you'll see the entire certificate chain. Usually, this means three certs, the website's certificate, the intermediate certificate, and the root certificate in that order. We need to put just the root and intermediate certificates into a next file in the opposite order.

    Copy the last cert, the root certificate, to a new text file. Grab just the stuff between, and including:

    -----BEGIN CERTIFICATE-----
    ...
    -----END CERTIFICATE-----
    

    Copy the middle cert (aka the intermediate certificate) to the new text file under the root cert. Again, grab the Begin and End Certificate lines and everything in between.

    Save this text file to the directory where your Python script resides. My recommendation is to call it CertBundle.pem. (If you give it a different name, or put it somewhere else in your folder structure, make sure that the verify line reflects that.) Update your script to reference the new certificate bundle:

    response = requests.post("https://www.example.com/", headers=headerContents, json=bodyContents, verify="CertBundle.pem")
    

    And that's it. If you have only the root or only the intermediate certificate, then Python can't validate the entire certificate chain. But, if you include both of the certificates in the certificate bundle that you created, then Python can validate that the intermediate was signed by the root, and then when it accesses the website it can validate that the website's certificate was signed by the intermediate certificate.

    edit: Fixed the file extension for the cert bundle. Also, fixed a couple of grammatical mistakes.

提交回复
热议问题