forked from genotrance/px
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpx.py
executable file
·1935 lines (1630 loc) · 65.1 KB
/
px.py
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"Px is an HTTP proxy server to automatically authenticate through an NTLM proxy"
from __future__ import print_function
__version__ = "0.4.0"
import base64
import ctypes
import ctypes.wintypes
import multiprocessing
import os
import select
import signal
import socket
import sys
import threading
import time
import traceback
# Print if possible
def pprint(*objs):
try:
print(*objs)
except:
pass
# Dependencies
try:
import concurrent.futures
except ImportError:
pprint("Requires module futures")
sys.exit()
try:
import netaddr
except ImportError:
pprint("Requires module netaddr")
sys.exit()
try:
import psutil
except ImportError:
pprint("Requires module psutil")
sys.exit()
try:
import pywintypes
import sspi
except ImportError:
pprint("Requires module pywin32")
sys.exit()
try:
import winkerberos
except ImportError:
pprint("Requires module winkerberos")
sys.exit()
try:
import ntlm_auth.ntlm
except ImportError:
pprint("Requires module ntlm-auth")
sys.exit()
try:
import keyring
import keyring.backends.Windows
keyring.set_keyring(keyring.backends.Windows.WinVaultKeyring())
except ImportError:
pprint("Requires module keyring")
sys.exit()
# Python 2.x vs 3.x support
try:
import configparser
import http.server as httpserver
import socketserver
import urllib.parse as urlparse
import winreg
except ImportError:
import ConfigParser as configparser
import SimpleHTTPServer as httpserver
import SocketServer as socketserver
import urlparse
import _winreg as winreg
os.getppid = psutil.Process().ppid
PermissionError = WindowsError
HELP = """Px v%s
An HTTP proxy server to automatically authenticate through an NTLM proxy
Usage:
px [FLAGS]
python px.py [FLAGS]
Actions:
--save
Save configuration to px.ini or file specified with --config
Allows setting up Px config directly from command line
Values specified on CLI override any values in existing config file
Values not specified on CLI or config file are set to defaults
--install
Add Px to the Windows registry to run on startup
--uninstall
Remove Px from the Windows registry
--quit
Quit a running instance of Px.exe
Configuration:
--config=
Specify config file. Valid file path, default: px.ini in working directory
--proxy= --server= proxy:server= in INI file
NTLM server(s) to connect through. IP:port, hostname:port
Multiple proxies can be specified comma separated. Px will iterate through
and use the one that works. Required field unless --noproxy is defined. If
remote server is not in noproxy list and proxy is undefined, Px will reject
the request
--pac= proxy:pac=
PAC file to use to connect
Use in place of server if PAC file should be loaded from a custom URL or
file location instead of from Internet Options
--listen= proxy:listen=
IP interface to listen on. Valid IP address, default: 127.0.0.1
--port= proxy:port=
Port to run this proxy. Valid port number, default: 3128
--gateway proxy:gateway=
Allow remote machines to use proxy. 0 or 1, default: 0
Overrides 'listen' and binds to all interfaces
--hostonly proxy:hostonly=
Allow only local interfaces to use proxy. 0 or 1, default: 0
Px allows all IP addresses assigned to local interfaces to use the service.
This allows local apps as well as VM or container apps to use Px when in a
NAT config. Px does this by listening on all interfaces and overriding the
allow list.
--allow= proxy:allow=
Allow connection from specific subnets. Comma separated, default: *.*.*.*
Whitelist which IPs can use the proxy. --hostonly overrides any definitions
unless --gateway mode is also specified
127.0.0.1 - specific ip
192.168.0.* - wildcards
192.168.0.1-192.168.0.255 - ranges
192.168.0.1/24 - CIDR
--noproxy= proxy:noproxy=
Direct connect to specific subnets like a regular proxy. Comma separated
Skip the NTLM proxy for connections to these subnets
127.0.0.1 - specific ip
192.168.0.* - wildcards
192.168.0.1-192.168.0.255 - ranges
192.168.0.1/24 - CIDR
--useragent= proxy:useragent=
Override or send User-Agent header on client's behalf
--username= proxy:username=
Authentication to use when SSPI is unavailable. Format is domain\\username
Service name "Px" and this username are used to retrieve the password using
Python keyring. Px only retrieves credentials and storage should be done
directly in the keyring backend.
On Windows, Credential Manager is the backed and can be accessed from
Control Panel > User Accounts > Credential Manager > Windows Credentials.
Create a generic credential with Px as the network address, this username
and corresponding password.
--auth= proxy:auth=
Force instead of discovering upstream proxy type
By default, Px will attempt to discover the upstream proxy type and either
use pywin32/ntlm-auth for NTLM auth or winkerberos for Kerberos or Negotiate
auth. This option will force either NTLM, Kerberos or Basic and not query the
upstream proxy type.
--workers= settings:workers=
Number of parallel workers (processes). Valid integer, default: 2
--threads= settings:threads=
Number of parallel threads per worker (process). Valid integer, default: 5
--idle= settings:idle=
Idle timeout in seconds for HTTP connect sessions. Valid integer, default: 30
--socktimeout= settings:socktimeout=
Timeout in seconds for connections before giving up. Valid float, default: 20
--proxyreload= settings:proxyreload=
Time interval in seconds before refreshing proxy info. Valid int, default: 60
Proxy info reloaded from a PAC file found via WPAD or AutoConfig URL, or
manual proxy info defined in Internet Options
--foreground settings:foreground=
Run in foreground when frozen or with pythonw.exe. 0 or 1, default: 0
Px will attach to the console and write to it even though the prompt is
available for further commands. CTRL-C in the console will exit Px
--debug settings:log=
Enable debug logging. default: 0
Logs are written to working directory and over-written on startup
A log is automatically created if Px crashes for some reason
--uniqlog
Generate unique log file names
Prevents logs from being overwritten on subsequent runs. Also useful if
running multiple instances of Px""" % __version__
# Windows version
# 6.1 = Windows 7
# 6.2 = Windows 8
# 6.3 = Windows 8.1
# 10.0 = Windows 10
WIN_VERSION = float(
str(sys.getwindowsversion().major) + "." +
str(sys.getwindowsversion().minor))
# Proxy modes - source of proxy info
MODE_NONE = 0
MODE_CONFIG = 1
MODE_AUTO = 2
MODE_PAC = 3
MODE_MANUAL = 4
MODE_CONFIG_PAC = 5
class State(object):
allow = netaddr.IPGlob("*.*.*.*")
config = None
domain = ""
exit = False
hostonly = False
logger = None
noproxy = netaddr.IPSet([])
noproxy_hosts = []
pac = ""
proxy_mode = MODE_NONE
proxy_refresh = None
proxy_server = []
proxy_type = {}
stdout = None
useragent = ""
username = ""
auth = None
ini = "px.ini"
max_disconnect = 3
max_line = 65536 + 1
# Locks for thread synchronization;
# multiprocess sync isn't neccessary because State object is only shared by
# threads but every process has it's own State object
proxy_type_lock = threading.Lock()
proxy_mode_lock = threading.Lock()
class Response(object):
__slots__ = ["code", "length", "headers", "data", "body", "chunked", "close"]
def __init__(self, code=503):
self.code = code
self.length = 0
self.headers = []
self.data = None
self.body = False
self.chunked = False
self.close = False
class Log(object):
def __init__(self, name, mode):
self.file = open(name, mode)
self.stdout = sys.stdout
self.stderr = sys.stderr
sys.stdout = self
sys.stderr = self
def close(self):
sys.stdout = self.stdout
sys.stderr = self.stderr
self.file.close()
def write(self, data):
try:
self.file.write(data)
except:
pass
if self.stdout is not None:
self.stdout.write(data)
self.flush()
def flush(self):
self.file.flush()
os.fsync(self.file.fileno())
if self.stdout is not None:
self.stdout.flush()
def dprint(msg):
if State.logger is not None:
# Do locking to avoid mixing the output of different threads as there are
# two calls to print which could otherwise interleave
sys.stdout.write(
multiprocessing.current_process().name + ": " +
threading.current_thread().name + ": " + str(int(time.time())) +
": " + sys._getframe(1).f_code.co_name + ": " + msg + "\n")
def dfile():
name = multiprocessing.current_process().name
if "--quit" in sys.argv:
name = "quit"
if "--uniqlog" in sys.argv:
name = "%s-%f" % (name, time.time())
logfile = os.path.join(os.path.dirname(get_script_path()),
"debug-%s.log" % name)
return logfile
def reopen_stdout():
clrstr = "\r" + " " * 80 + "\r"
if State.logger is None:
State.stdout = sys.stdout
sys.stdout = open("CONOUT$", "w")
sys.stdout.write(clrstr)
else:
State.stdout = State.logger.stdout
State.logger.stdout = open("CONOUT$", "w")
State.logger.stdout.write(clrstr)
def restore_stdout():
if State.logger is None:
sys.stdout.close()
sys.stdout = State.stdout
else:
State.logger.stdout.close()
State.logger.stdout = State.stdout
###
# Auth support
def b64decode(val):
try:
return base64.decodebytes(val.encode("utf-8"))
except AttributeError:
return base64.decodebytes(val)
def b64encode(val):
try:
return base64.encodebytes(val.encode("utf-8"))
except AttributeError:
return base64.encodebytes(val)
class AuthMessageGenerator:
def __init__(self, proxy_type, proxy_server_address):
pwd = ""
if State.username:
key = State.username
if State.domain != "":
key = State.domain + "\\" + State.username
pwd = keyring.get_password("Px", key)
if proxy_type == "NTLM":
if not pwd:
self.ctx = sspi.ClientAuth("NTLM",
os.environ.get("USERNAME"), scflags=0)
self.get_response = self.get_response_sspi
else:
self.ctx = ntlm_auth.ntlm.NtlmContext(
State.username, pwd, State.domain, "", ntlm_compatibility=3)
self.get_response = self.get_response_ntlm
elif proxy_type == "BASIC":
if not State.username:
dprint("No username configured for Basic authentication")
elif not pwd:
dprint("No password configured for Basic authentication")
else:
# Colons are forbidden in usernames and passwords for basic auth
# but since this can happen very easily, we make a special check
# just for colons so people immediately understand that and don't
# have to look up other resources.
if ":" in State.username or ":" in pwd:
dprint("Credentials contain invalid colon character")
else:
# Additionally check for invalid control characters as per
# RFC5234 Appendix B.1 (section CTL)
illegal_control_characters = "".join(
chr(i) for i in range(0x20)) + "\u007F"
if any(char in State.username or char in pwd
for char in illegal_control_characters):
dprint("Credentials contain invalid characters: %s" % ", ".join("0x" + "%x" % ord(char) for char in illegal_control_characters))
else:
# Remove newline appended by base64 function
self.ctx = b64encode(
"%s:%s" % (State.username, pwd))[:-1].decode()
self.get_response = self.get_response_basic
else:
principal = None
if pwd:
if State.domain:
principal = (urlparse.quote(State.username) + "@" +
urlparse.quote(State.domain) + ":" + urlparse.quote(pwd))
else:
principal = (urlparse.quote(State.username) + ":" +
urlparse.quote(pwd))
_, self.ctx = winkerberos.authGSSClientInit("HTTP@" +
proxy_server_address, principal=principal, gssflags=0,
mech_oid=winkerberos.GSS_MECH_OID_SPNEGO)
self.get_response = self.get_response_wkb
def get_response_sspi(self, challenge=None):
dprint("pywin32 SSPI")
if challenge:
challenge = b64decode(challenge)
output_buffer = None
try:
error_msg, output_buffer = self.ctx.authorize(challenge)
except pywintypes.error:
traceback.print_exc(file=sys.stdout)
return None
response_msg = b64encode(output_buffer[0].Buffer)
response_msg = response_msg.decode("utf-8").replace('\012', '')
return response_msg
def get_response_wkb(self, challenge=""):
dprint("winkerberos SSPI")
try:
winkerberos.authGSSClientStep(self.ctx, challenge)
auth_req = winkerberos.authGSSClientResponse(self.ctx)
except winkerberos.GSSError:
traceback.print_exc(file=sys.stdout)
return None
return auth_req
def get_response_ntlm(self, challenge=""):
dprint("ntlm-auth")
if challenge:
challenge = b64decode(challenge)
response_msg = b64encode(self.ctx.step(challenge))
response_msg = response_msg.decode("utf-8").replace('\012', '')
return response_msg
def get_response_basic(self, challenge=""):
dprint("basic")
return self.ctx
###
# Proxy handler
class Proxy(httpserver.SimpleHTTPRequestHandler):
protocol_version = "HTTP/1.1"
# Contains the proxy servers responsible for the url this Proxy instance
# (aka thread) serves
proxy_servers = []
proxy_socket = None
def handle_one_request(self):
try:
httpserver.SimpleHTTPRequestHandler.handle_one_request(self)
except socket.error as e:
dprint("Socket error: %s" % e)
if not hasattr(self, "_host_disconnected"):
self._host_disconnected = 1
dprint("Host disconnected")
elif self._host_disconnected < State.max_disconnect:
self._host_disconnected += 1
dprint("Host disconnected: %d" % self._host_disconnected)
else:
dprint("Closed connection to avoid infinite loop")
self.close_connection = True
def address_string(self):
host, port = self.client_address[:2]
#return socket.getfqdn(host)
return host
def log_message(self, format, *args):
dprint(format % args)
def do_socket_connect(self, destination=None):
# Already connected?
if self.proxy_socket is not None:
return True
dests = list(self.proxy_servers) if destination is None else [
destination]
for dest in dests:
dprint("New connection: " + str(dest))
proxy_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
proxy_socket.connect(dest)
self.proxy_address = dest
self.proxy_socket = proxy_socket
break
except Exception as e:
dprint("Connect failed: %s" % e)
# move a non reachable proxy to the end of the proxy list;
if len(self.proxy_servers) > 1:
# append first and then remove, this should ensure thread
# safety with manual configurated proxies (in this case
# self.proxy_servers references the shared
# State.proxy_server)
self.proxy_servers.append(dest)
self.proxy_servers.remove(dest)
if self.proxy_socket is not None:
return True
return False
def do_socket(self, xheaders={}, destination=None):
dprint("Entering")
# Connect to proxy or destination
if not self.do_socket_connect(destination):
return Response(408)
# No chit chat on SSL
if destination is not None and self.command == "CONNECT":
return Response(200)
cl = 0
chk = False
expect = False
keepalive = False
ua = False
cmdstr = "%s %s %s\r\n" % (self.command, self.path, self.request_version)
self.proxy_socket.sendall(cmdstr.encode("utf-8"))
dprint(cmdstr.strip())
for header in self.headers:
hlower = header.lower()
if hlower == "user-agent" and State.useragent != "":
ua = True
h = "%s: %s\r\n" % (header, State.useragent)
else:
h = "%s: %s\r\n" % (header, self.headers[header])
self.proxy_socket.sendall(h.encode("utf-8"))
if hlower != "authorization":
dprint("Sending %s" % h.strip())
else:
dprint("Sending %s: sanitized len(%d)" % (
header, len(self.headers[header])))
if hlower == "content-length":
cl = int(self.headers[header])
elif (hlower == "expect" and
self.headers[header].lower() == "100-continue"):
expect = True
elif hlower == "proxy-connection":
keepalive = True
elif (hlower == "transfer-encoding" and
self.headers[header].lower() == "chunked"):
dprint("CHUNKED data")
chk = True
if not keepalive and self.request_version.lower() == "http/1.0":
xheaders["Proxy-Connection"] = "keep-alive"
if not ua and State.useragent != "":
xheaders["User-Agent"] = State.useragent
for header in xheaders:
h = ("%s: %s\r\n" % (header, xheaders[header])).encode("utf-8")
self.proxy_socket.sendall(h)
if header.lower() != "proxy-authorization":
dprint("Sending extra %s" % h.strip())
else:
dprint("Sending extra %s: sanitized len(%d)" % (
header, len(xheaders[header])))
self.proxy_socket.sendall(b"\r\n")
if self.command in ["POST", "PUT", "PATCH"]:
if not hasattr(self, "body"):
dprint("Getting body for POST/PUT/PATCH")
if cl:
self.body = self.rfile.read(cl)
else:
self.body = self.rfile.read()
dprint("Sending body for POST/PUT/PATCH: %d = %d" % (
cl or -1, len(self.body)))
self.proxy_socket.sendall(self.body)
self.proxy_fp = self.proxy_socket.makefile("rb")
resp = Response()
if self.command != "HEAD":
resp.body = True
# Response code
for i in range(2):
dprint("Reading response code")
line = self.proxy_fp.readline(State.max_line)
if line == b"\r\n":
line = self.proxy_fp.readline(State.max_line)
try:
resp.code = int(line.split()[1])
except (ValueError, IndexError):
dprint("Bad response %s" % line)
if line == b"":
dprint("Client closed connection")
return Response(444)
if (b"connection established" in line.lower() or
resp.code == 204 or resp.code == 304):
resp.body = False
dprint("Response code: %d " % resp.code + str(resp.body))
# Get response again if 100-Continue
if not (expect and resp.code == 100):
break
# Headers
dprint("Reading response headers")
while not State.exit:
line = self.proxy_fp.readline(State.max_line).decode("utf-8")
if line == b"":
if self.proxy_socket:
self.proxy_socket.shutdown(socket.SHUT_WR)
self.proxy_socket.close()
self.proxy_socket = None
dprint("Proxy closed connection: %s" % resp.code)
return Response(444)
if line == "\r\n":
break
nv = line.split(":", 1)
if len(nv) != 2:
dprint("Bad header =>%s<=" % line)
continue
name = nv[0].strip()
value = nv[1].strip()
resp.headers.append((name, value))
if name.lower() != "proxy-authenticate":
dprint("Received %s: %s" % (name, value))
else:
dprint("Received %s: sanitized (%d)" % (name, len(value)))
if name.lower() == "content-length":
resp.length = int(value)
if not resp.length:
resp.body = False
elif (name.lower() == "transfer-encoding" and
value.lower() == "chunked"):
resp.chunked = True
resp.body = True
elif (name.lower() in ["proxy-connection", "connection"] and
value.lower() == "close"):
resp.close = True
return resp
def do_proxy_type(self):
# Connect to proxy
if not hasattr(self, "proxy_address"):
if not self.do_socket_connect():
return Response(408), None
State.proxy_type_lock.acquire()
try:
# Read State.proxy_type only once and use value for function return
# if it is not None; State.proxy_type should only be read here to
# avoid getting None after successfully identifying the proxy type
# if another thread clears it with load_proxy
proxy_type = State.proxy_type.get(self.proxy_address, State.auth)
if proxy_type is None:
# New proxy, don't know type yet
dprint("Searching proxy type")
resp = self.do_socket()
proxy_auth = ""
for header in resp.headers:
if header[0].lower() == "proxy-authenticate":
proxy_auth += header[1] + " "
for auth in proxy_auth.split():
if auth.upper() in ["NTLM", "KERBEROS", "NEGOTIATE", "BASIC"]:
proxy_type = auth
break
if proxy_type is not None:
# Writing State.proxy_type only once but use local variable
# as return value to avoid losing the query result (for the
# current request) by clearing State.proxy_type in load_proxy
State.proxy_type[self.proxy_address] = proxy_type
dprint("Auth mechanisms: " + proxy_auth)
dprint("Selected: " + str(self.proxy_address) + ": " +
str(proxy_type))
return resp, proxy_type
return Response(407), proxy_type
finally:
State.proxy_type_lock.release()
def do_transaction(self):
dprint("Entering")
ipport = self.get_destination()
if ipport not in [False, True]:
dprint("Skipping auth proxying")
resp = self.do_socket(destination=ipport)
elif ipport:
# Get proxy type directly from do_proxy_type instead by accessing
# State.proxy_type do avoid a race condition with clearing
# State.proxy_type in load_proxy which sometimes led to a proxy type
# of None (clearing State.proxy_type in one thread was done after
# another thread's do_proxy_type but before accessing
# State.proxy_type in the second thread)
resp, proxy_type = self.do_proxy_type()
if resp.code == 407:
# Unknown auth mechanism
if proxy_type is None:
dprint("Unknown auth mechanism expected")
return resp
# Generate auth message
ntlm = AuthMessageGenerator(proxy_type, self.proxy_address[0])
ntlm_resp = ntlm.get_response()
if ntlm_resp is None:
dprint("Bad auth response")
return Response(503)
self.fwd_data(resp, flush=True)
hconnection = ""
for i in ["connection", "Connection"]:
if i in self.headers:
hconnection = self.headers[i]
del self.headers[i]
dprint("Remove header %s: %s" % (i, hconnection))
# Send auth message
resp = self.do_socket({
"Proxy-Authorization": "%s %s" % (proxy_type, ntlm_resp),
"Proxy-Connection": "Keep-Alive"
})
if resp.code == 407:
dprint("Auth required")
ntlm_challenge = ""
for header in resp.headers:
if (header[0].lower() == "proxy-authenticate" and
proxy_type.upper() in header[1].upper()):
h = header[1].split()
if len(h) == 2:
ntlm_challenge = h[1]
break
if ntlm_challenge:
dprint("Challenged")
ntlm_resp = ntlm.get_response(ntlm_challenge)
if ntlm_resp is None:
dprint("Bad auth response")
return Response(503)
self.fwd_data(resp, flush=True)
if hconnection != "":
self.headers["Connection"] = hconnection
dprint("Restore header Connection: " + hconnection)
# Reply to challenge
resp = self.do_socket({
"Proxy-Authorization": "%s %s" % (
proxy_type, ntlm_resp)
})
else:
dprint("Didn't get challenge, auth didn't work")
else:
dprint("No auth required cached")
else:
dprint("No auth required")
else:
dprint("No proxy server specified and not in noproxy list")
return Response(501)
return resp
def do_HEAD(self):
dprint("Entering")
self.do_GET()
dprint("Done")
def do_PAC(self):
resp = Response(404)
if State.proxy_mode in [MODE_PAC, MODE_CONFIG_PAC]:
pac = State.pac
if "file://" in State.pac:
pac = file_url_to_local_path(State.pac)
dprint(pac)
try:
resp.code = 200
with open(pac) as p:
resp.data = p.read().encode("utf-8")
resp.body = True
resp.headers = [
("Content-Length", len(resp.data)),
("Content-Type", "application/x-ns-proxy-autoconfig")
]
except:
traceback.print_exc(file=sys.stdout)
return resp
def do_GET(self):
dprint("Entering")
dprint("Path = " + self.path)
if "/PxPACFile.pac" in self.path:
resp = self.do_PAC()
else:
resp = self.do_transaction()
if resp.code >= 400:
dprint("Error %d" % resp.code)
self.fwd_resp(resp)
dprint("Done")
def do_POST(self):
dprint("Entering")
self.do_GET()
dprint("Done")
def do_PUT(self):
dprint("Entering")
self.do_GET()
dprint("Done")
def do_DELETE(self):
dprint("Entering")
self.do_GET()
dprint("Done")
def do_PATCH(self):
dprint("Entering")
self.do_GET()
dprint("Done")
def do_CONNECT(self):
dprint("Entering")
for i in ["connection", "Connection"]:
if i in self.headers:
del self.headers[i]
dprint("Remove header " + i)
cl = 0
cs = 0
resp = self.do_transaction()
if resp.code >= 400:
dprint("Error %d" % resp.code)
self.fwd_resp(resp)
else:
# Proxy connection may be already closed due to header
# (Proxy-)Connection: close received from proxy -> forward this to
# the client
if self.proxy_socket is None:
dprint("Proxy connection closed")
self.send_response(200, "True")
self.send_header("Proxy-Connection", "close")
self.end_headers()
else:
dprint("Tunneling through proxy")
self.send_response(200, "Connection established")
self.send_header("Proxy-Agent", self.version_string())
self.end_headers()
# sockets will be removed from these lists, when they are
# detected as closed by remote host; wlist contains sockets
# only when data has to be written
rlist = [self.connection, self.proxy_socket]
wlist = []
# data to be written to client connection and proxy socket
cdata = []
sdata = []
idle = State.config.getint("settings", "idle")
max_idle = time.time() + idle
while not State.exit and (rlist or wlist):
(ins, outs, exs) = select.select(rlist, wlist, rlist, idle)
if exs:
break
if ins:
for i in ins:
if i is self.proxy_socket:
out = self.connection
wdata = cdata
source = "proxy"
else:
out = self.proxy_socket
wdata = sdata
source = "client"
data = i.recv(4096)
if data:
cl += len(data)
# Prepare data to send it later in outs section
wdata.append(data)
if out not in outs:
outs.append(out)
max_idle = time.time() + idle
else:
# No data means connection closed by remote host
dprint("Connection closed by %s" % source)
# Because tunnel is closed on one end there is
# no need to read from both ends
del rlist[:]
# Do not write anymore to the closed end
if i in wlist:
wlist.remove(i)
if i in outs:
outs.remove(i)
if outs:
for o in outs:
if o is self.proxy_socket:
wdata = sdata
else:
wdata = cdata
data = wdata[0]
# socket.send() may sending only a part of the data
# (as documentation says). To ensure sending all data
bsnt = o.send(data)
if bsnt > 0:
if bsnt < len(data):
# Not all data was sent; store data not
# sent and ensure select() get's it when
# the socket can be written again
wdata[0] = data[bsnt:]
if o not in wlist:
wlist.append(o)
else:
wdata.pop(0)
if not data and o in wlist:
wlist.remove(o)
cs += bsnt
else:
dprint("No data sent")
max_idle = time.time() + idle
if max_idle < time.time():
# No data in timeout seconds
dprint("Proxy connection timeout")
break
# After serving the proxy tunnel it could not be used for samething else.
# A proxy doesn't really know, when a proxy tunnnel isn't needed any
# more (there is no content length for data). So servings will be ended
# either after timeout seconds without data transfer or when at least
# one side closes the connection. Close both proxy and client
# connection if still open.
if self.proxy_socket is not None:
dprint("Cleanup proxy connection")
self.proxy_socket.shutdown(socket.SHUT_WR)
self.proxy_socket.close()
self.proxy_socket = None
self.close_connection = True
dprint("%d bytes read, %d bytes written" % (cl, cs))
dprint("Done")
def fwd_data(self, resp, flush=False):
cl = resp.length
dprint("Reading response data")
if resp.body:
if cl:
dprint("Content length %d" % cl)
while cl > 0:
if cl > 4096:
l = 4096
cl -= l
else:
l = cl
cl = 0
d = self.proxy_fp.read(l)
if not flush:
self.wfile.write(d)
elif resp.chunked:
dprint("Chunked encoding")
while not State.exit:
line = self.proxy_fp.readline(State.max_line)