Search code examples
pythonsocketsproxyimap

PySocks proxy auhtentication failed


I'm still try create imap\pop3 proxied client. First try is on PHP is here. Now I try the same with python.

I found an answer, which good fits, so my code based is on stackowerflow answer and it work for proxy without authentication:

class SocksIMAP4SSL(IMAP4_SSL):
    def open(self, host, port=IMAP4_SSL_PORT):
        self.host = host
        self.port = port
        self.sock = create_connection(dest_pair=(host, port), proxy_type=PROXY_TYPE_HTTP, proxy_addr=PROXY_IP,
                                      proxy_port=PROXY_PORT, proxy_rdns=True, proxy_username=PROXY_AUTH_LOGIN,
                                      proxy_password=PROXY_AUTH_PASS)
        # self.sock = socket.create_connection((host, port))
        self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
        self.file = self.sslobj.makefile('rb')

But if I use proxy with authentication it always fail by reason:

socks.HTTPError: 407: Proxy Authentication Required

Proxy auth type: basic. Both login and password is correct. What I am doing wrong?


Solution

  • I used https://github.com/Anorov/PySocks, but It does not support basic authentication for HTTP proxy. A few lines solves this issue:

    http_headers = [
        b"Connect %s:%s HTTP/1.1" % (addr.encode('idna'), str(dest_port).encode()),
        b"Host: %s" % dest_addr.encode('idna')
    ]
    
    if username and password:
        http_headers.append(b"Proxy-Authorization: basic %s" % str(b64encode("%s:%s" % (username, password))))
    
    http_headers.append(b"\r\n")
    
    self.sendall(b"\r\n".join(http_headers))