forked from genotrance/px
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
387 lines (301 loc) · 10 KB
/
test.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
import multiprocessing
import os
import re
import shutil
import socket
import subprocess
import sys
import time
import traceback
import psutil
CURL = 'curl.exe -s -L -k -A "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36" -H "Accept-Language: en-US"'
CURL_PROXY = ' --proxy-ntlm '
BASEURL = ""
PROXY = ""
TESTS = []
try:
ConnectionRefusedError
except NameError:
ConnectionRefusedError = socket.error
def exec_output(cmd):
pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout
if pipe != None:
output = pipe.read().decode("UTF-8", "ignore")
else:
print("Error running curl")
sys.exit()
return output
def curl(url, proxy="", ntlm=False, filename="", head=False):
output = ""
cmd = CURL
if filename:
cmd += " -o " + filename
if head:
cmd += ' -I'
if proxy:
cmd += " --proxy " + proxy
if ntlm:
cmd += ' --proxy-ntlm -U :'
cmd += ' "%s"' % url
if "--debug" in sys.argv:
print(cmd)
return exec_output(cmd)
def getPyversion(cmd):
return int(exec_output(cmd + " -V").split(" ")[1].replace(".", ""))
def write(data, file):
with open(file, "w") as f:
f.write(data)
def check(url, proxy, port):
start = time.time()
a = curl(url, proxy=proxy, ntlm=True)
end = time.time()
ta = end - start
b = curl(url, proxy="localhost:%d" % port)
tb = time.time() - end
la = len(a)
lb = len(b)
out = 100
if la < lb:
out = la / lb * 100
elif la > lb:
out = lb / la * 100
print(" %.2f%%\t%.2fx\t%s" % (out, tb / ta, url))
def waitprocs(procs):
ret = True
while len(procs):
for i in range(len(procs)):
if not procs[i].is_alive():
if procs[i].exitcode:
ret = False
procs.pop(i)
break
time.sleep(0.1)
return ret
def run(base, port):
if not checkPxStart("localhost", port):
return False
start = time.time()
pop = ""
while True:
pop = curl(base, proxy="localhost:%d" % port)
if pop == "":
time.sleep(0.5)
else:
break
procs = []
#urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', pop)
urls = re.findall("http[s]?://[a-zA-Z_./0-9-]+", pop)
if len(urls) == 0:
print("No urls found")
return False
for url in set(urls):
p = multiprocessing.Process(target=check, args=(url, PROXY, port))
#p.daemon = True
p.start()
procs.append(p)
time.sleep(0.5)
ret = True
if not waitprocs(procs):
ret = False
end = time.time()
print((" Time: %.2fs" % (end-start)) + " sec")
return ret
def runPxTest(cmd, testproc, ips, port):
pipe = subprocess.Popen("cmd /k start /wait /min " + cmd + " --port=" + str(port), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
ret = testproc(ips, port)
pxproc = psutil.Process(pipe.pid)
for child in pxproc.children(recursive=True):
try:
child.kill()
except psutil.NoSuchProcess:
pass
try:
pxproc.kill()
except:
pass
time.sleep(0.5)
return ret
def runTest(test, python, count):
port = 3129
cmd = "px "
if python:
port = getPyversion(python) * 10
cmd = python + " px.py "
cmd += "--debug --uniqlog " + test[0] + " --port=" + str(port)
testproc = test[1]
ips = test[2]
print("Test %d: \"" % count + test[0] + "\" on port " + str(port))
p = multiprocessing.Process(target=runPxTest, args=(cmd, testproc, ips, port))
p.start()
return p
def getips():
localips = [ip[4][0] for ip in socket.getaddrinfo(socket.gethostname(), 80, socket.AF_INET)]
localips.insert(0, "127.0.0.1")
return localips
def checkPxStart(ip, port):
# Make sure Px starts
retry = 20
while True:
try:
socket.create_connection((ip, port), 2)
break
except (socket.timeout, ConnectionRefusedError):
time.sleep(1)
retry -= 1
if retry == 0:
print("Px didn't start")
return False
return True
# Test --listen and --port, --hostonly, --gateway and --allow
def checkCommon(ips, port, checkProc):
if ips == [""]:
ips = ["127.0.0.1"]
if port == "":
port = "3128"
port = int(port)
if not checkPxStart(ips[0], port):
return False
localips = getips()
for lip in localips:
for pport in set([3128, port]):
sys.stdout.write(" Checking: " + lip + ":" + str(pport) + " = ")
ret = checkProc(lip, pport)
sys.stdout.write(str(ret) + ": ")
if ((lip not in ips or port != pport) and ret is False) or (lip in ips and port == pport and ret is True):
print("Passed")
else:
print("Failed")
return False
return True
def checkSocket(ips, port):
def checkProc(lip, pport):
try:
socket.create_connection((lip, pport), 2)
except (socket.timeout, ConnectionRefusedError):
return False
return True
return checkCommon(ips, port, checkProc)
def checkFilter(ips, port):
def checkProc(lip, port):
rcode = subprocess.call("curl --proxy " + lip + ":" + str(port) + " http://google.com",
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
sys.stdout.write(str(rcode) + " ")
if rcode == 0:
return True
elif rcode in [7, 52, 56]:
return False
else:
print("Weird curl return " + str(rcode))
sys.exit()
return checkCommon(ips, port, checkProc)
def remoteTest(port, fail=False):
lip = 'echo $SSH_CLIENT ^| cut -d \\\" \\\" -f 1,1'
cmd = os.getenv("REMOTE_SSH")
if cmd is None:
print("Skipping remote test - REMOTE_SSH not set")
return
cmd = cmd + " curl --proxy `%s`:%s --connect-timeout 2 -s http://google.com" % (lip, port)
sys.stdout.write(" Checking: Remote:" + str(port) + " = ")
ret = subprocess.call(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if (ret == 0 and fail == False) or (ret != 0 and fail == True) :
print(str(ret) + ": Passed")
else:
print(str(ret) + ": Failed")
return False
return True
def hostonlyTest(ips, port):
return checkSocket(ips, port) and remoteTest(port, fail=True)
def gatewayTest(ips, port):
return checkSocket(ips, port) and remoteTest(port)
def allowTest127(ips, port):
return checkFilter(ips, port) and remoteTest(port, fail=True)
def allowTest169(ips, port):
return checkFilter(ips, port) and remoteTest(port, fail=True)
def allowTest192(ips, port):
return checkFilter(ips, port) and remoteTest(port)
def listenTestLocal(ip, port):
return checkSocket([ip], port) and remoteTest(port, fail=True)
def listenTestRemote(ip, port):
return checkSocket([ip], port) and remoteTest(port)
def proxyTest(base, port):
return run(base, port)
def noproxyTest(base, port):
return run(base, port)
def socketTestSetup():
if "--nohostonly" not in sys.argv:
TESTS.append(("--proxy=" + PROXY + " --hostonly", hostonlyTest, getips()))
if "--nogateway" not in sys.argv:
TESTS.append(("--proxy=" + PROXY + " --gateway", gatewayTest, getips()))
if "--noallow" not in sys.argv:
TESTS.append(("--proxy=" + PROXY + " --gateway --allow=127.*.*.*",
allowTest127, [""]))
TESTS.append(("--proxy=" + PROXY + " --gateway --allow=169.*.*.*",
allowTest169, list(filter(lambda x: "169" in x, getips()))))
TESTS.append(("--proxy=" + PROXY + " --gateway --allow=192.*.*.*",
allowTest192, list(filter(lambda x: "192" in x, getips()))))
if "--nolisten" not in sys.argv:
localips = getips()
localips.insert(0, "")
localips.remove("127.0.0.1")
for ip in localips[:3]:
cmd = "--proxy=" + PROXY
if ip != "":
cmd += " --listen=" + ip
testproc = listenTestLocal
if "192" in ip:
testproc = listenTestRemote
TESTS.append((cmd, testproc, ip))
def auto():
# Make temp directory
try:
shutil.rmtree("testrun")
except:
pass
time.sleep(1)
try:
os.makedirs("testrun", exist_ok=True)
except TypeError:
try:
os.makedirs("testrun")
except WindowsError:
pass
os.chdir("testrun")
# Load base px.ini
shutil.copy("../px.ini", ".")
shutil.copy("../px.py", ".")
shutil.copy("../dist/px.exe", ".")
# Setup tests
socketTestSetup()
if "--noproxy" not in sys.argv:
TESTS.append(("--workers=4 --proxy=" + PROXY, proxyTest, BASEURL))
if "--nonoproxy" not in sys.argv:
TESTS.append(("--workers=4 --threads=30 --noproxy=*.*.*.*", noproxyTest, BASEURL))
count = 1
for test in TESTS:
procs = []
# Latest version
procs.append(runTest(test, "c:\\Miniconda\\python", count))
count += 1
# Test different versions of Python
pys = ["27", "34", "35"]
for py in pys:
procs.append(runTest(test, "c:\\Miniconda\\envs\\%s\\python" % py, count))
count += 1
# Run px.exe
procs.append(runTest(test, None, count))
count += 1
if not waitprocs(procs):
break
os.chdir("..")
if __name__ == "__main__":
"""python test.py testproxy.org:80 http://baseurl.com
Point test.py to the NTLM proxy server that Px should connect through
Base URL is some base webpage which will be spidered for URLs to
compare results directly through proxy and through Px"""
if len(sys.argv) > 1:
PROXY = sys.argv[1]
if len(sys.argv) > 2:
BASEURL = sys.argv[2]
if PROXY == "" or BASEURL == "":
sys.exit()
auto()