将单个证书添加到请求

han*_*ine 5 python ssl python-requests

我正在尝试从 Linux 计算机上运行的 Python/requests 连接到公司内部网 HTTPS 服务器,该服务器使用内部 CA。我有一个 .pem 文件,其中包含我们的证书(4096 位 RSA、CSSM_KEYUSE_VERIFY、CA = true)。

\n\n

我将其放入/usr/share/ca-certificates并使用的子文件夹中sudo dpkg-reconfigure ca-certificates,以便将其集成到系统中。

\n\n

请求文档中,我发现:

\n\n
\n

您可以使用可信 CA \xe2\x80\xa6 的证书来验证 CA_BUNDLE 文件或目录的路径。如果将 verify 设置为目录的路径,则该目录必须已使用 OpenSSL 提供的 c_rehash 实用程序进行过处理。

\n
\n\n

我相信(但不确定)/etc/ssl/certs满足这个条件。

\n\n

现在,我尝试了多种方式的请求:

\n\n
requests.get(download_url)\n# throws requests.exceptions.SSLError: ("bad handshake: Error([\n#   (\'SSL routines\', \'ssl3_get_server_certificate\',\n#    \'certificate verify failed\')],)",)\n\nrequests.get(download_url, verify = False)\n# works, but is obviously bad (and spits out a warning)\n\nrequests.get(download_url, verify = pem_file_path)\n# same SSLError as above (option shows no effect)\n\nrequests.get(download_url, cert = pem_file_path)\nrequests.get(download_url, cert = \'/etc/ssl/certs\')\n# both throw OpenSSL.SSL.Error: [\n#   (\'PEM routines\', \'PEM_read_bio\', \'no start line\'),\n#   (\'SSL routines\', \'SSL_CTX_use_PrivateKey_file\', \'PEM lib\')]\n\nrequests.get(download_url, verify = \'/etc/ssl/certs\')\n# Finally, this raises an unprintable exception:\n# requests.exceptions.SSLError: <exception str() failed>\n
Run Code Online (Sandbox Code Playgroud)\n\n

实际上,在 python 中使用带有请求的自签名证书看起来可以描述相同的问题(但尚未得到解答)。

\n

han*_*ine 3

感谢@stark,我发现问题是我的证书文件已过期。有了正确的、最新的证书(即使是 DER 格式,带有 .cer 扩展名),以下语法现在可以使用:

requests.get(download_url, verify = cer_file_path)
Run Code Online (Sandbox Code Playgroud)