Skip to content Skip to sidebar Skip to footer

How Do I Respond To A "connect" Method Request In A Proxy Server Using Socket In Python?

I am currently programming a proxy server using httplib, and when I try to connect to HTTPS websites (such as facebook and google) my client sends me 'CONNECT' requests that look l

Solution 1:

I am replying after this long time because I recently worked with this concept. It may help others.

To work with CONNECT http method proxy need to create socket connection with the server's https port (ex. 443). Once connection is established you can send "HTTP/1.1 200 Connection established" as response.

After this client and server with communicate with each other through proxy. Proxy has to just transfer data from client socket to server socket and vice versa. Client and server will exchange certificate information for handshaking, once handshaking is done they will start sharing data in encrypted format so proxy will not be able to understand anything.

May the following code helps you.

def _read_write(self):
    socs = [self.client, self.target]
    count = 0while1:
        count += 1
        (recv, _, error) = select.select(socs, [], socs, 3)
        iferror:
            breakif recv:
            for in_ in recv:
                data = in_.recv(BUFLEN)
                if in_ is self.client:
                    out = self.target
                else:
                    out = self.client
                if data:
                    out.send(data)
                    print(data)
                    count = 0if count == time_out_max:
            break

Hope this answer helps anyone in need. As I had to go through a lot of things to find this answer.

Solution 2:

I met basically the same problem and the way I finally solved this is to look up for sample code on GitHub. It turns out that the proxy2 project is quite helpful. Some relevant code that is pretty similar to rushikesh's answer:

defconnect_relay(self):
        address = self.path.split(':', 1)
        address[1] = int(address[1]) or443try:
            s = socket.create_connection(address, timeout=self.timeout)
        except Exception as e:
            self.send_error(502)
            return
        self.send_response(200, 'Connection Established')
        self.end_headers()

        conns = [self.connection, s]
        self.close_connection = 0whilenot self.close_connection:
            rlist, wlist, xlist = select.select(conns, [], conns, self.timeout)
            if xlist ornot rlist:
                breakfor r in rlist:
                other = conns[1] if r is conns[0] else conns[0]
                data = r.recv(8192)
                ifnot data:
                    self.close_connection = 1break
                other.sendall(data)

You can find more information in the repo.

Post a Comment for "How Do I Respond To A "connect" Method Request In A Proxy Server Using Socket In Python?"