如何使用 python 检索远程主机的 TLS/SSL 对等证书?
我需要扫描 IP 列表并从该 IP 上的证书检索通用名称(对于允许端口 443 连接的每个 IP)。我已经能够使用套接字和 ssl 模块成功地完成此操作。它适用于所有具有有效签名证书的 IP,但不适用于自签名证书。
如果我使用此方法,它需要一个由我的 CA 捆绑包验证的有效证书:
from socket import socket
import ssl
s = socket()
c = ssl.wrap_socket(s,cert_reqs=ssl.CERT_REQUIRED, ca_certs='ca-bundle.crt')
c.connect(('127.0.0.1', 443))
print c.getpeercert()
如果我删除 cert_reqs=ssl.CERT_REQUIRED ,则它会连接,但根本无法获取证书。
如何检索 IP 上证书的通用名称,无论它是否针对 ca 捆绑包进行验证?
I need to scan through a list of IPs and retrieve the common name from the certificate on that IP (for every IP that allows port 443 connections). I have been able to successfully do this using the sockets and ssl modules. It works for all IPs with valid, signed certificates but it isn't working for self-signed certificates.
If I use this method, it requires a valid cert that is verified by my CA-bundle:
from socket import socket
import ssl
s = socket()
c = ssl.wrap_socket(s,cert_reqs=ssl.CERT_REQUIRED, ca_certs='ca-bundle.crt')
c.connect(('127.0.0.1', 443))
print c.getpeercert()
If I remove the cert_reqs=ssl.CERT_REQUIRED
then it connects but doesn't get the certificate at all.
How can I retrieve the common name for a certificate on an IP whether it validates against the ca-bundle or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
python ssl 库似乎只会在具有有效签名的情况下为您解析证书。
您仍然可以使用
ssl.get_server_certificate()
函数获取服务器证书,但它以 PEM 格式返回。 (或者,您可以调用c.getpeercert(True)
,它以二进制 DER 格式返回证书,无论是否经过验证。)从这里,我将使用 M2Crypto 或 OpenSSL 来读取证书并获取值:
The python ssl library seems like it only parses out the cert for you if it has a valid signature.
You can still get the server certificate with the
ssl.get_server_certificate()
function, but it returns it in PEM format. (Alternatively, you could callc.getpeercert(True)
, which returns the cert in binary DER format, whether it's validated or not.)From here, I would use M2Crypto or OpenSSL to read the cert and get values:
使用 SNI 支持检索和解析、解析日期并显示扩展数据(如
subjectAltName
):输出:
Retrieving and parsing with SNI support, parsing dates and showing extension data (like
subjectAltName
):Output:
在 Mac 上,您需要安装 swig 和 M2Crypto
在终端上运行:
然后:
然后您可以运行上面的代码:
On Mac you need to install swig and M2Crypto
On terminal run:
And then:
Then you can run the code above: