从 Python 中的无效证书中获取证书信息



我正在开发Python 2.7.13(Win x64)脚本来验证SSL证书,并发出问题警报。但是,我遇到了一个问题,即脚本仅在证书有效时才返回信息。

如果证书无效,我会收到 SSL CERTIFICATE_VERIFY_FAILED错误。通常,当引发错误时,我只会使用 try/catch 并提醒证书无效,但这里的问题是我需要证书的实际到期日期。

根据 https://docs.python.org/2/library/ssl.html 我尝试使用 conn._https_verify_certificates(enable=False) 禁用证书验证,但收到该属性_https_verify_certificates不存在的错误。

这是我到目前为止的代码。我确定我错过了一些明显的东西。当然,Python可以在不验证的情况下提取SSL证书,对吧?

import socket
import ssl
def ssl_expiry_datetime(hostname):
ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
context = ssl.create_default_context()
conn = context.wrap_socket(
socket.socket(socket.AF_INET),
server_hostname=hostname,
)
# 3 second timeout because Lambda has runtime limitations
conn.settimeout(3.0)
#conn._https_verify_certificates(enable=False)
conn.connect((hostname, 443))
ssl_info = conn.getpeercert()
# parse the string from the certificate into a Python datetime object
return ['notAfter']
myhost = 'www.google.com'
print ssl_expiry_datetime(myhost)

非常感谢!!!

经过大量的试验和错误,我发现您可以使用check_hostname功能关闭SSLcertificate主机名验证。

context.check_hostname = False

如果目标与 SSL 证书上的公用名 (CN) 不匹配,这将允许程序在 Web 服务器上连接。但是,当 Web 服务器使用无效的 SSL 证书时,连接将失败并引发 ConnetionError 错误。如果目的是获取所有SSL证书,即使是无效的证书,则以下解决方案只能部分满足您的需求

下面是一个建议的解决方案:

import socket, ssl
def ssl_expiry_datetime(hostname):
ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
context = ssl.create_default_context()
context.check_hostname = False
conn = context.wrap_socket(
socket.socket(socket.AF_INET),
server_hostname=hostname,
)
# 3 second timeout because Lambda has runtime limitations
conn.settimeout(3.0)
#conn._https_verify_certificates(enable=False)
conn.connect((hostname, 443))
ssl_info = conn.getpeercert()
# parse the string from the certificate into a Python datetime object
return ['notAfter']
myhost = 'example.com'
print ssl_expiry_datetime(myhost)

或者,您可以使用请求库,它允许您完全关闭验证。

引用:

  1. 21.6. urllib.request — 用于打开 URL 的可扩展库 - https://docs.python.org/3/library/urllib.request.html#urllib.request.urlretrieve
  2. 17.3.3. SSL 上下文 - https://docs.python.org/2/library/ssl.html#ssl-contexts

最新更新