Python ssl:check_hostname 中的 IP 地址

Python ssl: IP address in check_hostname

Python3 ssl 库可以使用 IP 地址,而不是证书中的主机名吗?

假设我尝试连接到服务器:

ip = '192.168.0.99'
context = ssl.create_default_context(cafile='ca.crt')
with socket.create_connection((ip, 443)) as sock:
  with context.wrap_socket(sock, server_hostname=ip) as ssock:
    print(ssock.version())

当我 运行 它时,我得到一个错误:

SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)

IP 地址 192.168.0.99 被写入证书 Common Name 和 Subject Alt Name。

$ openssl x509 -in san.crt  -noout  -text | grep -B 1 192.168.0.99
        Signature Algorithm: sha256WithRSAEncryption
        Issuer: C = RU, ST = MSK, O = Internet Widgits Pty Ltd, OU = example, CN = 192.168.0.99
--
            Not After : Jul  4 21:31:32 2030 GMT
        Subject: C = RU, ST = MSK, O = Internet Widgits Pty Ltd, OU = example, CN = 192.168.0.99
--
            X509v3 Subject Alternative Name:
                IP Address:192.168.0.99

SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)

错误不是关于主机名与证书不匹配,而是关于无法为证书找到本地受信任的颁发者。

context = ssl.create_default_context(cafile='ca.crt')

我假设您的意图是 ca.crtsan.crt 的发行人。但是根据您从证书中显示的内容,它看起来像是一个自签名证书(主题和颁发者相同)并且没有由 ca.crt.

签名