hi, i am trying to implement a proxy based on BaseHTTPServer built-in module. the GET & POST methods work fine, but i have some problems implementing the CONNECT (do_CONNECT) method, i understand how ssl tunneling works theoritically, i tried to implement it using httplib.HTTPSConnection, i write the headers and the data back to the client, but when i test it, the browser only shows a page not found...

can you please suggest what to do, just a few helpful pointers would be appreciated...

Dani AI

Generated

CONNECT must establish a raw TCP tunnel, not perform an HTTP fetch on behalf of the browser. After parsing the target host:port from the CONNECT request, open a TCP connection to that host, reply with an HTTP 200 (for example HTTP/1.1 200 Connection established\r\n\r\n) and then forward bytes bidirectionally between client and server. A frequent pitfall — and the likely reason for 's "page not found" — is using an HTTP client (like httplib.HTTPSConnection) to get the page and then sending that response back. Browsers expect to do the TLS handshake themselves over the tunnel, so proxying must relay raw TLS bytes unless the proxy intentionally terminates TLS.

A minimal relay loop (select-based) is often the simplest and most robust approach:

remote = socket.create_connection((host, port))
# send HTTP 200 to client, then relay raw bytes
sockets = [client_sock, remote]   # client_sock = the handler's raw socket (self.request or self.connection)
while True:
    r, _, _ = select.select(sockets, [], [])
    for s in r:
        data = s.recv(8192)
        if not data:
            client_sock.close(); remote.close(); break
        (remote if s is client_sock else client_sock).sendall(data)

Notes and cautions: wrapping sockets with SSL (ssl.wrap_socket) is only required if the proxy will terminate/inspect TLS (a true MITM) — that requires creating/signing certificates and making clients trust your CA. For plain tunneling do not wrap sockets. For Python 3, BaseHTTPServer moved to http.server and httplib became http.client; see the CONNECT semantics in RFC 7231 and the Python handler docs at http.server.

Recommended Answers

All 2 Replies

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.