forked from alexbers/mtprotoproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mtprotoproxy.py
executable file
·2364 lines (1800 loc) · 81.3 KB
/
mtprotoproxy.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 python3
import asyncio
import socket
import urllib.parse
import urllib.request
import collections
import time
import datetime
import hmac
import base64
import hashlib
import random
import binascii
import sys
import re
import runpy
import signal
import os
import stat
import traceback
TG_DATACENTER_PORT = 443
TG_DATACENTERS_V4 = [
"149.154.175.50", "149.154.167.51", "149.154.175.100",
"149.154.167.91", "149.154.171.5"
]
TG_DATACENTERS_V6 = [
"2001:b28:f23d:f001::a", "2001:67c:04e8:f002::a", "2001:b28:f23d:f003::a",
"2001:67c:04e8:f004::a", "2001:b28:f23f:f005::a"
]
# This list will be updated in the runtime
TG_MIDDLE_PROXIES_V4 = {
1: [("149.154.175.50", 8888)], -1: [("149.154.175.50", 8888)],
2: [("149.154.162.38", 80)], -2: [("149.154.162.38", 80)],
3: [("149.154.175.100", 8888)], -3: [("149.154.175.100", 8888)],
4: [("91.108.4.136", 8888)], -4: [("149.154.165.109", 8888)],
5: [("91.108.56.181", 8888)], -5: [("91.108.56.181", 8888)]
}
TG_MIDDLE_PROXIES_V6 = {
1: [("2001:b28:f23d:f001::d", 8888)], -1: [("2001:b28:f23d:f001::d", 8888)],
2: [("2001:67c:04e8:f002::d", 80)], -2: [("2001:67c:04e8:f002::d", 80)],
3: [("2001:b28:f23d:f003::d", 8888)], -3: [("2001:b28:f23d:f003::d", 8888)],
4: [("2001:67c:04e8:f004::d", 8888)], -4: [("2001:67c:04e8:f004::d", 8888)],
5: [("2001:b28:f23f:f005::d", 8888)], -5: [("2001:67c:04e8:f004::d", 8888)]
}
PROXY_SECRET = bytes.fromhex(
"c4f9faca9678e6bb48ad6c7e2ce5c0d24430645d554addeb55419e034da62721" +
"d046eaab6e52ab14a95a443ecfb3463e79a05a66612adf9caeda8be9a80da698" +
"6fb0a6ff387af84d88ef3a6413713e5c3377f6e1a3d47d99f5e0c56eece8f05c" +
"54c490b079e31bef82ff0ee8f2b0a32756d249c5f21269816cb7061b265db212"
)
SKIP_LEN = 8
PREKEY_LEN = 32
KEY_LEN = 32
IV_LEN = 16
HANDSHAKE_LEN = 64
TLS_HANDSHAKE_LEN = 1 + 2 + 2 + 512
PROTO_TAG_POS = 56
DC_IDX_POS = 60
MIN_CERT_LEN = 1024
PROTO_TAG_ABRIDGED = b"\xef\xef\xef\xef"
PROTO_TAG_INTERMEDIATE = b"\xee\xee\xee\xee"
PROTO_TAG_SECURE = b"\xdd\xdd\xdd\xdd"
CBC_PADDING = 16
PADDING_FILLER = b"\x04\x00\x00\x00"
MIN_MSG_LEN = 12
MAX_MSG_LEN = 2 ** 24
STAT_DURATION_BUCKETS = [0.1, 0.5, 1, 2, 5, 15, 60, 300, 600, 1800, 2**31 - 1]
my_ip_info = {"ipv4": None, "ipv6": None}
used_handshakes = collections.OrderedDict()
client_ips = collections.OrderedDict()
last_client_ips = {}
disable_middle_proxy = False
is_time_skewed = False
fake_cert_len = random.randrange(1024, 4096)
mask_host_cached_ip = None
last_clients_with_time_skew = {}
last_clients_with_same_handshake = collections.Counter()
proxy_start_time = 0
proxy_links = []
stats = collections.Counter()
user_stats = collections.defaultdict(collections.Counter)
config = {}
def init_config():
global config
# we use conf_dict to protect the original config from exceptions when reloading
if len(sys.argv) < 2:
conf_dict = runpy.run_module("config")
elif len(sys.argv) == 2:
# launch with own config
conf_dict = runpy.run_path(sys.argv[1])
else:
# undocumented way of launching
conf_dict = {}
conf_dict["PORT"] = int(sys.argv[1])
secrets = sys.argv[2].split(",")
conf_dict["USERS"] = {"user%d" % i: secrets[i].zfill(32) for i in range(len(secrets))}
conf_dict["MODES"] = {"classic": False, "secure": True, "tls": True}
if len(sys.argv) > 3:
conf_dict["AD_TAG"] = sys.argv[3]
if len(sys.argv) > 4:
conf_dict["TLS_DOMAIN"] = sys.argv[4]
conf_dict["MODES"] = {"classic": False, "secure": False, "tls": True}
conf_dict = {k: v for k, v in conf_dict.items() if k.isupper()}
conf_dict.setdefault("PORT", 3256)
conf_dict.setdefault("USERS", {"tg": "00000000000000000000000000000000"})
conf_dict["AD_TAG"] = bytes.fromhex(conf_dict.get("AD_TAG", ""))
for user, secret in conf_dict["USERS"].items():
if not re.fullmatch("[0-9a-fA-F]{32}", secret):
fixed_secret = re.sub(r"[^0-9a-fA-F]", "", secret).zfill(32)[:32]
print_err("Bad secret for user %s, should be 32 hex chars, got %s. " % (user, secret))
print_err("Changing it to %s" % fixed_secret)
conf_dict["USERS"][user] = fixed_secret
# load advanced settings
# use middle proxy, necessary to show ad
conf_dict.setdefault("USE_MIDDLE_PROXY", len(conf_dict["AD_TAG"]) == 16)
# if IPv6 avaliable, use it by default
conf_dict.setdefault("PREFER_IPV6", socket.has_ipv6)
# disables tg->client trafic reencryption, faster but less secure
conf_dict.setdefault("FAST_MODE", True)
# enables some working modes
modes = conf_dict.get("MODES", {})
if "MODES" not in conf_dict:
modes.setdefault("classic", True)
modes.setdefault("secure", True)
modes.setdefault("tls", True)
else:
modes.setdefault("classic", False)
modes.setdefault("secure", False)
modes.setdefault("tls", False)
legacy_warning = False
if "SECURE_ONLY" in conf_dict:
legacy_warning = True
modes["classic"] = not bool(conf_dict["SECURE_ONLY"])
if "TLS_ONLY" in conf_dict:
legacy_warning = True
if conf_dict["TLS_ONLY"]:
modes["classic"] = False
modes["secure"] = False
if not modes["classic"] and not modes["secure"] and not modes["tls"]:
print_err("No known modes enabled, enabling tls-only mode")
modes["tls"] = True
if legacy_warning:
print_err("Legacy options SECURE_ONLY or TLS_ONLY detected")
print_err("Please use MODES in your config instead:")
print_err("MODES = {")
print_err(' "classic": %s,' % modes["classic"])
print_err(' "secure": %s,' % modes["secure"])
print_err(' "tls": %s' % modes["tls"])
print_err("}")
conf_dict["MODES"] = modes
# accept incoming connections only with proxy protocol v1/v2, useful for nginx and haproxy
conf_dict.setdefault("PROXY_PROTOCOL", False)
# set the tls domain for the proxy, has an influence only on starting message
conf_dict.setdefault("TLS_DOMAIN", "www.google.com")
# enable proxying bad clients to some host
conf_dict.setdefault("MASK", True)
# the next host to forward bad clients
conf_dict.setdefault("MASK_HOST", conf_dict["TLS_DOMAIN"])
# set the home domain for the proxy, has an influence only on the log message
conf_dict.setdefault("MY_DOMAIN", False)
# the next host's port to forward bad clients
conf_dict.setdefault("MASK_PORT", 443)
# use upstream SOCKS5 proxy
conf_dict.setdefault("SOCKS5_HOST", None)
conf_dict.setdefault("SOCKS5_PORT", None)
conf_dict.setdefault("SOCKS5_USER", None)
conf_dict.setdefault("SOCKS5_PASS", None)
if conf_dict["SOCKS5_HOST"] and conf_dict["SOCKS5_PORT"]:
# Disable the middle proxy if using socks, they are not compatible
conf_dict["USE_MIDDLE_PROXY"] = False
# user tcp connection limits, the mapping from name to the integer limit
# one client can create many tcp connections, up to 8
conf_dict.setdefault("USER_MAX_TCP_CONNS", {})
# expiration date for users in format of day/month/year
conf_dict.setdefault("USER_EXPIRATIONS", {})
for user in conf_dict["USER_EXPIRATIONS"]:
expiration = datetime.datetime.strptime(conf_dict["USER_EXPIRATIONS"][user], "%d/%m/%Y")
conf_dict["USER_EXPIRATIONS"][user] = expiration
# the data quota for user
conf_dict.setdefault("USER_DATA_QUOTA", {})
# length of used handshake randoms for active fingerprinting protection, zero to disable
conf_dict.setdefault("REPLAY_CHECK_LEN", 65536)
# accept clients with bad clocks. This reduces the protection against replay attacks
conf_dict.setdefault("IGNORE_TIME_SKEW", False)
# length of last client ip addresses for logging
conf_dict.setdefault("CLIENT_IPS_LEN", 131072)
# delay in seconds between stats printing
conf_dict.setdefault("STATS_PRINT_PERIOD", 600)
# delay in seconds between middle proxy info updates
conf_dict.setdefault("PROXY_INFO_UPDATE_PERIOD", 24*60*60)
# delay in seconds between time getting, zero means disabled
conf_dict.setdefault("GET_TIME_PERIOD", 10*60)
# delay in seconds between getting the length of certificate on the mask host
conf_dict.setdefault("GET_CERT_LEN_PERIOD", random.randrange(4*60*60, 6*60*60))
# max socket buffer size to the client direction, the more the faster, but more RAM hungry
# can be the tuple (low, users_margin, high) for the adaptive case. If no much users, use high
conf_dict.setdefault("TO_CLT_BUFSIZE", (16384, 100, 131072))
# max socket buffer size to the telegram servers direction, also can be the tuple
conf_dict.setdefault("TO_TG_BUFSIZE", 65536)
# keepalive period for clients in secs
conf_dict.setdefault("CLIENT_KEEPALIVE", 10*60)
# drop client after this timeout if the handshake fail
conf_dict.setdefault("CLIENT_HANDSHAKE_TIMEOUT", random.randrange(5, 15))
# if client doesn't confirm data for this number of seconds, it is dropped
conf_dict.setdefault("CLIENT_ACK_TIMEOUT", 5*60)
# telegram servers connect timeout in seconds
conf_dict.setdefault("TG_CONNECT_TIMEOUT", 10)
# listen address for IPv4
conf_dict.setdefault("LISTEN_ADDR_IPV4", "0.0.0.0")
# listen address for IPv6
conf_dict.setdefault("LISTEN_ADDR_IPV6", "::")
# listen unix socket
conf_dict.setdefault("LISTEN_UNIX_SOCK", "")
# prometheus exporter listen port, use some random port here
conf_dict.setdefault("METRICS_PORT", None)
# prometheus listen addr ipv4
conf_dict.setdefault("METRICS_LISTEN_ADDR_IPV4", "0.0.0.0")
# prometheus listen addr ipv6
conf_dict.setdefault("METRICS_LISTEN_ADDR_IPV6", None)
# prometheus scrapers whitelist
conf_dict.setdefault("METRICS_WHITELIST", ["127.0.0.1", "::1"])
# export proxy link to prometheus
conf_dict.setdefault("METRICS_EXPORT_LINKS", False)
# default prefix for metrics
conf_dict.setdefault("METRICS_PREFIX", "mtprotoproxy_")
# allow access to config by attributes
config = type("config", (dict,), conf_dict)(conf_dict)
def apply_upstream_proxy_settings():
# apply socks settings in place
if config.SOCKS5_HOST and config.SOCKS5_PORT:
import socks
print_err("Socket-proxy mode activated, it is incompatible with advertising and uvloop")
socks.set_default_proxy(socks.PROXY_TYPE_SOCKS5, config.SOCKS5_HOST, config.SOCKS5_PORT,
username=config.SOCKS5_USER, password=config.SOCKS5_PASS)
if not hasattr(socket, "origsocket"):
socket.origsocket = socket.socket
socket.socket = socks.socksocket
elif hasattr(socket, "origsocket"):
socket.socket = socket.origsocket
del socket.origsocket
def try_use_cryptography_module():
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
class CryptographyEncryptorAdapter:
__slots__ = ('encryptor', 'decryptor')
def __init__(self, cipher):
self.encryptor = cipher.encryptor()
self.decryptor = cipher.decryptor()
def encrypt(self, data):
return self.encryptor.update(data)
def decrypt(self, data):
return self.decryptor.update(data)
def create_aes_ctr(key, iv):
iv_bytes = int.to_bytes(iv, 16, "big")
cipher = Cipher(algorithms.AES(key), modes.CTR(iv_bytes), default_backend())
return CryptographyEncryptorAdapter(cipher)
def create_aes_cbc(key, iv):
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), default_backend())
return CryptographyEncryptorAdapter(cipher)
return create_aes_ctr, create_aes_cbc
def try_use_pycrypto_or_pycryptodome_module():
from Crypto.Cipher import AES
from Crypto.Util import Counter
def create_aes_ctr(key, iv):
ctr = Counter.new(128, initial_value=iv)
return AES.new(key, AES.MODE_CTR, counter=ctr)
def create_aes_cbc(key, iv):
return AES.new(key, AES.MODE_CBC, iv)
return create_aes_ctr, create_aes_cbc
def use_slow_bundled_cryptography_module():
import pyaes
msg = "To make the program a *lot* faster, please install cryptography module: "
msg += "pip install cryptography\n"
print(msg, flush=True, file=sys.stderr)
class BundledEncryptorAdapter:
__slots__ = ('mode', )
def __init__(self, mode):
self.mode = mode
def encrypt(self, data):
encrypter = pyaes.Encrypter(self.mode, pyaes.PADDING_NONE)
return encrypter.feed(data) + encrypter.feed()
def decrypt(self, data):
decrypter = pyaes.Decrypter(self.mode, pyaes.PADDING_NONE)
return decrypter.feed(data) + decrypter.feed()
def create_aes_ctr(key, iv):
ctr = pyaes.Counter(iv)
return pyaes.AESModeOfOperationCTR(key, ctr)
def create_aes_cbc(key, iv):
mode = pyaes.AESModeOfOperationCBC(key, iv)
return BundledEncryptorAdapter(mode)
return create_aes_ctr, create_aes_cbc
try:
create_aes_ctr, create_aes_cbc = try_use_cryptography_module()
except ImportError:
try:
create_aes_ctr, create_aes_cbc = try_use_pycrypto_or_pycryptodome_module()
except ImportError:
create_aes_ctr, create_aes_cbc = use_slow_bundled_cryptography_module()
def print_err(*params):
print(*params, file=sys.stderr, flush=True)
def ensure_users_in_user_stats():
global user_stats
for user in config.USERS:
user_stats[user].update()
def init_proxy_start_time():
global proxy_start_time
proxy_start_time = time.time()
def update_stats(**kw_stats):
global stats
stats.update(**kw_stats)
def update_user_stats(user, **kw_stats):
global user_stats
user_stats[user].update(**kw_stats)
def update_durations(duration):
global stats
for bucket in STAT_DURATION_BUCKETS:
if duration <= bucket:
break
update_stats(**{"connects_with_duration_le_%s" % str(bucket): 1})
def get_curr_connects_count():
global user_stats
all_connects = 0
for user, stat in user_stats.items():
all_connects += stat["curr_connects"]
return all_connects
def get_to_tg_bufsize():
if isinstance(config.TO_TG_BUFSIZE, int):
return config.TO_TG_BUFSIZE
low, margin, high = config.TO_TG_BUFSIZE
return high if get_curr_connects_count() < margin else low
def get_to_clt_bufsize():
if isinstance(config.TO_CLT_BUFSIZE, int):
return config.TO_CLT_BUFSIZE
low, margin, high = config.TO_CLT_BUFSIZE
return high if get_curr_connects_count() < margin else low
class MyRandom(random.Random):
def __init__(self):
super().__init__()
key = bytes([random.randrange(256) for i in range(32)])
iv = random.randrange(256**16)
self.encryptor = create_aes_ctr(key, iv)
self.buffer = bytearray()
def getrandbits(self, k):
numbytes = (k + 7) // 8
return int.from_bytes(self.getrandbytes(numbytes), 'big') >> (numbytes * 8 - k)
def getrandbytes(self, n):
CHUNK_SIZE = 512
while n > len(self.buffer):
data = int.to_bytes(super().getrandbits(CHUNK_SIZE*8), CHUNK_SIZE, "big")
self.buffer += self.encryptor.encrypt(data)
result = self.buffer[:n]
self.buffer = self.buffer[n:]
return bytes(result)
myrandom = MyRandom()
class TgConnectionPool:
MAX_CONNS_IN_POOL = 64
def __init__(self):
self.pools = {}
async def open_tg_connection(self, host, port, init_func=None):
task = asyncio.open_connection(host, port, limit=get_to_clt_bufsize())
reader_tgt, writer_tgt = await asyncio.wait_for(task, timeout=config.TG_CONNECT_TIMEOUT)
set_keepalive(writer_tgt.get_extra_info("socket"))
set_bufsizes(writer_tgt.get_extra_info("socket"), get_to_clt_bufsize(), get_to_tg_bufsize())
if init_func:
return await asyncio.wait_for(init_func(host, port, reader_tgt, writer_tgt),
timeout=config.TG_CONNECT_TIMEOUT)
return reader_tgt, writer_tgt
def register_host_port(self, host, port, init_func):
if (host, port, init_func) not in self.pools:
self.pools[(host, port, init_func)] = []
while len(self.pools[(host, port, init_func)]) < TgConnectionPool.MAX_CONNS_IN_POOL:
connect_task = asyncio.ensure_future(self.open_tg_connection(host, port, init_func))
self.pools[(host, port, init_func)].append(connect_task)
async def get_connection(self, host, port, init_func=None):
self.register_host_port(host, port, init_func)
ret = None
for task in self.pools[(host, port, init_func)][::]:
if task.done():
if task.exception():
self.pools[(host, port, init_func)].remove(task)
continue
reader, writer, *other = task.result()
if writer.transport.is_closing():
self.pools[(host, port, init_func)].remove(task)
continue
if not ret:
self.pools[(host, port, init_func)].remove(task)
ret = (reader, writer, *other)
self.register_host_port(host, port, init_func)
if ret:
return ret
return await self.open_tg_connection(host, port, init_func)
tg_connection_pool = TgConnectionPool()
class LayeredStreamReaderBase:
__slots__ = ("upstream", )
def __init__(self, upstream):
self.upstream = upstream
async def read(self, n):
return await self.upstream.read(n)
async def readexactly(self, n):
return await self.upstream.readexactly(n)
class LayeredStreamWriterBase:
__slots__ = ("upstream", )
def __init__(self, upstream):
self.upstream = upstream
def write(self, data, extra={}):
return self.upstream.write(data)
def write_eof(self):
return self.upstream.write_eof()
async def drain(self):
return await self.upstream.drain()
def close(self):
return self.upstream.close()
def abort(self):
return self.upstream.transport.abort()
def get_extra_info(self, name):
return self.upstream.get_extra_info(name)
@property
def transport(self):
return self.upstream.transport
class FakeTLSStreamReader(LayeredStreamReaderBase):
__slots__ = ('buf', )
def __init__(self, upstream):
self.upstream = upstream
self.buf = bytearray()
async def read(self, n, ignore_buf=False):
if self.buf and not ignore_buf:
data = self.buf
self.buf = bytearray()
return bytes(data)
while True:
tls_rec_type = await self.upstream.readexactly(1)
if not tls_rec_type:
return b""
if tls_rec_type not in [b"\x14", b"\x17"]:
print_err("BUG: bad tls type %s in FakeTLSStreamReader" % tls_rec_type)
return b""
version = await self.upstream.readexactly(2)
if version != b"\x03\x03":
print_err("BUG: unknown version %s in FakeTLSStreamReader" % version)
return b""
data_len = int.from_bytes(await self.upstream.readexactly(2), "big")
data = await self.upstream.readexactly(data_len)
if tls_rec_type == b"\x14":
continue
return data
async def readexactly(self, n):
while len(self.buf) < n:
tls_data = await self.read(1, ignore_buf=True)
if not tls_data:
return b""
self.buf += tls_data
data, self.buf = self.buf[:n], self.buf[n:]
return bytes(data)
class FakeTLSStreamWriter(LayeredStreamWriterBase):
__slots__ = ()
def __init__(self, upstream):
self.upstream = upstream
def write(self, data, extra={}):
MAX_CHUNK_SIZE = 16384 + 24
for start in range(0, len(data), MAX_CHUNK_SIZE):
end = min(start+MAX_CHUNK_SIZE, len(data))
self.upstream.write(b"\x17\x03\x03" + int.to_bytes(end-start, 2, "big"))
self.upstream.write(data[start: end])
return len(data)
class CryptoWrappedStreamReader(LayeredStreamReaderBase):
__slots__ = ('decryptor', 'block_size', 'buf')
def __init__(self, upstream, decryptor, block_size=1):
self.upstream = upstream
self.decryptor = decryptor
self.block_size = block_size
self.buf = bytearray()
async def read(self, n):
if self.buf:
ret = bytes(self.buf)
self.buf.clear()
return ret
else:
data = await self.upstream.read(n)
if not data:
return b""
needed_till_full_block = -len(data) % self.block_size
if needed_till_full_block > 0:
data += self.upstream.readexactly(needed_till_full_block)
return self.decryptor.decrypt(data)
async def readexactly(self, n):
if n > len(self.buf):
to_read = n - len(self.buf)
needed_till_full_block = -to_read % self.block_size
to_read_block_aligned = to_read + needed_till_full_block
data = await self.upstream.readexactly(to_read_block_aligned)
self.buf += self.decryptor.decrypt(data)
ret = bytes(self.buf[:n])
self.buf = self.buf[n:]
return ret
class CryptoWrappedStreamWriter(LayeredStreamWriterBase):
__slots__ = ('encryptor', 'block_size')
def __init__(self, upstream, encryptor, block_size=1):
self.upstream = upstream
self.encryptor = encryptor
self.block_size = block_size
def write(self, data, extra={}):
if len(data) % self.block_size != 0:
print_err("BUG: writing %d bytes not aligned to block size %d" % (
len(data), self.block_size))
return 0
q = self.encryptor.encrypt(data)
return self.upstream.write(q)
class MTProtoFrameStreamReader(LayeredStreamReaderBase):
__slots__ = ('seq_no', )
def __init__(self, upstream, seq_no=0):
self.upstream = upstream
self.seq_no = seq_no
async def read(self, buf_size):
msg_len_bytes = await self.upstream.readexactly(4)
msg_len = int.from_bytes(msg_len_bytes, "little")
# skip paddings
while msg_len == 4:
msg_len_bytes = await self.upstream.readexactly(4)
msg_len = int.from_bytes(msg_len_bytes, "little")
len_is_bad = (msg_len % len(PADDING_FILLER) != 0)
if not MIN_MSG_LEN <= msg_len <= MAX_MSG_LEN or len_is_bad:
print_err("msg_len is bad, closing connection", msg_len)
return b""
msg_seq_bytes = await self.upstream.readexactly(4)
msg_seq = int.from_bytes(msg_seq_bytes, "little", signed=True)
if msg_seq != self.seq_no:
print_err("unexpected seq_no")
return b""
self.seq_no += 1
data = await self.upstream.readexactly(msg_len - 4 - 4 - 4)
checksum_bytes = await self.upstream.readexactly(4)
checksum = int.from_bytes(checksum_bytes, "little")
computed_checksum = binascii.crc32(msg_len_bytes + msg_seq_bytes + data)
if computed_checksum != checksum:
return b""
return data
class MTProtoFrameStreamWriter(LayeredStreamWriterBase):
__slots__ = ('seq_no', )
def __init__(self, upstream, seq_no=0):
self.upstream = upstream
self.seq_no = seq_no
def write(self, msg, extra={}):
len_bytes = int.to_bytes(len(msg) + 4 + 4 + 4, 4, "little")
seq_bytes = int.to_bytes(self.seq_no, 4, "little", signed=True)
self.seq_no += 1
msg_without_checksum = len_bytes + seq_bytes + msg
checksum = int.to_bytes(binascii.crc32(msg_without_checksum), 4, "little")
full_msg = msg_without_checksum + checksum
padding = PADDING_FILLER * ((-len(full_msg) % CBC_PADDING) // len(PADDING_FILLER))
return self.upstream.write(full_msg + padding)
class MTProtoCompactFrameStreamReader(LayeredStreamReaderBase):
__slots__ = ()
async def read(self, buf_size):
msg_len_bytes = await self.upstream.readexactly(1)
msg_len = int.from_bytes(msg_len_bytes, "little")
extra = {"QUICKACK_FLAG": False}
if msg_len >= 0x80:
extra["QUICKACK_FLAG"] = True
msg_len -= 0x80
if msg_len == 0x7f:
msg_len_bytes = await self.upstream.readexactly(3)
msg_len = int.from_bytes(msg_len_bytes, "little")
msg_len *= 4
data = await self.upstream.readexactly(msg_len)
return data, extra
class MTProtoCompactFrameStreamWriter(LayeredStreamWriterBase):
__slots__ = ()
def write(self, data, extra={}):
SMALL_PKT_BORDER = 0x7f
LARGE_PKT_BORGER = 256 ** 3
if len(data) % 4 != 0:
print_err("BUG: MTProtoFrameStreamWriter attempted to send msg with len", len(data))
return 0
if extra.get("SIMPLE_ACK"):
return self.upstream.write(data[::-1])
len_div_four = len(data) // 4
if len_div_four < SMALL_PKT_BORDER:
return self.upstream.write(bytes([len_div_four]) + data)
elif len_div_four < LARGE_PKT_BORGER:
return self.upstream.write(b'\x7f' + int.to_bytes(len_div_four, 3, 'little') + data)
else:
print_err("Attempted to send too large pkt len =", len(data))
return 0
class MTProtoIntermediateFrameStreamReader(LayeredStreamReaderBase):
__slots__ = ()
async def read(self, buf_size):
msg_len_bytes = await self.upstream.readexactly(4)
msg_len = int.from_bytes(msg_len_bytes, "little")
extra = {}
if msg_len > 0x80000000:
extra["QUICKACK_FLAG"] = True
msg_len -= 0x80000000
data = await self.upstream.readexactly(msg_len)
return data, extra
class MTProtoIntermediateFrameStreamWriter(LayeredStreamWriterBase):
__slots__ = ()
def write(self, data, extra={}):
if extra.get("SIMPLE_ACK"):
return self.upstream.write(data)
else:
return self.upstream.write(int.to_bytes(len(data), 4, 'little') + data)
class MTProtoSecureIntermediateFrameStreamReader(LayeredStreamReaderBase):
__slots__ = ()
async def read(self, buf_size):
msg_len_bytes = await self.upstream.readexactly(4)
msg_len = int.from_bytes(msg_len_bytes, "little")
extra = {}
if msg_len > 0x80000000:
extra["QUICKACK_FLAG"] = True
msg_len -= 0x80000000
data = await self.upstream.readexactly(msg_len)
if msg_len % 4 != 0:
cut_border = msg_len - (msg_len % 4)
data = data[:cut_border]
return data, extra
class MTProtoSecureIntermediateFrameStreamWriter(LayeredStreamWriterBase):
__slots__ = ()
def write(self, data, extra={}):
MAX_PADDING_LEN = 4
if extra.get("SIMPLE_ACK"):
# TODO: make this unpredictable
return self.upstream.write(data)
else:
padding_len = myrandom.randrange(MAX_PADDING_LEN)
padding = myrandom.getrandbytes(padding_len)
padded_data_len_bytes = int.to_bytes(len(data) + padding_len, 4, 'little')
return self.upstream.write(padded_data_len_bytes + data + padding)
class ProxyReqStreamReader(LayeredStreamReaderBase):
__slots__ = ()
async def read(self, msg):
RPC_PROXY_ANS = b"\x0d\xda\x03\x44"
RPC_CLOSE_EXT = b"\xa2\x34\xb6\x5e"
RPC_SIMPLE_ACK = b"\x9b\x40\xac\x3b"
data = await self.upstream.read(1)
if len(data) < 4:
return b""
ans_type = data[:4]
if ans_type == RPC_CLOSE_EXT:
return b""
if ans_type == RPC_PROXY_ANS:
ans_flags, conn_id, conn_data = data[4:8], data[8:16], data[16:]
return conn_data
if ans_type == RPC_SIMPLE_ACK:
conn_id, confirm = data[4:12], data[12:16]
return confirm, {"SIMPLE_ACK": True}
print_err("unknown rpc ans type:", ans_type)
return b""
class ProxyReqStreamWriter(LayeredStreamWriterBase):
__slots__ = ('remote_ip_port', 'our_ip_port', 'out_conn_id', 'proto_tag')
def __init__(self, upstream, cl_ip, cl_port, my_ip, my_port, proto_tag):
self.upstream = upstream
if ":" not in cl_ip:
self.remote_ip_port = b"\x00" * 10 + b"\xff\xff"
self.remote_ip_port += socket.inet_pton(socket.AF_INET, cl_ip)
else:
self.remote_ip_port = socket.inet_pton(socket.AF_INET6, cl_ip)
self.remote_ip_port += int.to_bytes(cl_port, 4, "little")
if ":" not in my_ip:
self.our_ip_port = b"\x00" * 10 + b"\xff\xff"
self.our_ip_port += socket.inet_pton(socket.AF_INET, my_ip)
else:
self.our_ip_port = socket.inet_pton(socket.AF_INET6, my_ip)
self.our_ip_port += int.to_bytes(my_port, 4, "little")
self.out_conn_id = myrandom.getrandbytes(8)
self.proto_tag = proto_tag
def write(self, msg, extra={}):
RPC_PROXY_REQ = b"\xee\xf1\xce\x36"
EXTRA_SIZE = b"\x18\x00\x00\x00"
PROXY_TAG = b"\xae\x26\x1e\xdb"
FOUR_BYTES_ALIGNER = b"\x00\x00\x00"
FLAG_NOT_ENCRYPTED = 0x2
FLAG_HAS_AD_TAG = 0x8
FLAG_MAGIC = 0x1000
FLAG_EXTMODE2 = 0x20000
FLAG_PAD = 0x8000000
FLAG_INTERMEDIATE = 0x20000000
FLAG_ABRIDGED = 0x40000000
FLAG_QUICKACK = 0x80000000
if len(msg) % 4 != 0:
print_err("BUG: attempted to send msg with len %d" % len(msg))
return 0
flags = FLAG_HAS_AD_TAG | FLAG_MAGIC | FLAG_EXTMODE2
if self.proto_tag == PROTO_TAG_ABRIDGED:
flags |= FLAG_ABRIDGED
elif self.proto_tag == PROTO_TAG_INTERMEDIATE:
flags |= FLAG_INTERMEDIATE
elif self.proto_tag == PROTO_TAG_SECURE:
flags |= FLAG_INTERMEDIATE | FLAG_PAD
if extra.get("QUICKACK_FLAG"):
flags |= FLAG_QUICKACK
if msg.startswith(b"\x00" * 8):
flags |= FLAG_NOT_ENCRYPTED
full_msg = bytearray()
full_msg += RPC_PROXY_REQ + int.to_bytes(flags, 4, "little") + self.out_conn_id
full_msg += self.remote_ip_port + self.our_ip_port + EXTRA_SIZE + PROXY_TAG
full_msg += bytes([len(config.AD_TAG)]) + config.AD_TAG + FOUR_BYTES_ALIGNER
full_msg += msg
return self.upstream.write(full_msg)
def try_setsockopt(sock, level, option, value):
try:
sock.setsockopt(level, option, value)
except OSError as E:
pass
def set_keepalive(sock, interval=40, attempts=5):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
if hasattr(socket, "TCP_KEEPIDLE"):
try_setsockopt(sock, socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, interval)
if hasattr(socket, "TCP_KEEPINTVL"):
try_setsockopt(sock, socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval)
if hasattr(socket, "TCP_KEEPCNT"):
try_setsockopt(sock, socket.IPPROTO_TCP, socket.TCP_KEEPCNT, attempts)
def set_ack_timeout(sock, timeout):
if hasattr(socket, "TCP_USER_TIMEOUT"):
try_setsockopt(sock, socket.IPPROTO_TCP, socket.TCP_USER_TIMEOUT, timeout*1000)
def set_bufsizes(sock, recv_buf, send_buf):
try_setsockopt(sock, socket.SOL_SOCKET, socket.SO_RCVBUF, recv_buf)
try_setsockopt(sock, socket.SOL_SOCKET, socket.SO_SNDBUF, send_buf)
def set_instant_rst(sock):
INSTANT_RST = b"\x01\x00\x00\x00\x00\x00\x00\x00"
if hasattr(socket, "SO_LINGER"):
try_setsockopt(sock, socket.SOL_SOCKET, socket.SO_LINGER, INSTANT_RST)
def gen_x25519_public_key():
# generates some number which has square root by modulo P
P = 2**255 - 19
n = myrandom.randrange(P)
return int.to_bytes((n*n) % P, length=32, byteorder="little")
async def connect_reader_to_writer(reader, writer):
BUF_SIZE = 8192