How to connect to HTTPS socket server via SOCKS4 proxy

748 Views Asked by At

I am trying to connect to my HTTPS server via SOCKS4 proxy, but it seems like it is not working.

Here is my code:

headers = "GET / HTTP/1.1\r\nHost: domain.com\r\n\r\n"
import socks
import ssl
conn = socks.socksocket()
conn.set_proxy(socks.SOCKS4, host, port)
conn.connect(("domain.com", 443))
conn = ssl.create_default_context().wrap_socket(conn, server_hostname="domain.com")
conn.send(headers.encode())

After I run that code, I checked my website log and nothing happened. But if I change the connect() port to 80, it worked.

1

There are 1 best solutions below

2
On

You are connect()'ing the socks TCP connection to the HTTPS server's TLS port before creating the ssl context. Which is fine, however the SSLSocket that wrap_socket() returns will automatically call do_handshake() to negotiate a TLS session only when its connect() method is called, which you are bypassing. So, you will need to manually call do_handshake() after wrap_socket() returns and before calling send(), eg:

headers = "GET / HTTP/1.1\r\nHost: domain.com\r\n\r\n"
import socks
import ssl
conn = socks.socksocket()
conn.set_proxy(socks.SOCKS4, host, port)
conn.connect(("domain.com", 443))
conn = ssl.create_default_context().wrap_socket(conn, server_hostname="domain.com")
conn.do_handshake()
conn.send(headers.encode())