forked from jerryma119/goagent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxylib.py
2338 lines (2126 loc) · 105 KB
/
proxylib.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
#!/usr/bin/env python
# coding:utf-8
__version__ = '1.1'
import sys
import os
import glob
import errno
import time
import struct
import collections
import binascii
import zlib
import itertools
import re
import fnmatch
import io
import random
import base64
import string
import hashlib
import threading
import thread
import socket
import ssl
import logging
import select
import Queue
import SocketServer
import BaseHTTPServer
import httplib
import urllib
import urllib2
import urlparse
import OpenSSL
import dnslib
gevent = sys.modules.get('gevent') or logging.warn('please enable gevent.')
# Re-add sslwrap to Python 2.7.9
import inspect
__ssl__ = __import__('ssl')
try:
_ssl = __ssl__._ssl
except AttributeError:
_ssl = __ssl__._ssl2
def new_sslwrap(sock, server_side=False, keyfile=None, certfile=None, cert_reqs=__ssl__.CERT_NONE, ssl_version=__ssl__.PROTOCOL_SSLv23, ca_certs=None, ciphers=None):
context = __ssl__.SSLContext(ssl_version)
context.verify_mode = cert_reqs or __ssl__.CERT_NONE
if ca_certs:
context.load_verify_locations(ca_certs)
if certfile:
context.load_cert_chain(certfile, keyfile)
if ciphers:
context.set_ciphers(ciphers)
caller_self = inspect.currentframe().f_back.f_locals['self']
return context._wrap_socket(sock, server_side=server_side, ssl_sock=caller_self)
if not hasattr(_ssl, 'sslwrap'):
_ssl.sslwrap = new_sslwrap
try:
from Crypto.Cipher.ARC4 import new as RC4Cipher
except ImportError:
logging.warn('Load Crypto.Cipher.ARC4 Failed, Use Pure Python Instead.')
class RC4Cipher(object):
def __init__(self, key):
x = 0
box = range(256)
for i, y in enumerate(box):
x = (x + y + ord(key[i % len(key)])) & 0xff
box[i], box[x] = box[x], y
self.__box = box
self.__x = 0
self.__y = 0
def encrypt(self, data):
out = []
out_append = out.append
x = self.__x
y = self.__y
box = self.__box
for char in data:
x = (x + 1) & 0xff
y = (y + box[x]) & 0xff
box[x], box[y] = box[y], box[x]
out_append(chr(ord(char) ^ box[(box[x] + box[y]) & 0xff]))
self.__x = x
self.__y = y
return ''.join(out)
class XORCipher(object):
"""XOR Cipher Class"""
def __init__(self, key):
self.__key_gen = itertools.cycle([ord(x) for x in key]).next
self.__key_xor = lambda s: ''.join(chr(ord(x) ^ self.__key_gen()) for x in s)
if len(key) == 1:
try:
from Crypto.Util.strxor import strxor_c
c = ord(key)
self.__key_xor = lambda s: strxor_c(s, c)
except ImportError:
logging.debug('Load Crypto.Util.strxor Failed, Use Pure Python Instead.\n')
def encrypt(self, data):
return self.__key_xor(data)
class CipherFileObject(object):
"""fileobj wrapper for cipher"""
def __init__(self, fileobj, cipher):
self.__fileobj = fileobj
self.__cipher = cipher
def __getattr__(self, attr):
if attr not in ('__fileobj', '__cipher'):
return getattr(self.__fileobj, attr)
def read(self, size=-1):
return self.__cipher.encrypt(self.__fileobj.read(size))
class CipherSocket(object):
"""socket wrapper for cipher"""
def __init__(self, sock, cipher):
self.__sock = fileobj
self.__cipher = cipher
def __getattr__(self, attr):
if attr not in ('__sock', '__cipher'):
return getattr(self.__sock, attr)
def recv(self, size):
data = self.__sock.recv(size)
return data and self.__cipher.encrypt(data)
def send(self, data, flags=0):
return data and self.__sock.send(self.__cipher.encrypt(data), flags)
class LRUCache(object):
"""http://pypi.python.org/pypi/lru/"""
def __init__(self, max_items=100):
self.cache = {}
self.key_order = []
self.max_items = max_items
def __setitem__(self, key, value):
self.cache[key] = value
self._mark(key)
def __getitem__(self, key):
value = self.cache[key]
self._mark(key)
return value
def __contains__(self, key):
return key in self.cache
def __len__(self):
return len(self.cache)
def _mark(self, key):
if key in self.key_order:
self.key_order.remove(key)
self.key_order.insert(0, key)
if len(self.key_order) > self.max_items:
index = self.max_items // 2
delitem = self.cache.__delitem__
key_order = self.key_order
any(delitem(key_order[x]) for x in xrange(index, len(key_order)))
self.key_order = self.key_order[:index]
def clear(self):
self.cache = {}
self.key_order = []
class CertUtility(object):
"""Cert Utility module, based on mitmproxy"""
def __init__(self, vendor, filename, dirname):
self.ca_vendor = vendor
self.ca_keyfile = filename
self.ca_thumbprint = ''
self.ca_certdir = dirname
self.ca_digest = 'sha256'
self.ca_lock = threading.Lock()
def create_ca(self):
key = OpenSSL.crypto.PKey()
key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048)
req = OpenSSL.crypto.X509Req()
subj = req.get_subject()
subj.countryName = 'CN'
subj.stateOrProvinceName = 'Internet'
subj.localityName = 'Cernet'
subj.organizationName = self.ca_vendor
subj.organizationalUnitName = self.ca_vendor
subj.commonName = self.ca_vendor
req.set_pubkey(key)
req.sign(key, self.ca_digest)
ca = OpenSSL.crypto.X509()
ca.set_serial_number(0)
ca.gmtime_adj_notBefore(0)
ca.gmtime_adj_notAfter(24 * 60 * 60 * 3652)
ca.set_issuer(req.get_subject())
ca.set_subject(req.get_subject())
ca.set_pubkey(req.get_pubkey())
ca.sign(key, self.ca_digest)
return key, ca
def dump_ca(self):
key, ca = self.create_ca()
with open(self.ca_keyfile, 'wb') as fp:
fp.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, ca))
fp.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key))
def get_cert_serial_number(self, commonname):
assert self.ca_thumbprint
saltname = '%s|%s' % (self.ca_thumbprint, commonname)
return int(hashlib.md5(saltname.encode('utf-8')).hexdigest(), 16)
def _get_cert(self, commonname, sans=()):
with open(self.ca_keyfile, 'rb') as fp:
content = fp.read()
key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, content)
ca = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, content)
pkey = OpenSSL.crypto.PKey()
pkey.generate_key(OpenSSL.crypto.TYPE_RSA, 2048)
req = OpenSSL.crypto.X509Req()
subj = req.get_subject()
subj.countryName = 'CN'
subj.stateOrProvinceName = 'Internet'
subj.localityName = 'Cernet'
subj.organizationalUnitName = self.ca_vendor
if commonname[0] == '.':
subj.commonName = '*' + commonname
subj.organizationName = '*' + commonname
sans = ['*'+commonname] + [x for x in sans if x != '*'+commonname]
else:
subj.commonName = commonname
subj.organizationName = commonname
sans = [commonname] + [x for x in sans if x != commonname]
#req.add_extensions([OpenSSL.crypto.X509Extension(b'subjectAltName', True, ', '.join('DNS: %s' % x for x in sans)).encode()])
req.set_pubkey(pkey)
req.sign(pkey, self.ca_digest)
cert = OpenSSL.crypto.X509()
cert.set_version(2)
try:
cert.set_serial_number(self.get_cert_serial_number(commonname))
except OpenSSL.SSL.Error:
cert.set_serial_number(int(time.time()*1000))
cert.gmtime_adj_notBefore(-600) #avoid crt time error warning
cert.gmtime_adj_notAfter(60 * 60 * 24 * 3652)
cert.set_issuer(ca.get_subject())
cert.set_subject(req.get_subject())
cert.set_pubkey(req.get_pubkey())
if commonname[0] == '.':
sans = ['*'+commonname] + [s for s in sans if s != '*'+commonname]
else:
sans = [commonname] + [s for s in sans if s != commonname]
#cert.add_extensions([OpenSSL.crypto.X509Extension(b'subjectAltName', True, ', '.join('DNS: %s' % x for x in sans))])
cert.sign(key, self.ca_digest)
certfile = os.path.join(self.ca_certdir, commonname + '.crt')
with open(certfile, 'wb') as fp:
fp.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert))
fp.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, pkey))
return certfile
def get_cert(self, commonname, sans=()):
if commonname.count('.') >= 2 and [len(x) for x in reversed(commonname.split('.'))] > [2, 4]:
commonname = '.'+commonname.partition('.')[-1]
certfile = os.path.join(self.ca_certdir, commonname + '.crt')
if os.path.exists(certfile):
return certfile
elif OpenSSL is None:
return self.ca_keyfile
else:
with self.ca_lock:
if os.path.exists(certfile):
return certfile
return self._get_cert(commonname, sans)
def import_ca(self, certfile):
commonname = os.path.splitext(os.path.basename(certfile))[0]
if sys.platform.startswith('win'):
import ctypes
with open(certfile, 'rb') as fp:
certdata = fp.read()
if certdata.startswith(b'-----'):
begin = b'-----BEGIN CERTIFICATE-----'
end = b'-----END CERTIFICATE-----'
certdata = base64.b64decode(b''.join(certdata[certdata.find(begin)+len(begin):certdata.find(end)].strip().splitlines()))
crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode())
store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000, b'ROOT'.decode())
if not store_handle:
return -1
CERT_FIND_SUBJECT_STR = 0x00080007
CERT_FIND_HASH = 0x10000
X509_ASN_ENCODING = 0x00000001
class CRYPT_HASH_BLOB(ctypes.Structure):
_fields_ = [('cbData', ctypes.c_ulong), ('pbData', ctypes.c_char_p)]
assert self.ca_thumbprint
crypt_hash = CRYPT_HASH_BLOB(20, binascii.a2b_hex(self.ca_thumbprint.replace(':', '')))
crypt_handle = crypt32.CertFindCertificateInStore(store_handle, X509_ASN_ENCODING, 0, CERT_FIND_HASH, ctypes.byref(crypt_hash), None)
if crypt_handle:
crypt32.CertFreeCertificateContext(crypt_handle)
return 0
ret = crypt32.CertAddEncodedCertificateToStore(store_handle, 0x1, certdata, len(certdata), 4, None)
crypt32.CertCloseStore(store_handle, 0)
del crypt32
return 0 if ret else -1
elif sys.platform == 'darwin':
return os.system(('security find-certificate -a -c "%s" | grep "%s" >/dev/null || security add-trusted-cert -d -r trustRoot -k "/Library/Keychains/System.keychain" "%s"' % (commonname, commonname, certfile.decode('utf-8'))).encode('utf-8'))
elif sys.platform.startswith('linux'):
import platform
platform_distname = platform.dist()[0]
if platform_distname == 'Ubuntu':
pemfile = "/etc/ssl/certs/%s.pem" % commonname
new_certfile = "/usr/local/share/ca-certificates/%s.crt" % commonname
if not os.path.exists(pemfile):
return os.system('cp "%s" "%s" && update-ca-certificates' % (certfile, new_certfile))
elif any(os.path.isfile('%s/certutil' % x) for x in os.environ['PATH'].split(os.pathsep)):
return os.system('certutil -L -d sql:$HOME/.pki/nssdb | grep "%s" || certutil -d sql:$HOME/.pki/nssdb -A -t "C,," -n "%s" -i "%s"' % (commonname, commonname, certfile))
else:
logging.warning('please install *libnss3-tools* package to import GoAgent root ca')
return 0
def remove_ca(self, name):
import ctypes
import ctypes.wintypes
class CERT_CONTEXT(ctypes.Structure):
_fields_ = [
('dwCertEncodingType', ctypes.wintypes.DWORD),
('pbCertEncoded', ctypes.POINTER(ctypes.wintypes.BYTE)),
('cbCertEncoded', ctypes.wintypes.DWORD),
('pCertInfo', ctypes.c_void_p),
('hCertStore', ctypes.c_void_p),]
crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode())
store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000, b'ROOT'.decode())
pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, None)
while pCertCtx:
certCtx = CERT_CONTEXT.from_address(pCertCtx)
certdata = ctypes.string_at(certCtx.pbCertEncoded, certCtx.cbCertEncoded)
cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, certdata)
if hasattr(cert, 'get_subject'):
cert = cert.get_subject()
cert_name = next((v for k, v in cert.get_components() if k == 'CN'), '')
if cert_name and name.lower() == cert_name.split()[0].lower():
crypt32.CertDeleteCertificateFromStore(crypt32.CertDuplicateCertificateContext(pCertCtx))
pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, pCertCtx)
return 0
def check_ca(self):
#Check CA exists
capath = os.path.join(os.path.dirname(os.path.abspath(__file__)), self.ca_keyfile)
certdir = os.path.join(os.path.dirname(os.path.abspath(__file__)), self.ca_certdir)
if not os.path.exists(capath):
if os.path.exists(certdir):
any(os.remove(x) for x in glob.glob(certdir+'/*.crt')+glob.glob(certdir+'/.*.crt'))
if os.name == 'nt':
try:
self.remove_ca(self.ca_vendor)
except Exception as e:
logging.warning('self.remove_ca failed: %r', e)
self.dump_ca()
with open(capath, 'rb') as fp:
self.ca_thumbprint = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, fp.read()).digest(self.ca_digest)
#Check Certs
certfiles = glob.glob(certdir+'/*.crt')+glob.glob(certdir+'/.*.crt')
if certfiles:
filename = random.choice(certfiles)
commonname = os.path.splitext(os.path.basename(filename))[0]
with open(filename, 'rb') as fp:
serial_number = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, fp.read()).get_serial_number()
if serial_number != self.get_cert_serial_number(commonname):
any(os.remove(x) for x in certfiles)
#Check CA imported
if self.import_ca(capath) != 0:
logging.warning('install root certificate failed, Please run as administrator/root/sudo')
#Check Certs Dir
if not os.path.exists(certdir):
os.makedirs(certdir)
CertUtil = CertUtility('GoAgent', 'CA.crt', 'certs')
class SSLConnection(object):
"""OpenSSL Connection Wapper"""
def __init__(self, context, sock):
self._context = context
self._sock = sock
self._connection = OpenSSL.SSL.Connection(context, sock)
self._makefile_refs = 0
def __getattr__(self, attr):
if attr not in ('_context', '_sock', '_connection', '_makefile_refs'):
return getattr(self._connection, attr)
def __iowait(self, io_func, *args, **kwargs):
timeout = self._sock.gettimeout() or 0.1
fd = self._sock.fileno()
while True:
try:
return io_func(*args, **kwargs)
except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantX509LookupError):
sys.exc_clear()
_, _, errors = select.select([fd], [], [fd], timeout)
if errors:
break
except OpenSSL.SSL.WantWriteError:
sys.exc_clear()
_, _, errors = select.select([], [fd], [fd], timeout)
if errors:
break
def accept(self):
sock, addr = self._sock.accept()
client = OpenSSL.SSL.Connection(sock._context, sock)
return client, addr
def do_handshake(self):
self.__iowait(self._connection.do_handshake)
def connect(self, *args, **kwargs):
return self.__iowait(self._connection.connect, *args, **kwargs)
def __send(self, data, flags=0):
try:
return self.__iowait(self._connection.send, data, flags)
except OpenSSL.SSL.SysCallError as e:
if e[0] == -1 and not data:
# errors when writing empty strings are expected and can be ignored
return 0
raise
def __send_memoryview(self, data, flags=0):
if hasattr(data, 'tobytes'):
data = data.tobytes()
return self.__send(data, flags)
send = __send if sys.version_info >= (2, 7, 5) else __send_memoryview
def recv(self, bufsiz, flags=0):
pending = self._connection.pending()
if pending:
return self._connection.recv(min(pending, bufsiz))
try:
return self.__iowait(self._connection.recv, bufsiz, flags)
except OpenSSL.SSL.ZeroReturnError:
return ''
except OpenSSL.SSL.SysCallError as e:
if e[0] == -1 and 'Unexpected EOF' in e[1]:
# errors when reading empty strings are expected and can be ignored
return ''
raise
def read(self, bufsiz, flags=0):
return self.recv(bufsiz, flags)
def write(self, buf, flags=0):
return self.sendall(buf, flags)
def close(self):
if self._makefile_refs < 1:
self._connection = None
if self._sock:
socket.socket.close(self._sock)
else:
self._makefile_refs -= 1
def makefile(self, mode='r', bufsize=-1):
self._makefile_refs += 1
return socket._fileobject(self, mode, bufsize, close=True)
@staticmethod
def context_builder(ssl_version='SSLv23', ca_certs=None, cipher_suites=('ALL', '!aNULL', '!eNULL')):
protocol_version = getattr(OpenSSL.SSL, '%s_METHOD' % ssl_version)
ssl_context = OpenSSL.SSL.Context(protocol_version)
if ca_certs:
ssl_context.load_verify_locations(os.path.abspath(ca_certs))
ssl_context.set_verify(OpenSSL.SSL.VERIFY_PEER, lambda c, x, e, d, ok: ok)
else:
ssl_context.set_verify(OpenSSL.SSL.VERIFY_NONE, lambda c, x, e, d, ok: ok)
ssl_context.set_cipher_list(':'.join(cipher_suites))
return ssl_context
def openssl_set_session_cache_mode(context, mode):
assert isinstance(context, OpenSSL.SSL.Context)
try:
import ctypes
SSL_CTRL_SET_SESS_CACHE_MODE = 44
SESS_CACHE_OFF = 0x0
SESS_CACHE_CLIENT = 0x1
SESS_CACHE_SERVER = 0x2
SESS_CACHE_BOTH = 0x3
c_mode = {'off':SESS_CACHE_OFF, 'client':SESS_CACHE_CLIENT, 'server':SESS_CACHE_SERVER, 'both':SESS_CACHE_BOTH}[mode.lower()]
if hasattr(context, 'set_session_cache_mode'):
context.set_session_cache_mode(c_mode)
elif OpenSSL.__version__ == '0.13':
# http://bazaar.launchpad.net/~exarkun/pyopenssl/release-0.13/view/head:/OpenSSL/ssl/context.h#L27
c_context = ctypes.c_void_p.from_address(id(context)+ctypes.sizeof(ctypes.c_int)+ctypes.sizeof(ctypes.c_voidp))
if os.name == 'nt':
# https://github.com/openssl/openssl/blob/92c78463720f71e47c251ffa58493e32cd793e13/ssl/ssl.h#L884
ctypes.c_int.from_address(c_context.value+ctypes.sizeof(ctypes.c_voidp)*7+ctypes.sizeof(ctypes.c_ulong)).value = c_mode
else:
import ctypes.util
# FIXME
# ctypes.cdll.LoadLibrary(ctypes.util.find_library('ssl')).SSL_CTX_ctrl(c_context, SSL_CTRL_SET_SESS_CACHE_MODE, c_mode, None)
except Exception as e:
logging.warning('openssl_set_session_cache_mode failed: %r', e)
class ProxyUtil(object):
"""ProxyUtil module, based on urllib2"""
@staticmethod
def parse_proxy(proxy):
return urllib2._parse_proxy(proxy)
@staticmethod
def get_system_proxy():
proxies = urllib2.getproxies()
return proxies.get('https') or proxies.get('http') or {}
@staticmethod
def get_listen_ip():
listen_ip = '127.0.0.1'
sock = None
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect(('8.8.8.8', 53))
listen_ip = sock.getsockname()[0]
except StandardError:
pass
finally:
if sock:
sock.close()
return listen_ip
def inflate(data):
return zlib.decompress(data, -zlib.MAX_WBITS)
def deflate(data):
return zlib.compress(data)[2:-4]
def message_html(title, banner, detail=''):
MESSAGE_TEMPLATE = '''
<html><head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>$title</title>
<style><!--
body {font-family: arial,sans-serif}
div.nav {margin-top: 1ex}
div.nav A {font-size: 10pt; font-family: arial,sans-serif}
span.nav {font-size: 10pt; font-family: arial,sans-serif; font-weight: bold}
div.nav A,span.big {font-size: 12pt; color: #0000cc}
div.nav A {font-size: 10pt; color: black}
A.l:link {color: #6f6f6f}
A.u:link {color: green}
//--></style>
</head>
<body text=#000000 bgcolor=#ffffff>
<table border=0 cellpadding=2 cellspacing=0 width=100%>
<tr><td bgcolor=#3366cc><font face=arial,sans-serif color=#ffffff><b>Message From LocalProxy</b></td></tr>
<tr><td> </td></tr></table>
<blockquote>
<H1>$banner</H1>
$detail
<p>
</blockquote>
<table width=100% cellpadding=0 cellspacing=0><tr><td bgcolor=#3366cc><img alt="" width=1 height=4></td></tr></table>
</body></html>
'''
return string.Template(MESSAGE_TEMPLATE).substitute(title=title, banner=banner, detail=detail)
def parse_hostport(host, default_port=80):
m = re.match(r'(.+)[#](\d+)$', host)
if m:
return m.group(1).strip('[]'), int(m.group(2))
else:
return host.strip('[]'), default_port
def dnslib_resolve_over_udp(query, dnsservers, timeout, **kwargs):
"""
http://gfwrev.blogspot.com/2009/11/gfwdns.html
http://zh.wikipedia.org/wiki/%E5%9F%9F%E5%90%8D%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%BC%93%E5%AD%98%E6%B1%A1%E6%9F%93
http://support.microsoft.com/kb/241352
https://gist.github.com/klzgrad/f124065c0616022b65e5
"""
if not isinstance(query, (basestring, dnslib.DNSRecord)):
raise TypeError('query argument requires string/DNSRecord')
blacklist = kwargs.get('blacklist', ())
blacklist_prefix = tuple(x for x in blacklist if x.endswith('.'))
turstservers = kwargs.get('turstservers', ())
dns_v4_servers = [x for x in dnsservers if ':' not in x]
dns_v6_servers = [x for x in dnsservers if ':' in x]
sock_v4 = sock_v6 = None
socks = []
if dns_v4_servers:
sock_v4 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socks.append(sock_v4)
if dns_v6_servers:
sock_v6 = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
socks.append(sock_v6)
timeout_at = time.time() + timeout
try:
for _ in xrange(4):
try:
for dnsserver in dns_v4_servers:
if isinstance(query, basestring):
if dnsserver in ('8.8.8.8', '8.8.4.4'):
query = '.'.join(x[:-1] + x[-1].upper() for x in query.split('.')).title()
query = dnslib.DNSRecord(q=dnslib.DNSQuestion(query))
query_data = query.pack()
if query.q.qtype == 1 and dnsserver in ('8.8.8.8', '8.8.4.4'):
query_data = query_data[:-5] + '\xc0\x04' + query_data[-4:]
sock_v4.sendto(query_data, parse_hostport(dnsserver, 53))
for dnsserver in dns_v6_servers:
if isinstance(query, basestring):
query = dnslib.DNSRecord(q=dnslib.DNSQuestion(query, qtype=dnslib.QTYPE.AAAA))
query_data = query.pack()
sock_v6.sendto(query_data, parse_hostport(dnsserver, 53))
while time.time() < timeout_at:
ins, _, _ = select.select(socks, [], [], 0.1)
for sock in ins:
reply_data, reply_address = sock.recvfrom(512)
reply_server = reply_address[0]
record = dnslib.DNSRecord.parse(reply_data)
iplist = [str(x.rdata) for x in record.rr if x.rtype in (1, 28, 255)]
if any(x in blacklist or x.startswith(blacklist_prefix) for x in iplist):
logging.warning('qname=%r dnsservers=%r record bad iplist=%r', query.q.qname, dnsservers, iplist)
elif record.header.rcode and not iplist and reply_server in turstservers:
logging.info('qname=%r trust reply_server=%r record rcode=%s', query.q.qname, reply_server, record.header.rcode)
return record
elif iplist:
logging.debug('qname=%r reply_server=%r record iplist=%s', query.q.qname, reply_server, iplist)
return record
else:
logging.debug('qname=%r reply_server=%r record null iplist=%s', query.q.qname, reply_server, iplist)
continue
except socket.error as e:
logging.warning('handle dns query=%s socket: %r', query, e)
raise socket.gaierror(11004, 'getaddrinfo %r from %r failed' % (query, dnsservers))
finally:
for sock in socks:
sock.close()
def dnslib_resolve_over_tcp(query, dnsservers, timeout, **kwargs):
"""dns query over tcp"""
if not isinstance(query, (basestring, dnslib.DNSRecord)):
raise TypeError('query argument requires string/DNSRecord')
blacklist = kwargs.get('blacklist', ())
blacklist_prefix = tuple(x for x in blacklist if x.endswith('.'))
def do_resolve(query, dnsserver, timeout, queobj):
if isinstance(query, basestring):
qtype = dnslib.QTYPE.AAAA if ':' in dnsserver else dnslib.QTYPE.A
query = dnslib.DNSRecord(q=dnslib.DNSQuestion(query, qtype=qtype))
query_data = query.pack()
sock_family = socket.AF_INET6 if ':' in dnsserver else socket.AF_INET
sock = socket.socket(sock_family)
rfile = None
try:
sock.settimeout(timeout or None)
sock.connect(parse_hostport(dnsserver, 53))
sock.send(struct.pack('>h', len(query_data)) + query_data)
rfile = sock.makefile('r', 1024)
reply_data_length = rfile.read(2)
if len(reply_data_length) < 2:
raise socket.gaierror(11004, 'getaddrinfo %r from %r failed' % (query.q.qname, dnsserver))
reply_data = rfile.read(struct.unpack('>h', reply_data_length)[0])
record = dnslib.DNSRecord.parse(reply_data)
iplist = [str(x.rdata) for x in record.rr if x.rtype in (1, 28, 255)]
if any(x in blacklist or x.startswith(blacklist_prefix) for x in iplist):
logging.debug('qname=%r dnsserver=%r record bad iplist=%r', query.q.qname, dnsserver, iplist)
raise socket.gaierror(11004, 'getaddrinfo %r from %r failed' % (query, dnsserver))
else:
logging.debug('qname=%r dnsserver=%r record iplist=%s', query.q.qname, dnsserver, iplist)
queobj.put(record)
except socket.error as e:
logging.debug('qname=%r dnsserver=%r failed %r', query.q.qname, dnsserver, e)
queobj.put(e)
finally:
if rfile:
rfile.close()
sock.close()
queobj = Queue.Queue()
for dnsserver in dnsservers:
thread.start_new_thread(do_resolve, (query, dnsserver, timeout, queobj))
for i in range(len(dnsservers)):
try:
result = queobj.get(timeout)
except Queue.Empty:
raise socket.gaierror(11004, 'getaddrinfo %r from %r failed' % (query, dnsservers))
if result and not isinstance(result, Exception):
return result
elif i == len(dnsservers) - 1:
logging.warning('dnslib_resolve_over_tcp %r with %s return %r', query, dnsservers, result)
raise socket.gaierror(11004, 'getaddrinfo %r from %r failed' % (query, dnsservers))
def dnslib_record2iplist(record):
"""convert dnslib.DNSRecord to iplist"""
assert isinstance(record, dnslib.DNSRecord)
iplist = [x for x in (str(r.rdata) for r in record.rr) if re.match(r'^\d+\.\d+\.\d+\.\d+$', x) or ':' in x]
return iplist
def get_dnsserver_list():
if os.name == 'nt':
import ctypes
import ctypes.wintypes
DNS_CONFIG_DNS_SERVER_LIST = 6
buf = ctypes.create_string_buffer(2048)
ctypes.windll.dnsapi.DnsQueryConfig(DNS_CONFIG_DNS_SERVER_LIST, 0, None, None, ctypes.byref(buf), ctypes.byref(ctypes.wintypes.DWORD(len(buf))))
ipcount = struct.unpack('I', buf[0:4])[0]
iplist = [socket.inet_ntoa(buf[i:i+4]) for i in xrange(4, ipcount*4+4, 4)]
return iplist
elif os.path.isfile('/etc/resolv.conf'):
with open('/etc/resolv.conf', 'rb') as fp:
return re.findall(r'(?m)^nameserver\s+(\S+)', fp.read())
else:
logging.warning("get_dnsserver_list failed: unsupport platform '%s-%s'", sys.platform, os.name)
return []
def spawn_later(seconds, target, *args, **kwargs):
def wrap(*args, **kwargs):
time.sleep(seconds)
return target(*args, **kwargs)
return thread.start_new_thread(wrap, args, kwargs)
def is_clienthello(data):
if len(data) < 20:
return False
if data.startswith('\x16\x03'):
# TLSv12/TLSv11/TLSv1/SSLv3
length, = struct.unpack('>h', data[3:5])
return len(data) == 5 + length
elif data[0] == '\x80' and data[2:4] == '\x01\x03':
# SSLv23
return len(data) == 2 + ord(data[1])
else:
return False
def extract_sni_name(packet):
if packet.startswith('\x16\x03'):
stream = io.BytesIO(packet)
stream.read(0x2b)
session_id_length = ord(stream.read(1))
stream.read(session_id_length)
cipher_suites_length, = struct.unpack('>h', stream.read(2))
stream.read(cipher_suites_length+2)
extensions_length, = struct.unpack('>h', stream.read(2))
# extensions = {}
while True:
data = stream.read(2)
if not data:
break
etype, = struct.unpack('>h', data)
elen, = struct.unpack('>h', stream.read(2))
edata = stream.read(elen)
if etype == 0:
server_name = edata[5:]
return server_name
def random_hostname():
word = ''.join(random.choice(('bcdfghjklmnpqrstvwxyz', 'aeiou')[x&1]) for x in xrange(random.randint(5, 10)))
gltd = random.choice(['org', 'com', 'net', 'gov', 'cn'])
return 'www.%s.%s' % (word, gltd)
def get_uptime():
if os.name == 'nt':
import ctypes
try:
tick = ctypes.windll.kernel32.GetTickCount64()
except AttributeError:
tick = ctypes.windll.kernel32.GetTickCount()
return tick / 1000.0
elif os.path.isfile('/proc/uptime'):
with open('/proc/uptime', 'rb') as fp:
uptime = fp.readline().strip().split()[0].strip()
return float(uptime)
elif any(os.path.isfile(os.path.join(x, 'uptime')) for x in os.environ['PATH'].split(os.pathsep)):
# http://www.opensource.apple.com/source/lldb/lldb-69/test/pexpect-2.4/examples/uptime.py
pattern = r'up\s+(.*?),\s+([0-9]+) users?,\s+load averages?: ([0-9]+\.[0-9][0-9]),?\s+([0-9]+\.[0-9][0-9]),?\s+([0-9]+\.[0-9][0-9])'
output = os.popen('uptime').read()
duration, _, _, _, _ = re.search(pattern, output).groups()
days, hours, mins = 0, 0, 0
if 'day' in duration:
m = re.search(r'([0-9]+)\s+day', duration)
days = int(m.group(1))
if ':' in duration:
m = re.search(r'([0-9]+):([0-9]+)', duration)
hours = int(m.group(1))
mins = int(m.group(2))
if 'min' in duration:
m = re.search(r'([0-9]+)\s+min', duration)
mins = int(m.group(1))
return days * 86400 + hours * 3600 + mins * 60
else:
#TODO: support other platforms
return None
def get_process_list():
import ctypes
Process = collections.namedtuple('Process', 'pid name exe')
process_list = []
if os.name == 'nt':
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
lpidProcess = (ctypes.c_ulong * 1024)()
cb = ctypes.sizeof(lpidProcess)
cbNeeded = ctypes.c_ulong()
ctypes.windll.psapi.EnumProcesses(ctypes.byref(lpidProcess), cb, ctypes.byref(cbNeeded))
nReturned = cbNeeded.value/ctypes.sizeof(ctypes.c_ulong())
pidProcess = [i for i in lpidProcess][:nReturned]
has_queryimage = hasattr(ctypes.windll.kernel32, 'QueryFullProcessImageNameA')
for pid in pidProcess:
hProcess = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, pid)
if hProcess:
modname = ctypes.create_string_buffer(2048)
count = ctypes.c_ulong(ctypes.sizeof(modname))
if has_queryimage:
ctypes.windll.kernel32.QueryFullProcessImageNameA(hProcess, 0, ctypes.byref(modname), ctypes.byref(count))
else:
ctypes.windll.psapi.GetModuleFileNameExA(hProcess, 0, ctypes.byref(modname), ctypes.byref(count))
exe = modname.value
name = os.path.basename(exe)
process_list.append(Process(pid=pid, name=name, exe=exe))
ctypes.windll.kernel32.CloseHandle(hProcess)
elif sys.platform.startswith('linux'):
for filename in glob.glob('/proc/[0-9]*/cmdline'):
pid = int(filename.split('/')[2])
exe_link = '/proc/%d/exe' % pid
if os.path.exists(exe_link):
exe = os.readlink(exe_link)
name = os.path.basename(exe)
process_list.append(Process(pid=pid, name=name, exe=exe))
else:
try:
import psutil
process_list = psutil.get_process_list()
except StandardError as e:
logging.exception('psutil.get_process_list() failed: %r', e)
return process_list
def forward_socket(local, remote, timeout, bufsize):
"""forward socket"""
try:
tick = 1
timecount = timeout
while 1:
timecount -= tick
if timecount <= 0:
break
(ins, _, errors) = select.select([local, remote], [], [local, remote], tick)
if errors:
break
for sock in ins:
data = sock.recv(bufsize)
if not data:
break
if sock is remote:
local.sendall(data)
timecount = timeout
else:
remote.sendall(data)
timecount = timeout
except socket.timeout:
pass
except (socket.error, ssl.SSLError, OpenSSL.SSL.Error) as e:
if e.args[0] not in (errno.ECONNABORTED, errno.ECONNRESET, errno.ENOTCONN, errno.EPIPE):
raise
if e.args[0] in (errno.EBADF,):
return
finally:
for sock in (remote, local):
try:
sock.close()
except StandardError:
pass
class LocalProxyServer(SocketServer.ThreadingTCPServer):
"""Local Proxy Server"""
request_queue_size = 4096
allow_reuse_address = True
daemon_threads = True
def __init__(self, listener, RequestHandlerClass, bind_and_activate=True):
"""Constructor. May be extended, do not override."""
if hasattr(listener, 'getsockname'):
SocketServer.BaseServer.__init__(self, listener.getsockname(), RequestHandlerClass)
self.socket = listener
else:
SocketServer.ThreadingTCPServer.__init__(self, listener, RequestHandlerClass, bind_and_activate)
def close_request(self, request):
try:
request.close()
except StandardError:
pass
def finish_request(self, request, client_address):
try:
self.RequestHandlerClass(request, client_address, self)
except (socket.error, ssl.SSLError, OpenSSL.SSL.Error) as e:
if e[0] not in (errno.ECONNABORTED, errno.ECONNRESET, errno.EPIPE):
raise
def handle_error(self, *args):
"""make ThreadingTCPServer happy"""
exc_info = sys.exc_info()
error = exc_info and len(exc_info) and exc_info[1]
if isinstance(error, (socket.error, ssl.SSLError, OpenSSL.SSL.Error)) and len(error.args) > 1 and 'bad write retry' in error.args[1]:
exc_info = error = None
else:
del exc_info, error
SocketServer.ThreadingTCPServer.handle_error(self, *args)
class BaseFetchPlugin(object):
"""abstract fetch plugin"""
def __init__(self, *args, **kwargs):
pass
def handle(self, handler, **kwargs):
raise NotImplementedError
class MockFetchPlugin(BaseFetchPlugin):
"""mock fetch plugin"""
def handle(self, handler, status=400, headers={}, body=''):
"""mock response"""
logging.info('%s "MOCK %s %s %s" %d %d', handler.address_string(), handler.command, handler.path, handler.protocol_version, status, len(body))
headers = dict((k.title(), v) for k, v in headers.items())
if isinstance(body, unicode):
body = body.encode('utf8')
if 'Transfer-Encoding' in headers:
del headers['Transfer-Encoding']
if 'Content-Length' not in headers:
headers['Content-Length'] = len(body)
if 'Connection' not in headers:
headers['Connection'] = 'close'
handler.send_response(status)
for key, value in headers.items():
handler.send_header(key, value)
handler.end_headers()
handler.wfile.write(body)
class StripPlugin(BaseFetchPlugin):
"""strip fetch plugin"""
def __init__(self, ssl_version='SSLv23', ciphers='ALL:!aNULL:!eNULL', cache_size=128, session_cache=True):
self.ssl_method = getattr(ssl, 'PROTOCOL_%s' % ssl_version)
self.ciphers = ciphers
def do_ssl_handshake(self, handler):
"do_ssl_handshake with ssl"
certfile = CertUtil.get_cert(handler.host)
ssl_sock = ssl.wrap_socket(handler.connection, keyfile=certfile, certfile=certfile, server_side=True, ssl_version=self.ssl_method, ciphers=self.ciphers)
handler.connection = ssl_sock
handler.rfile = handler.connection.makefile('rb', handler.bufsize)
handler.wfile = handler.connection.makefile('wb', 0)
handler.scheme = 'https'
def handle(self, handler, do_ssl_handshake=True):
"""strip connect"""
logging.info('%s "STRIP %s %s:%d %s" - -', handler.address_string(), handler.command, handler.host, handler.port, handler.protocol_version)
handler.send_response(200)
handler.end_headers()