HTTPS proxy tunneling with the ssl module

后端 未结 5 1146
耶瑟儿~
耶瑟儿~ 2021-01-02 01:51

I\'d like to manually (using the socket and ssl modules) make an HTTPS request through a proxy which itself uses HTTPS.

I can perform the i

5条回答
  •  爱一瞬间的悲伤
    2021-01-02 02:14

    This should work if the CONNECT string is rewritten as follows:

    CONNECT = "CONNECT %s:%s HTTP/1.0\r\nConnection: close\r\n\r\n" % (server, port)
    

    Not sure why this works, but maybe it has something to do with the proxy I'm using. Here's an example code:

    from OpenSSL import SSL
    import socket
    
    def verify_cb(conn, cert, errun, depth, ok):
            return True
    
    server = 'mail.google.com'
    port = 443
    PROXY_ADDR = ("proxy.example.com", 3128)
    CONNECT = "CONNECT %s:%s HTTP/1.0\r\nConnection: close\r\n\r\n" % (server, port)
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(PROXY_ADDR)
    s.send(CONNECT)
    print s.recv(4096)      
    
    ctx = SSL.Context(SSL.SSLv23_METHOD)
    ctx.set_verify(SSL.VERIFY_PEER, verify_cb)
    ss = SSL.Connection(ctx, s)
    
    ss.set_connect_state()
    ss.do_handshake()
    cert = ss.get_peer_certificate()
    print cert.get_subject()
    ss.shutdown()
    ss.close()
    

    Note how the socket is first opened and then open socket placed in SSL context. Then I manually initialize SSL handshake. And output:

    HTTP/1.1 200 Connection established

    It's based on pyOpenSSL because I needed to fetch invalid certificates too and Python built-in ssl module will always try to verify the certificate if it's received.

提交回复
热议问题