-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.py
More file actions
215 lines (190 loc) · 9.37 KB
/
Copy pathproxy.py
File metadata and controls
215 lines (190 loc) · 9.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import socket
import threading
import hashlib
import os
import re
import argparse
import configparser
import sys
# ---------------------------------------------------------------------------
# Configuration loading
#
# Values are resolved in this priority order (highest wins):
# 1. CLI arguments (--host, --port, --username, --password, etc.)
# 2. Environment variables (PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASSWORD,
# LISTEN_HOST, LISTEN_PORT)
# 3. Config file (proxy.conf by default, or path given with --config)
# 4. Built-in defaults (listen on 127.0.0.1:3128)
#
# Copy proxy.conf.example to proxy.conf and fill in your details.
# proxy.conf is listed in .gitignore so credentials are never committed.
# ---------------------------------------------------------------------------
def load_config():
parser = argparse.ArgumentParser(
description="Digest Proxy Bridge — local clear proxy with HTTP Digest Authentication."
)
parser.add_argument("--config", default="proxy.conf",
metavar="FILE",
help="Path to INI config file (default: proxy.conf)")
parser.add_argument("--host", help="Upstream proxy hostname or IP")
parser.add_argument("--port", type=int, help="Upstream proxy port")
parser.add_argument("--username", help="Proxy username")
parser.add_argument("--password", help="Proxy password")
parser.add_argument("--listen-host", dest="listen_host",
help="Local address to listen on (default: 127.0.0.1)")
parser.add_argument("--listen-port", dest="listen_port", type=int,
help="Local port to listen on (default: 3128)")
args = parser.parse_args()
# --- defaults ---
cfg = {
"upstream_host": None,
"upstream_port": 8080,
"username": None,
"password": None,
"listen_host": "127.0.0.1",
"listen_port": 3128,
}
# --- config file (lowest priority) ---
ini = configparser.ConfigParser()
config_path = args.config
if os.path.exists(config_path):
ini.read(config_path)
sec = "proxy"
if ini.has_section(sec):
if ini.has_option(sec, "upstream_host"): cfg["upstream_host"] = ini.get(sec, "upstream_host")
if ini.has_option(sec, "upstream_port"): cfg["upstream_port"] = ini.getint(sec, "upstream_port")
if ini.has_option(sec, "username"): cfg["username"] = ini.get(sec, "username")
if ini.has_option(sec, "password"): cfg["password"] = ini.get(sec, "password")
if ini.has_option(sec, "listen_host"): cfg["listen_host"] = ini.get(sec, "listen_host")
if ini.has_option(sec, "listen_port"): cfg["listen_port"] = ini.getint(sec, "listen_port")
elif config_path != "proxy.conf":
# Only error if the user explicitly requested a non-default file
print(f"Error: config file not found: {config_path}", file=sys.stderr)
sys.exit(1)
# --- environment variables ---
env_map = {
"PROXY_HOST": ("upstream_host", str),
"PROXY_PORT": ("upstream_port", int),
"PROXY_USER": ("username", str),
"PROXY_PASSWORD": ("password", str),
"LISTEN_HOST": ("listen_host", str),
"LISTEN_PORT": ("listen_port", int),
}
for env_key, (cfg_key, cast) in env_map.items():
val = os.environ.get(env_key)
if val:
cfg[cfg_key] = cast(val)
# --- CLI arguments (highest priority) ---
if args.host: cfg["upstream_host"] = args.host
if args.port: cfg["upstream_port"] = args.port
if args.username: cfg["username"] = args.username
if args.password: cfg["password"] = args.password
if args.listen_host: cfg["listen_host"] = args.listen_host
if args.listen_port: cfg["listen_port"] = args.listen_port
# --- validate ---
missing = [k for k in ("upstream_host", "username", "password") if not cfg[k]]
if missing:
print(f"Error: missing required configuration: {', '.join(missing)}", file=sys.stderr)
print("Provide values via proxy.conf, environment variables, or CLI arguments.", file=sys.stderr)
print("Copy proxy.conf.example to proxy.conf and fill in your details.", file=sys.stderr)
print("Run with --help for CLI usage.", file=sys.stderr)
sys.exit(1)
return cfg
_cfg = load_config()
UPSTREAM_PROXY_HOST = _cfg["upstream_host"]
UPSTREAM_PROXY_PORT = _cfg["upstream_port"]
USERNAME = _cfg["username"]
PASSWORD = _cfg["password"]
LISTEN_HOST = _cfg["listen_host"]
LISTEN_PORT = _cfg["listen_port"]
def get_digest_auth_header(method, uri, realm, nonce, qop, nc="00000001", cnonce=None):
if not cnonce:
cnonce = hashlib.md5(os.urandom(16)).hexdigest()[:16]
ha1 = hashlib.md5(f"{USERNAME}:{realm}:{PASSWORD}".encode()).hexdigest()
ha2 = hashlib.md5(f"{method}:{uri}".encode()).hexdigest()
if qop and "auth" in qop:
qop = "auth"
response = hashlib.md5(f"{ha1}:{nonce}:{nc}:{cnonce}:{qop}:{ha2}".encode()).hexdigest()
return (f'Digest username="{USERNAME}", realm="{realm}", nonce="{nonce}", '
f'uri="{uri}", qop={qop}, nc={nc}, cnonce="{cnonce}", response="{response}"')
else:
response = hashlib.md5(f"{ha1}:{nonce}:{ha2}".encode()).hexdigest()
return f'Digest username="{USERNAME}", realm="{realm}", nonce="{nonce}", uri="{uri}", response="{response}"'
def parse_authenticate_header(header_bytes):
header_str = header_bytes.decode('latin-1', 'ignore')
match = re.search(r'Proxy-Authenticate: Digest\s+(.*)', header_str, re.IGNORECASE)
if not match: return None
params = {}
for part in re.split(r',\s*', match.group(1)):
if '=' in part:
k, v = part.split('=', 1)
params[k.strip()] = v.strip().strip('"')
return params
def pipe_sockets(src, dst):
try:
while True:
data = src.recv(16384)
if not data: break
dst.sendall(data)
except: pass
finally:
src.close()
dst.close()
def handle_client(client_sock):
try:
request_raw = client_sock.recv(16384)
if not request_raw: return
first_line_parts = request_raw.split(b'\r\n')[0].decode('latin-1').split()
if len(first_line_parts) < 3: return
method, target, version = first_line_parts
print(f">>> {method} {target}")
# Force Connection: close to ensure fresh handshake per request
headers_section = request_raw.split(b'\r\n', 1)[1]
new_headers = []
for line in headers_section.split(b'\r\n'):
line_l = line.lower()
if line and not any(line_l.startswith(h) for h in [b"connection:", b"proxy-connection:", b"proxy-authorization:"]):
new_headers.append(line)
new_headers.append(b"Connection: close")
new_headers.append(b"Proxy-Connection: close")
clean_req = f"{method} {target} {version}\r\n".encode() + b"\r\n".join(new_headers) + b"\r\n\r\n"
upstream = socket.create_connection((UPSTREAM_PROXY_HOST, UPSTREAM_PROXY_PORT))
upstream.sendall(clean_req)
response_chunk = upstream.recv(16384)
if b" 407 " in response_chunk[:100]:
while b"\r\n\r\n" not in response_chunk:
more = upstream.recv(8192)
if not more: break
response_chunk += more
params = parse_authenticate_header(response_chunk)
if params:
auth_val = get_digest_auth_header(method, target, params.get('realm'),
params.get('nonce'), params.get('qop'))
new_headers.append(f"Proxy-Authorization: {auth_val}".encode())
auth_req = f"{method} {target} {version}\r\n".encode() + b"\r\n".join(new_headers) + b"\r\n\r\n"
upstream.close()
upstream = socket.create_connection((UPSTREAM_PROXY_HOST, UPSTREAM_PROXY_PORT))
upstream.sendall(auth_req)
response_chunk = upstream.recv(16384)
if method == "CONNECT" and (b" 200 " in response_chunk[:50] or b"connection established" in response_chunk.lower()):
client_sock.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
threading.Thread(target=pipe_sockets, args=(client_sock, upstream), daemon=True).start()
threading.Thread(target=pipe_sockets, args=(upstream, client_sock), daemon=True).start()
else:
client_sock.sendall(response_chunk)
threading.Thread(target=pipe_sockets, args=(client_sock, upstream), daemon=True).start()
threading.Thread(target=pipe_sockets, args=(upstream, client_sock), daemon=True).start()
except Exception as e:
print(f"Error: {e}")
client_sock.close()
def main():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((LISTEN_HOST, LISTEN_PORT))
server.listen(100)
print(f"Binary-Safe Digest Bridge running on {LISTEN_HOST}:{LISTEN_PORT}")
while True:
client, _ = server.accept()
threading.Thread(target=handle_client, args=(client,), daemon=True).start()
if __name__ == "__main__":
main()