如何获取 requests.exceptions.SSLError 的更多详细信息?

How to get more details on a requests.exceptions.SSLError?

当我使用过期的 HTTPS 证书请求 URL 时,我没有从请求中收到有意义的错误。相反,它给了我一连串的“ssl.SSLError: A failure in the SSL library occurred”。

请参阅此示例 https://expired.badssl.com/ :

>python
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May  3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> requests.get("https://expired.badssl.com/")
Traceback (most recent call last):
  File "C:\Users\me\apps\Python39\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
    httplib_response = self._make_request(
  File "C:\Users\me\apps\Python39\lib\site-packages\urllib3\connectionpool.py", line 381, in _make_request
    self._validate_conn(conn)
  File "C:\Users\me\apps\Python39\lib\site-packages\urllib3\connectionpool.py", line 978, in _validate_conn
    conn.connect()
  File "C:\Users\me\apps\Python39\lib\site-packages\urllib3\connection.py", line 362, in connect
    self.sock = ssl_wrap_socket(
  File "C:\Users\me\apps\Python39\lib\site-packages\urllib3\util\ssl_.py", line 386, in ssl_wrap_socket
    return context.wrap_socket(sock, server_hostname=server_hostname)
  File "C:\Users\me\apps\Python39\lib\ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "C:\Users\me\apps\Python39\lib\ssl.py", line 1040, in _create
    self.do_handshake()
  File "C:\Users\me\apps\Python39\lib\ssl.py", line 1309, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: A failure in the SSL library occurred (_ssl.c:1129)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\me\apps\Python39\lib\site-packages\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "C:\Users\me\apps\Python39\lib\site-packages\urllib3\connectionpool.py", line 726, in urlopen
    retries = retries.increment(
  File "C:\Users\me\apps\Python39\lib\site-packages\urllib3\util\retry.py", line 446, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='expired.badssl.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, 'A failure in the SSL library occurred (_ssl.c:1129)')))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\me\apps\Python39\lib\site-packages\requests\api.py", line 76, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Users\me\apps\Python39\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\me\apps\Python39\lib\site-packages\requests\sessions.py", line 530, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\me\apps\Python39\lib\site-packages\requests\sessions.py", line 643, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\me\apps\Python39\lib\site-packages\requests\adapters.py", line 514, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='expired.badssl.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, 'A failure in the SSL library occurred (_ssl.c:1129)')))
>>>

requests 是 2.24.0,ssl.OPENSSL_VERSION 表示“OpenSSL 1.1.1h 2020 年 9 月 22 日”。我无法更新软件包。

如何获得有意义的错误或错误消息,告诉我证书已过期?

您通常会这样处理这样的事情:

import requests
try:
    requests.get("https://expired.badssl.com/")
except requests.exceptions.SSLError as e:
    print(f'oops! got the following SSL error: {e}')

在我的测试机器上,输出包含 [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired

由于“证书已过期”不在您的异常文本中,我怀疑您的版本中存在错误。 requests 2.24.0 不是最新版本。此外,requests 同时使用 urllib3 和 certifi。也许你应该试试:

pip install --upgrade urllib3 requests certifi

要求:

  • 环境:Python3.9.5 / 请求 2.24.0 / OpenSSL 1.1.1h
  • 如果与服务器的联系失败,应确定问题是否是过期的服务器证书

最简单的解决方案是将已安装的 OpenSSL 更新为当前版本 1.1.1n,但即使 1.1.1i 也足以获取包含 certificate has expired 的消息。但是无法更新 OpenSSL 库,正如您在 post.

中提到的那样

或者,您可以在请求期间捕获异常,然后明确检查服务器证书是否已过期。

要做到这一点,例如,您可以使用我之前 中的 get_cert_for_hostname 函数,并相应地将 not_valid_after 字段与当前日期进行比较。

一个简单的 self-contained 示例可能如下所示:

import ssl
import requests
import platform
from datetime import datetime
from cryptography import x509


def get_cert_for_hostname(hostname, port):
    conn = ssl.create_connection((hostname, port))
    context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    sock = context.wrap_socket(conn, server_hostname=hostname)
    certDER = sock.getpeercert(True)
    certPEM = ssl.DER_cert_to_PEM_cert(certDER)
    conn.close()
    return x509.load_pem_x509_certificate(certPEM.encode('ascii'))


def is_cert_expired(hostname, port):
    cert = get_cert_for_hostname(hostname, port)
    return datetime.now() > cert.not_valid_after


if __name__ == '__main__':
    print(f"Python version: {platform.python_version()}")
    print(f"OpenSSL version: {ssl.OPENSSL_VERSION}")
    print(f"requests version: {requests.__version__}")  #
    hosts = ['software7.com', 'expired.badssl.com']
    for host in hosts:
        try:
            requests.get(f"https://{host}")
            print(f"request for host {host} was successful")
        except BaseException as err:
            if is_cert_expired(host, 443):
                print(f"certificate for {host} expired")
            else:
                print(f"error {err} with {host}")

这会将以下内容记录到调试控制台:

Python version: 3.9.5
OpenSSL version: OpenSSL 1.1.1h  22 Sep 2020
requests version: 2.24.0
request for host software7.com was successful
certificate for expired.badssl.com expired