使用urllib.request验证HTTPS证书 [英] Verifying HTTPS certificates with urllib.request
问题描述
我正在尝试使用打开https网址Python 3中的 urlopen
方法 urllib.request
模块。它似乎工作正常,但文档警告说[i] f既没有 cafile
也没有 capath
被指定, HTTPS请求不会对服务器的证书进行任何验证。
I am trying to open an https URL using the urlopen
method in Python 3's urllib.request
module. It seems to work fine, but the documentation warns that "[i]f neither cafile
nor capath
is specified, an HTTPS request will not do any verification of the server’s certificate".
我猜我需要指定其中一个参数,如果我不希望我的程序容易受到攻击中间人攻击,撤销证书问题和其他漏洞。
I am guessing I need to specify one of those parameters if I don't want my program to be vulnerable to man-in-the-middle attacks, problems with revoked certificates, and other vulnerabilities.
cafile
和 capath
应该指向证书列表。我应该从哪里获得此列表?是否有任何简单和跨平台的方式来使用我的操作系统或浏览器使用的相同证书列表?
cafile
and capath
are supposed to point to a list of certificates. Where am I supposed to get this list from? Is there any simple and cross-platform way to use the same list of certificates that my OS or browser uses?
推荐答案
我找到了我正在尝试做的事情的图书馆: Certifi 。可以通过从命令行运行 pip install certifi
来安装它。
I found a library that does what I'm trying to do: Certifi. It can be installed by running pip install certifi
from the command line.
现在可以轻松地发出请求并验证它们:
Making requests and verifying them is now easy:
import certifi
import urllib.request
urllib.request.urlopen("https://example.com/", cafile=certifi.where())
正如我所料,这将为具有有效证书的站点返回 HTTPResponse
对象,并为具有有效证书的站点引发 ssl.CertificateError
异常证书无效。
As I expected, this returns a HTTPResponse
object for a site with a valid certificate and raises a ssl.CertificateError
exception for a site with an invalid certificate.
这篇关于使用urllib.request验证HTTPS证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!