'Python socket with proxy. Authentication Error (407)
Thank you for reading. I was able to make a request with a socket connected to a proxy. But, return a 407. That is, there is an error in authentication in the proxy.
I put a Headers ['proxy-yauthorization'], but it doesn't work. It is sent with Basic + "User: Pass" based64.
def http_proxy_connect(address, proxy = None, auth = None, headers = {}):
import socket
import base64
def valid_address(addr):
""" Verify that an IP/port tuple is valid """
return isinstance(addr, (list, tuple)) and len(addr) == 2 and isinstance(addr[0], str) and isinstance(addr[1], (int, int))
if not valid_address(address):
raise ValueError('Invalid target address')
if proxy == None:
s = socket.socket()
s.connect(address)
return s, 0, {}
if not valid_address(proxy):
raise ValueError('Invalid proxy address')
headers = {
'host': address[0]
}
headers['proxy-authorization'] = 'Basic ' + auth
headers['Proxy-Authorization'] = 'Basic ' + auth
headers['Proxy-Authenticate'] = 'Basic'
s = socket.socket()
s.connect(proxy)
fp = s.makefile('wr')
fp.write('CONNECT %s:%d HTTP/1.0\r\n' % address)
fp.write('\r\n'.join('%s: %s' % (k, v) for (k, v) in headers.items()) + '\r\n\r\n')
print('\r\n'.join('%s: %s' % (k, v) for (k, v) in headers.items()) + '\r\n\r\n')
fp.flush()
statusline = fp.readline().rstrip('\r\n')
if statusline.count(' ') < 2:
fp.close()
s.close()
raise IOError('Bad response')
version, status, statusmsg = statusline.split(' ', 2)
if not version in ('HTTP/1.0', 'HTTP/1.1'):
fp.close()
s.close()
raise IOError('Unsupported HTTP version')
try:
status = int(status)
except ValueError:
fp.close()
s.close()
raise IOError('Bad response')
response_headers = {}
while True:
tl = ''
l = fp.readline().rstrip('\r\n')
if l == '':
break
if not ':' in l:
continue
k, v = l.split(':', 1)
response_headers[k.strip().lower()] = v.strip()
fp.close()
return (s, status, response_headers)
print(http_proxy_connect(('xxxxx',80), ('xxxxx',50000), 'user:pass in base64!'));
I am currently sending in Headers ['proxy-yauthorization'], "Basic User: Pass" in base64.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
