aiohttp 如何检索对等证书?

aiohttp how do I retrieve peer certificate?

我想获取证书哈希。但我不知道如何获得服务器对等证书。在请求或响应中。我发送请求的服务器设置 Connection close header,因此在响应中检索原始 ssl 套接字不起作用。

暂时没有办法,抱歉。 您可以轻松检查证书哈希:https://docs.aiohttp.org/en/stable/client_advanced.html#ssl-control-for-tcp-sockets

以下示例使用 SHA-256 指纹检查:

fingerprint = b'...'  # should be 64 bytes length hash (256/8)

r = await session.get('https://example.com',
                      ssl=aiohttp.Fingerprint(fingerprint))

我想到了这个solution/hack

import aiohttp


class WrappedResponseClass(aiohttp.ClientResponse):

    def __init__(self, *args, **kwargs):
        super(WrappedResponseClass, self).__init__(*args, **kwargs)
        self._peer_cert = None

    async def start(self, connection, read_until_eof=False):
        try:
            self._peer_cert = connection.transport._ssl_protocol._extra['ssl_object'].getpeercert(True)
        except Exception:
            pass
        return await super(WrappedResponseClass, self).start(connection, read_until_eof)

    @property
    def peer_cert(self):
        return self._peer_cert



session = aiohttp.ClientSession(otherargs..., response_class=WrappedResponseClass)