带有反向Python HTTPS服务器的反向代理

时间:2018-08-26 19:22:43

标签: python https server twisted reverse-proxy

我正在尝试建立一个反向代理,以过滤所有传入本地服务器的请求。

服务器:

import BaseHTTPServer, SimpleHTTPServer
import ssl
import os

def main():
    httpd = BaseHTTPServer.HTTPServer(('192.168.58.1', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)
    os.chdir('./content')
    # httpd.socket = ssl.wrap_socket(httpd.socket, certfile='../server.pem', server_side=True)
    httpd.serve_forever()

if __name__ == '__main__':
    main()

代理:

from twisted.web import proxy, server
from twisted.internet import ssl, reactor
import argparse
from OpenSSL import crypto

class BadURL():
    def render(self, request):
        return "Banned"

class HTTPSReverseProxyResource(proxy.ReverseProxyResource, object):

    def getChild(self, path, request):

        if "fmm" in path:
            return BadURL()
        child = super(HTTPSReverseProxyResource, self).getChild(path, request)
        return HTTPSReverseProxyResource(child.host, child.port, child.path,
                                     child.reactor)


if __name__ == '__main__':

    ap = argparse.ArgumentParser()
    ap.add_argument('-c', type=str)
    ap.add_argument('-k', type=str)
    ns = ap.parse_args()

    myProxy = HTTPSReverseProxyResource('192.168.58.1', 4443, '')

    site = server.Site(myProxy)

    if ns.c:
        with open(ns.c, 'rb') as fp:
            ssl_cert = fp.read()
        if ns.k:

            with open(ns.k, 'rb') as fp:
                ssl_key = fp.read()
            certificate = ssl.PrivateCertificate.load(
                    ssl_cert,
                    ssl.KeyPair.load(ssl_key, crypto.FILETYPE_PEM),
                    crypto.FILETYPE_PEM)
        else:
            certificate = ssl.PrivateCertificate.loadPEM(ssl_cert)
        reactor.listenSSL(8080, site, certificate.options())
    else:
        reactor.listenTCP(8080, site)
    reactor.run()

问题和我的问题是,当我使用HTTPS服务器时(在服务器中取消注释“ httpd.socket = ssl.wrap_socket ...”行),代理返回的所有页面均为空白。

1 个答案:

答案 0 :(得分:1)

您没有将proxyClientFactoryClass方法添加到反向代理类(Python-Twisted: Reverse Proxy to HTTPS API: Could not connect)中。试试这个:

class HTTPSReverseProxyResource(proxy.ReverseProxyResource, object):
    def proxyClientFactoryClass(self, *args, **kwargs):
        """
        Make all connections using HTTPS.
        """
        return TLSMemoryBIOFactory(
            ssl.optionsForClientTLS(self.host.decode("ascii")), True,
            super(HTTPSReverseProxyResource, self)
            .proxyClientFactoryClass(*args, **kwargs))

    def getChild(self, path, request):

        if "fmm" in path:
            return BadURL()
        child = super(HTTPSReverseProxyResource, self).getChild(path, request)
        return HTTPSReverseProxyResource(child.host, child.port, child.path,
                                     child.reactor)