gpt4 book ai didi

python - 如何使用 httplib2 进行相互证书认证

转载 作者:太空狗 更新时间:2023-10-29 20:59:46 24 4
gpt4 key购买 nike

我正在使用 httplib2 从我的服务器向另一个 Web 服务发出请求。我们想使用相互证书认证。我看到了如何为传出连接使用证书 (h.set_certificate),但是如何检查应答服务器使用的证书?

This ticket似乎表明 httplib2 本身并不执行此操作,并且只有关于查找位置的模糊建议。

这可能吗?我是否必须在较低级别进行破解?

最佳答案

这是我的同事 Dave St. Germain 为解决该问题而编写的代码:

import ssl
import socket
from httplib2 import has_timeout
import httplib2
import socks


class CertificateValidationError(httplib2.HttpLib2Error):
pass


def validating_sever_factory(ca_cert_file):
# we need to define a closure here because we don't control
# the arguments this class is instantiated with
class ValidatingHTTPSConnection(httplib2.HTTPSConnectionWithTimeout):

def connect(self):
# begin copypasta from HTTPSConnectionWithTimeout
"Connect to a host on a given (SSL) port."

if self.proxy_info and self.proxy_info.isgood():
sock = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM)
sock.setproxy(*self.proxy_info.astuple())
else:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

if has_timeout(self.timeout):
sock.settimeout(self.timeout)
sock.connect((self.host, self.port))
# end copypasta


try:
self.sock = ssl.wrap_socket(sock,
self.key_file,
self.cert_file,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=ca_cert_file
)
except ssl.SSLError:
# we have to capture the exception here and raise later because
# httplib2 tries to ignore exceptions on connect
import sys
self._exc_info = sys.exc_info()
raise
else:
self._exc_info = None

# this might be redundant
server_cert = self.sock.getpeercert()
if not server_cert:
raise CertificateValidationError(repr(server_cert))

def getresponse(self):
if not self._exc_info:
return httplib2.HTTPSConnectionWithTimeout.getresponse(self)
else:
raise self._exc_info[1], None, self._exc_info[2]
return ValidatingHTTPSConnection


def do_request(url,
method='GET',
body=None,
headers=None,
keyfile=None,
certfile=None,
ca_certs=None,
proxy_info=None,
timeout=30):
"""
makes an http/https request, with optional client certificate and server
certificate verification.
returns response, content
"""
kwargs = {}
h = httplib2.Http(proxy_info=proxy_info, timeout=timeout)
is_ssl = url.startswith('https')
if is_ssl and ca_certs:
kwargs['connection_type'] = validating_sever_factory(ca_certs)

if is_ssl and keyfile and certfile:
h.add_certificate(keyfile, certfile, '')
return h.request(url, method=method, body=body, headers=headers, **kwargs)

关于python - 如何使用 httplib2 进行相互证书认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2363105/

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