python - 在 Twisted 中将 HTTP 代理转换为 HTTPS 代理

标签 python http proxy https twisted

最近我一直在研究 twisted 中的 HTTP 代理。经过多次试验和错误,我想我终于有了一些工作。不过,我想知道的是,如果可能的话,我如何扩展此代理以使其也能够处理 HTTPS 页面?这是我到目前为止所得到的:

from twisted.internet import reactor
from twisted.web import http
from twisted.web.proxy import Proxy, ProxyRequest, ProxyClientFactory, ProxyClient



class HTTPProxyClient(ProxyClient):
    def handleHeader(self, key, value):
        print "%s : %s" % (key, value)
        ProxyClient.handleHeader(self, key, value)

    def handleResponsePart(self, buffer):
        print buffer
        ProxyClient.handleResponsePart(self, buffer)

class HTTPProxyFactory(ProxyClientFactory):
    protocol = HTTPProxyClient

class HTTPProxyRequest(ProxyRequest):
    protocols = {'http' : HTTPProxyFactory}

    def process(self):
        print self.method
        for k,v in self.requestHeaders.getAllRawHeaders():
            print "%s : %s" % (k,v)
        print "\n \n"

        ProxyRequest.process(self)

class HTTPProxy(Proxy):

    requestFactory = HTTPProxyRequest


factory = http.HTTPFactory()
factory.protocol = HTTPProxy

reactor.listenSSL(8001, factory)
reactor.run()

正如这段代码所展示的,为了举例起见,现在我只是打印出正在通过连接的任何内容。是否可以使用相同的类来处理 HTTPS?如果没有,我应该如何实现这样的事情?

最佳答案

如果您想通过 HTTP 代理连接到 HTTPS 网站,您需要使用 CONNECT HTTP 动词(因为这就是 HTTPS 代理的工作方式)。在这种情况下,代理服务器只是连接到目标服务器并将服务器发送的任何内容中继回客户端的套接字(反之亦然)。在这种情况下不涉及缓存(但您可能能够记录您正在连接的主机)。

交换看起来像这样(客户端到代理):

C->P: CONNECT target.host:443 HTTP/1.0
C->P:

P->C: 200 OK
P->C: 

在此之后,代理只需打开一个到目标服务器的普通套接字(还没有 HTTP 或 SSL/TLS)并在初始客户端和目标服务器之间中继所有内容(包括客户端发起的 TLS 握手)。客户端将现有套接字升级到代理以使用 TLS/SSL(通过启动 SSL/TLS 握手)。一旦客户端读取了“200”状态行,就客户端而言,就好像它已经直接连接到目标服务器。

关于python - 在 Twisted 中将 HTTP 代理转换为 HTTPS 代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3118602/

相关文章:

Python( Pandas ): replace value if previous value is same as next value

python - 将多项式与 numpy.convolve 相乘返回错误结果

angularjs - Angular : why $http GET params encrypted?

http - JMeter -> HTTPSampler 错误 java.lang.NoSuchFieldError : DEF_CONTENT_CHARSET on PUT request

c - 通过 HTTP 请求上传文件到 Google Drive (C)

"Resource temporarily unavailable"后的Python多处理池恢复

google-app-engine - 使用谷歌分析 super 代理授权访问

swift - 如何使用 Swift Perfect Framework 创建代理服务器?

java - 服务 bean 在 spring cglib 代理中注入(inject)失败

python - Celery:实例在一两周后变得缓慢