gpt4 book ai didi

python - 如何通过 http.client.HTTPSConnection 设置 SNI

转载 作者:行者123 更新时间:2023-12-04 22:36:52 48 4
gpt4 key购买 nike

我正在使用 http.client.HTTPSConnection生成到我的服务器的 HTTPS 连接。我不能使用原始主机名连接到服务器,因为这是一个测试设置,但我需要使用正确的主机名作为 SNI 进行正确的 TLS 握手。如何为 HTTPS 连接的客户端 hello 设置 SNI?

ssl.SSLSocket.server_hostname来看,如果我可以访问底层套接字,我应该能够将它的 server_hostname 设置为我想要的值。 HTTPSConnection确实有 sock成员,但它是 None施工后。

如果更多源代码上下文有帮助,我正在 proxy-verifier 中的测试代理上工作。 .见 proxy_http1.py#L94

最佳答案

在问题的评论部分,Steffen Ullrich 引导我找到答案。通过http.client.HTTPSConnection 对我尝试做的事情没有直接的支持。 .但是,http.client.HTTPSConnection调用ssl.SSLContext.wrap_socket函数关闭传入的 SSLContext。因此,我能够通过为该类创建一个包装器来获得我想要的。如果它对其他人有帮助,我的代码现在如下所示:

if scheme == 'https':
if socket.client_sni:


class WrapSSSLContext(ssl.SSLContext):
'''
HTTPSConnection provides no way to specify the
server_hostname in the underlying socket. We
accomplish this by wrapping the context to
overrride the wrap_socket behavior (called later
by HTTPSConnection) to specify the
server_hostname that we want.
'''
def __new__(cls, server_hostname, *args, **kwargs):
return super().__new__(cls, *args, *kwargs)


def __init__(self, server_hostname, *args, **kwargs):
super().__init__(*args, **kwargs)
self._server_hostname = server_hostname


def wrap_socket(self, sock, *args, **kwargs):
kwargs['server_hostname'] = self._server_hostname
return super().wrap_socket(sock, *args, **kwargs)


proxy_to_server_context = WrapSSSLContext(socket.client_sni)
else:
proxy_to_server_context = ssl.SSLContext()
self.tls.conns[origin] = http.client.HTTPSConnection(
replay_server, timeout=self.timeout,
context=proxy_to_server_context, cert_file=self.cert_file)

因此,如果我想指定 SNI,我使用自定义 WrapSSSLContext明确提供我想要的 server_hostname 的类。否则我只使用标准 ssl.SSLContext .我已经在数据包捕获中验证了这指定了我想要在客户端打招呼中的 SNI。

谢谢史蒂芬!

关于python - 如何通过 http.client.HTTPSConnection 设置 SNI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61280350/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com