Python请求:使用自签名验证

2024-09-29 23:19:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试使用自签名证书测试请求SSL验证,并将其设置为verify param CA bundle。我得到了[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590),而不是测试通过。在

这是我的测试代码:

class TestSubjectVerification(HttpTestSupport):
    @classmethod
    def setUpClass(cls):
        cls.https_port = get_random_port()
        cls.httpsd = server.HTTPServer(('', cls.https_port), Handler)
        cls.httpsd.socket = ssl.wrap_socket(cls.httpsd.socket,
                                            certfile=os.path.join(TEST_RESOURCES_DIR, "certificate.pem"),
                                            keyfile=os.path.join(TEST_RESOURCES_DIR, "private.key"),
                                            server_side=True)
        Thread(target=cls.httpsd.serve_forever).start()

    def test_hello(self):
        port = self.__class__.https_port
        ca = os.path.join(TEST_RESOURCES_DIR, "certificate.pem")
        r = requests.get("https://127.0.0.1:%s" % port, verify=ca)
        self.assertEqual("hello", r.text)

我用以下openssl命令创建了我的密钥和证书(引用了stackoverflow post):

openssl genrsa -out private.key 3072

openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730

自定义开放式ssl.cnf,我指定127.0.0.1作为IP subjectAltName。检查证书:

^{pr2}$

此外,curl似乎可以很好地验证证书并打印响应(尽管它会给出一些其他错误):

curl --cacert /path/to/my/certificate.pem  https://127.0.0.1:8443/
curl: (56) GnuTLS recv error (-110): The TLS connection was non-properly terminated.
hello

curl https://127.0.0.1:8443/
curl: (60) server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

Tags: pathkeyhttpssslserverosportsocket
1条回答
网友
1楼 · 发布于 2024-09-29 23:19:31

我猜您使用的是python2.7。根据源代码ssl.py文件只检查使用者备用名称中的DNS条目,这意味着您的IP地址条目将被忽略。即使在最新版本的Python2.7(即2.7.13)中,这似乎也是有效的。在

对于python3,这是修复的。根据ssl.py文件在python3.5中,它将特别检查subject alternative names中的IP地址类型。在

这意味着您要么必须使用DNS条目,而不是IP address条目,后者虽然在python2.7中是错误的,但是停止了python3的工作。或者可以使用python3。或者使用主机名。在

相关问题 更多 >

    热门问题