-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmtproxy_bridge.py
More file actions
2051 lines (1718 loc) · 80.1 KB
/
Copy pathmtproxy_bridge.py
File metadata and controls
2051 lines (1718 loc) · 80.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
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
# mtproxy-bridge
# Copyright (C) 2026-present UserN0tAdmin <https://github.com/UserN0tAdmin/mtproxy-bridge>
#
# This file is part of mtproxy-bridge.
#
# mtproxy-bridge is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# mtproxy-bridge is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with mtproxy-bridge. If not, see <http://www.gnu.org/licenses/>.
"""
Local MTProto Proxy bridge.
Starts a SOCKS5 server on 127.0.0.1:<port> and tunnels bytes between the
client (Kurigram) and Telegram via an MTProto proxy (FakeTLS or obfuscated2).
Transport framing is determined by the secret type (mirrors TDLib
``ObfuscatedTransport::init`` / ``ProxySecret``):
- 0xEE + 16 bytes + domain → FakeTLS + padded (0xDDDDDDDD)
- 0xDD + 16 bytes → obfuscated2 + padded (0xDDDDDDDD)
- bare 16 bytes → obfuscated2 + abridged (0xEF)
The bridge does NOT translate framing: the client must use the transport
matching the secret (``TCPIntermediatePadded`` for ee/dd, ``TCPAbridged`` for
bare 16-byte secrets). After the handshake, bytes are relayed end-to-end as-is.
"""
from __future__ import annotations
import argparse
import asyncio
import base64
import hashlib
import hmac
import ipaddress
import logging
import os
import secrets
import signal
import socket
import struct
import time
from typing import Callable, NamedTuple
from urllib.parse import urlparse, parse_qs
try:
from cryptography.hazmat.primitives.ciphers import (
Cipher,
algorithms,
modes,
CipherContext,
)
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
except ImportError as e:
raise SystemExit(
"Required package 'cryptography' is missing (pip install cryptography)"
) from e
# ============================================================================
# Логирование
# ============================================================================
log = logging.getLogger("mtproxy_bridge")
def _hex(data: bytes, limit: int = 64) -> str:
"""Короткое hex-представление для логов; длинные буферы усекаются."""
if len(data) <= limit:
return data.hex()
return data[:limit].hex() + f"...({len(data)} bytes)"
# ============================================================================
# TCP-тюнинг upstream-сокета (TCP_NODELAY + keepalive)
# ============================================================================
_TCP_KEEPALIVE_TIME = 30 # секунд до первого keepalive-проба
_TCP_KEEPALIVE_INTERVAL = 10 # секунд между пробами
_TCP_KEEPALIVE_PROBES = 3 # проб до разрыва
def _apply_tcp_tuning(writer: asyncio.StreamWriter, peer_label: object) -> None:
"""Включает TCP_NODELAY + keepalive на сокете writer'а (best-effort).
TCP_NODELAY критичен для мелких MTProto-фреймов (ack/ping/rpc_result) —
иначе Nagle коагулирует их ~40ms. Keepalive защищает от зависших
NAT-сессий. Недоступность опции на конкретной платформе логируется, но
не рвёт соединение.
"""
sock = writer.get_extra_info("socket")
if sock is None:
return
try:
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
except OSError as e:
log.warning(f"[client {peer_label}] TCP_NODELAY not set: {e}")
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
except OSError as e:
log.debug(f"[client {peer_label}] SO_KEEPALIVE not set: {e}")
return
for opt_name, value in (
("TCP_KEEPIDLE", _TCP_KEEPALIVE_TIME),
("TCP_KEEPINTVL", _TCP_KEEPALIVE_INTERVAL),
("TCP_KEEPCNT", _TCP_KEEPALIVE_PROBES),
):
opt = getattr(socket, opt_name, None)
if opt is None:
continue
try:
sock.setsockopt(socket.IPPROTO_TCP, opt, value)
except OSError as e:
log.debug(f"[client {peer_label}] {opt_name}={value} not set: {e}")
# ============================================================================
# Activity timeout для relay
# ============================================================================
# Хоть один байт за этот интервал, иначе оба направления разрываются.
# Защита от зависших клиентов/upstream и утечки FD при idle-коннектах.
ACTIVITY_TIMEOUT_SECS = 1800 # 30 минут
# Таймаут на каждый readexactly внутри SOCKS5 handshake (slowloris-защита).
SOCKS5_HANDSHAKE_TIMEOUT_SECS = 15.0
# Таймаут на TCP-connect к upstream (молчаливый drop без RST иначе вешает
# корутину на OS-level timeout ~127 c).
UPSTREAM_CONNECT_TIMEOUT_SECS = 5.0
# Грейс-период для уже открытых соединений при остановке сервера.
SHUTDOWN_GRACE_SECS = 5.0
# ============================================================================
# Разбор tg://proxy?server=...&port=...&secret=... и секрета
# ============================================================================
# Transport-теги (см. ObfuscatedTransport::init в td/mtproto/TcpTransport.cpp).
TAG_ABRIDGED = b"\xef\xef\xef\xef"
TAG_PADDED_INTERMEDIATE = b"\xdd\xdd\xdd\xdd"
# TDLib ProxySecret::MAX_DOMAIN_LENGTH (td/mtproto/ProxySecret.h:18). Домен
# длиннее обрезается в ProxySecret::get_domain() → substr(0, MAX_DOMAIN_LENGTH).
_MAX_DOMAIN_LENGTH = 182
class ProxyLink(NamedTuple):
"""Parsed MTProto link."""
server: str
port: int
secret_key: bytes # 16 байт
domain: str # SNI-домен (только для FakeTLS / ee-секретов)
is_fake_tls: bool
expected_tag: bytes # транспортный тег, соответствующий типу секрета
def parse_secret(secret_str: str) -> tuple[bytes, str, bool, bytes]:
"""Parse an MTProto secret in hex or base64url form.
Semantics (mirrors TDLib ``ProxySecret::from_binary``,
td/mtproto/ProxySecret.cpp:29-46, + ``ObfuscatedTransport::init``
из td/mtproto/TcpTransport.cpp):
- bare 16 bytes → obfuscated2 + abridged
- 0xEE + 16 + domain (≥18) → FakeTLS + padded intermediate
- 0xDD + 16 (len == 17) → obfuscated2 + padded intermediate
Empty secret (TDLib plain TCP, ProxySecret size 0) is NOT supported.
Raises:
ValueError: empty secret, unrecognized format, or invalid length.
"""
s = secret_str.strip()
if all(c in "0123456789abcdefABCDEF" for c in s) and len(s) % 2 == 0:
raw = bytes.fromhex(s)
else:
b64 = s.replace("-", "+").replace("_", "/")
b64 += "=" * (-len(b64) % 4)
raw = base64.b64decode(b64)
if not raw:
raise ValueError(
"Empty secret — TDLib plain TCP (ProxySecret size 0) is not supported "
"by this bridge; provide a 16-byte / 0xDD / 0xEE secret"
)
if len(raw) == 16:
return raw, "", False, TAG_ABRIDGED
if raw[0] == 0xEE:
# TDLib: ProxySecret::emulate_tls() → secret.size() ≥ 17 (0xEE + 16 + domain).
# ProxySecret::from_binary (td/mtproto/ProxySecret.cpp:39) принимает size ≥ 18
# (домен ≥ 1 байт). Мост следует TDLib-семантике.
if len(raw) < 18:
raise ValueError(
f"FakeTLS (ee) secret must be ≥18 bytes "
f"(0xEE + 16-byte key + ≥1-byte domain), got {len(raw)}"
)
# TDLib: ProxySecret::get_domain() возвращает secret_.substr(17)
# (td/mtproto/ProxySecret.h:18).
if len(raw) > 17 + _MAX_DOMAIN_LENGTH:
raise ValueError(
f"FakeTLS domain too long ({len(raw) - 17} bytes), "
f"maximum allowed is {_MAX_DOMAIN_LENGTH} bytes"
)
# Preserve as ASCII only, refuse anything else so we don't silently corrupt SNI
domain_bytes = raw[17:]
try:
domain = domain_bytes.decode("ascii")
except UnicodeDecodeError as e:
raise ValueError(
f"FakeTLS domain must be ASCII, got non-ASCII bytes: {e}"
) from e
return raw[1:17], domain, True, TAG_PADDED_INTERMEDIATE
if raw[0] == 0xDD:
# TDLib: ProxySecret::use_random_padding() → secret.size() == 17
# (0xDD + 16-byte key).
if len(raw) != 17:
raise ValueError(
f"dd-secret must be exactly 17 bytes (0xDD + 16-byte key), "
f"got {len(raw)}"
)
return raw[1:17], "", False, TAG_PADDED_INTERMEDIATE
raise ValueError(
f"Unrecognized secret format (first byte=0x{raw[0]:02x}, "
f"len={len(raw)}); expected 16 bytes (bare), 0xDD + 16 bytes, "
f"or 0xEE + 16 bytes + ASCII domain (≥4 bytes)"
)
def parse_tg_link(link: str) -> ProxyLink:
"""Parse ``tg://proxy?server=...&port=...&secret=...`` into a :class:`ProxyLink`.
Raises:
ValueError: required parameters server/port/secret are missing.
"""
parsed = urlparse(link)
params = parse_qs(parsed.query)
if not params.get("server") or not params.get("port") or not params.get("secret"):
raise ValueError("Invalid link: server, port or secret is missing")
server = params["server"][0]
port = int(params["port"][0])
secret_str = params["secret"][0]
key, domain, is_fake_tls, expected_tag = parse_secret(secret_str)
return ProxyLink(server, port, key, domain, is_fake_tls, expected_tag)
# ============================================================================
# FakeTLS ClientHello — декларативная схема (порт TlsHello::get_default из TDLib)
# ============================================================================
_HELLO_DIGEST_LENGTH = 32
_CLIENT_HELLO_LIMIT = 2048
_MAX_GREASE = 8
class _Blk:
pass
class _BlkStr(_Blk):
def __init__(self, data: bytes):
self.data = data
class _BlkZero(_Blk):
def __init__(self, length: int):
self.length = length
class _BlkGrease(_Blk):
def __init__(self, seed: int):
self.seed = seed
class _BlkRandom(_Blk):
def __init__(self, length: int):
self.length = length
class _BlkDomain(_Blk):
pass
class _BlkPubKey(_Blk):
pass
class _BlkScope(_Blk):
def __init__(self, entries: list):
self.entries = entries
class _BlkPerm(_Blk):
def __init__(self, elements: list):
self.elements = elements
class _BlkM(_Blk):
pass
class _BlkE(_Blk):
pass
class _BlkPadding(_Blk):
pass
def _prepare_client_hello_rules(
use_block_m: bool = True, use_block_e: bool = True
) -> list:
"""Строит декларативную схему ClientHello (порт ``TlsHello::get_default``
из TDLib, td/mtproto/TlsInit.cpp:139-241).
Args:
use_block_m: включить блок M (Kyber-like key share).
use_block_e: включить блок E (random extra в encrypted_server_name).
"""
def S(d: bytes) -> _BlkStr:
return _BlkStr(d)
def Z(n: int) -> _BlkZero:
return _BlkZero(n)
def G(s: int) -> _BlkGrease:
return _BlkGrease(s)
def R(n: int) -> _BlkRandom:
return _BlkRandom(n)
def D() -> _BlkDomain:
return _BlkDomain()
def K() -> _BlkPubKey:
return _BlkPubKey()
def M() -> _BlkM:
return _BlkM()
def E() -> _BlkE:
return _BlkE()
def P() -> _BlkPadding:
return _BlkPadding()
def Scope(*entries: _Blk) -> _BlkScope:
return _BlkScope(list(entries))
def Perm(*elements: list) -> _BlkPerm:
return _BlkPerm(list(elements))
# key_share extension
if use_block_m:
key_share_entries = [
S(b"\x00\x33\x04\xef\x04\xed"),
G(4),
S(b"\x00\x01\x00\x11\xec\x04\xc0"),
M(),
K(),
S(b"\x00\x1d\x00\x20"),
K(),
]
else:
key_share_entries = [
S(b"\x00\x33\x00\x4f\x00\x4d"),
G(4),
S(b"\x00\x01\x00\x11\xec\x00\x20"),
K(),
S(b"\x00\x1d\x00\x20"),
K(),
]
# encrypted_server_name (fe0d) extension
if use_block_e:
esni_entries = [
S(b"\xfe\x0d"),
Scope(S(b"\x00\x00\x01\x00\x01"), R(1), S(b"\x00\x20"), R(32), Scope(E())),
]
else:
esni_entries = [
S(b"\xfe\x0d"),
Scope(S(b"\x00\x00\x01\x00\x01"), R(1), S(b"\x00\x20"), R(32)),
]
return [
S(b"\x16\x03\x01"),
Scope(
S(b"\x01\x00"),
Scope(
S(b"\x03\x03"),
Z(_HELLO_DIGEST_LENGTH),
S(b"\x20"),
R(32),
S(b"\x00\x20"),
G(0),
S(
bytes.fromhex(
"130113021303c02bc02fc02cc030cca9cca8c013c014009c009d002f0035"
)
),
S(b"\x01\x00"),
Scope(
G(2),
S(b"\x00\x00"),
Perm(
[S(b"\x00\x00"), Scope(Scope(S(b"\x00"), Scope(D())))],
[S(b"\x00\x05\x00\x05\x01\x00\x00\x00\x00")],
[
S(b"\x00\x0a\x00\x0c\x00\x0a"),
G(4),
S(b"\x11\xec\x00\x1d\x00\x17\x00\x18"),
],
[S(b"\x00\x0b\x00\x02\x01\x00")],
[
S(
bytes.fromhex(
"000d0012001004030804040105030805050108060601"
)
)
],
[S(bytes.fromhex("0010000e000c02683208687474702f312e31"))],
[S(b"\x00\x12\x00\x00")],
[S(b"\x00\x17\x00\x00")],
[S(b"\x00\x1b\x00\x03\x02\x00\x02")],
[S(b"\x00\x23\x00\x00")],
[S(b"\x00\x2b\x00\x07\x06"), G(6), S(b"\x03\x04\x03\x03")],
[S(b"\x00\x2d\x00\x02\x01\x01")],
key_share_entries,
[S(b"\x44\xcd\x00\x05\x00\x03\x02\x68\x32")],
esni_entries,
[S(b"\xff\x01\x00\x01\x00")],
),
G(3),
S(b"\x00\x01\x00"),
P(),
),
),
),
]
def _prepare_greases() -> bytes:
"""Генерирует 8 байт GREASE-значений (порт ``Grease::init`` из TDLib,
td/mtproto/TlsInit.cpp:28-38)."""
result = bytearray(secrets.token_bytes(_MAX_GREASE))
for i in range(_MAX_GREASE):
result[i] = (result[i] & 0xF0) + 0x0A
for i in range(0, _MAX_GREASE, 2):
if result[i] == result[i + 1]:
result[i + 1] ^= 0x10
return bytes(result)
class _HelloPart:
"""Рендерер блоков ClientHello (порт ``TlsHelloStore::do_op`` из TDLib,
td/mtproto/TlsInit.cpp:386-508)."""
def __init__(self, domain: bytes, greases: bytes):
self._domain = domain
self._greases = greases
self._result = bytearray()
self._digest_position = -1
self._error = False
def render_blocks(self, blocks: list) -> None:
"""Последовательно рендерит список блоков в ``self._result``."""
for blk in blocks:
if self._error:
return
self._render_block(blk)
def _grow(self, n: int) -> bool:
"""Проверяет, что ``self._result`` можно расширить на ``n`` байт.
При превышении лимита (2048 байт) устанавливает ``self._error``
и возвращает False (порт ``TlsHelloStore::do_op`` grow-логики;
TDLib использует отдельный класс ``TlsHelloCalcLength`` для расчёта
и ``CHECK(size < (1 << 14))`` для per-scope лимита, но мосту это не
нужно — глобальный cap 2048 < 16384 страхует строже).
"""
if n <= 0 or len(self._result) + n > _CLIENT_HELLO_LIMIT:
self._error = True
return False
return True
def _render_block(self, blk: _Blk) -> None:
if isinstance(blk, _BlkStr):
if not self._grow(len(blk.data)):
return
self._result.extend(blk.data)
elif isinstance(blk, _BlkZero):
if not self._grow(blk.length):
return
start = len(self._result)
self._result.extend(b"\x00" * blk.length)
if blk.length == _HELLO_DIGEST_LENGTH and self._digest_position < 0:
self._digest_position = start
elif isinstance(blk, _BlkGrease):
if blk.seed < 0 or blk.seed >= len(self._greases):
self._error = True
return
if not self._grow(2):
return
g = self._greases[blk.seed]
self._result.extend(bytes([g, g]))
elif isinstance(blk, _BlkRandom):
if not self._grow(blk.length):
return
self._result.extend(secrets.token_bytes(blk.length))
elif isinstance(blk, _BlkDomain):
if not self._grow(len(self._domain)):
return
self._result.extend(self._domain)
elif isinstance(blk, _BlkPubKey):
if not self._grow(32):
return
priv = X25519PrivateKey.generate()
self._result.extend(priv.public_key().public_bytes_raw())
elif isinstance(blk, _BlkScope):
if not self._grow(2):
return
length_pos = len(self._result)
self._result.extend(b"\x00\x00")
body_start = len(self._result)
self.render_blocks(blk.entries)
body_len = len(self._result) - body_start
self._result[length_pos : length_pos + 2] = body_len.to_bytes(2, "big")
elif isinstance(blk, _BlkPerm):
parts = []
for element in blk.elements:
part = _HelloPart(self._domain, self._greases)
part.render_blocks(element)
if part._error:
self._error = True
return
parts.append(part.take())
secrets.SystemRandom().shuffle(parts)
for part in parts:
if not self._grow(len(part)):
return
self._result.extend(part)
elif isinstance(blk, _BlkM):
self._render_block_M()
elif isinstance(blk, _BlkE):
lengths = [144, 176, 208, 240]
length = secrets.choice(lengths)
if not self._grow(length):
return
self._result.extend(secrets.token_bytes(length))
elif isinstance(blk, _BlkPadding):
self._render_padding()
else:
self._error = True
def _render_block_M(self) -> None:
"""Рендерит Kyber-like блок M (порт ``Op::MlKem768Key`` из TDLib,
td/mtproto/TlsInit.cpp:441-451)."""
k_elements = 384
k_added = 32
output_len = k_elements * 3 + k_added # 1184
if not self._grow(output_len):
return
random_data = secrets.token_bytes(k_elements * 8 + k_added)
ints = struct.unpack(f"<{k_elements * 2}I", random_data[: k_elements * 8])
chars = bytearray(k_elements * 3 + k_added)
idx = 0
for i in range(k_elements):
a = ints[i * 2] % 3329
b = ints[i * 2 + 1] % 3329
chars[idx] = a & 0xFF
chars[idx + 1] = ((a >> 8) + ((b & 0x0F) << 4)) & 0xFF
chars[idx + 2] = (b >> 4) & 0xFF
idx += 3
chars[idx:] = random_data[k_elements * 8 :]
self._result.extend(chars)
def _render_padding(self) -> None:
"""Дополняет ClientHello до 513 байт extension-записью с zero padding.
Порт ``Op::Padding`` из TDLib (td/mtproto/TlsInit.cpp:495-504).
"""
length = len(self._result)
if length < 513:
needed = 513 - length
# 2 байта (\x00\x15) + 2 байта length + needed нулей = needed + 4
if not self._grow(needed + 4):
return
self._result.extend(b"\x00\x15")
self._result.extend(needed.to_bytes(2, "big"))
self._result.extend(b"\x00" * needed)
def finalize(self, key: bytes) -> None:
"""Записывает HMAC-SHA256 digest и инжектирует timestamp в последние 4 байта."""
if self._error or self._digest_position < 0:
self._error = True
return
self._write_digest(key)
self._inject_timestamp()
def _write_digest(self, key: bytes) -> None:
"""Вычисляет HMAC-SHA256 от текущего буфера и пишет в digest-слот."""
digest = hmac.new(key, bytes(self._result), hashlib.sha256).digest()
self._result[
self._digest_position : self._digest_position + _HELLO_DIGEST_LENGTH
] = digest
def _inject_timestamp(self) -> None:
"""XOR-ит текущие 4 байта digest-слота с unix-временем (anti-replay)."""
ts_pos = self._digest_position + _HELLO_DIGEST_LENGTH - 4
existing = int.from_bytes(self._result[ts_pos : ts_pos + 4], "little")
ts = int(time.time())
new_val = (existing ^ ts) & 0xFFFFFFFF
self._result[ts_pos : ts_pos + 4] = new_val.to_bytes(4, "little")
def take(self) -> bytes:
"""Возвращает готовый ClientHello или пустые байты при ошибке рендера."""
if self._error:
return b""
return bytes(self._result)
def extract_digest(self) -> bytes:
"""Возвращает bytes digest-слота (пусто, если позиция ещё не определена)."""
if self._digest_position < 0:
return b""
return bytes(
self._result[
self._digest_position : self._digest_position + _HELLO_DIGEST_LENGTH
]
)
class ClientHello(NamedTuple):
"""Сгенерированный ClientHello: payload + digest для проверки ответа."""
data: bytes
digest: bytes
def _prepare_client_hello(
domain: bytes, key: bytes, use_block_m: bool = True, use_block_e: bool = True
) -> ClientHello:
"""Генерирует ClientHello + digest для FakeTLS handshake.
Args:
domain: SNI-домен (ASCII).
key: 16-байтный секрет прокси (HMAC key).
use_block_m: флаг блока M (см. :func:`_prepare_client_hello_rules`).
use_block_e: флаг блока E.
Raises:
ValueError: не удалось сгенерировать ClientHello (превышен лимит
размера или нет digest-слота).
"""
rules = _prepare_client_hello_rules(
use_block_m=use_block_m, use_block_e=use_block_e
)
part = _HelloPart(domain, _prepare_greases())
part.render_blocks(rules)
part.finalize(key)
data = part.take()
if not data:
raise ValueError("Failed to generate ClientHello")
return ClientHello(data=data, digest=part.extract_digest())
# ============================================================================
# FakeTLS handshake — инкрементальный парсер ServerHello
# ============================================================================
_TLS_HANDSHAKE_PREFIX = b"\x16\x03\x03"
_CCS_APPDATA_PREFIX = b"\x14\x03\x03\x00\x01\x01\x17\x03\x03"
_SERVER_HELLO_DIGEST_POSITION = 11
_MAX_SERVER_HELLO_LENGTH = 65536
async def _read_exactly_logged(
reader: asyncio.StreamReader, n: int, what: str, timeout: float = 15.0
) -> bytes:
"""``readexactly`` с логированием и таймаутом.
Raises:
ConnectionError: таймаут или обрыв соединения до получения ``n`` байт.
"""
try:
data = await asyncio.wait_for(reader.readexactly(n), timeout=timeout)
except asyncio.TimeoutError:
log.error(
f" [handshake] Timeout reading {what} (need {n} bytes, {timeout}s)"
)
raise ConnectionError(f"Timeout reading {what}")
except asyncio.IncompleteReadError as e:
log.error(
f" [handshake] Connection closed while reading {what}: "
f"got {len(e.partial)}/{n} bytes"
)
raise ConnectionError(
f"Connection closed while reading {what}: {len(e.partial)}/{n}"
)
log.debug(f" [handshake] Read {n} bytes for '{what}': {_hex(data)}")
return data
async def async_faketls_handshake(
reader: asyncio.StreamReader,
writer: asyncio.StreamWriter,
domain: str,
secret_key: bytes,
use_block_m: bool = True,
use_block_e: bool = True,
) -> bytes:
"""Асинхронный клиентский FakeTLS handshake.
Отправляет ClientHello, читает ServerHello + CCS + AppData, проверяет
server-side HMAC-SHA256 (соответствует TDLib ``TlsInit::send_hello`` и
``TlsInit::wait_hello_response``, td/mtproto/TlsInit.cpp:599-648).
Args:
reader: поток чтения от upstream-прокси.
writer: поток записи к upstream-прокси.
domain: SNI-домен из ee-секрета.
secret_key: 16-байтный секрет прокси.
use_block_m: флаг блока M (Kyber-like key share) в ClientHello.
use_block_e: флаг блока E в ClientHello.
Returns:
Байты первого AppData body от сервера (может быть пустым).
Raises:
ConnectionError: любая ошибка handshake (неверный формат ответа,
несовпадение HMAC, таймаут).
"""
log.info(f" [handshake] FakeTLS handshake starting, domain='{domain}'")
# Шаг 1: ClientHello
hello = _prepare_client_hello(
domain.encode("ascii"),
secret_key,
use_block_m=use_block_m,
use_block_e=use_block_e,
)
log.debug(f" [handshake] ClientHello generated: {len(hello.data)} bytes")
log.debug(f" [handshake] ClientHello first 32 bytes: {_hex(hello.data, 32)}")
log.debug(f" [handshake] ClientHello digest: {_hex(hello.digest, 32)}")
writer.write(hello.data)
await writer.drain()
log.debug(" [handshake] ClientHello sent")
# Шаг 2: ServerHello record header (5 байт)
log.debug(" [handshake] Waiting for ServerHello record header (5 bytes)...")
hdr = await _read_exactly_logged(reader, 5, "ServerHello record header")
if hdr[0:3] != _TLS_HANDSHAKE_PREFIX:
log.error(
f" [handshake] Expected 16 03 03, got {hdr[0:3].hex()} — "
f"looks like a fallback site (proxy did not recognize the secret)"
)
raise ConnectionError(
f"Server response is not a TLS handshake record (expected 16 03 03, "
f"got {hdr[0:3].hex()}). Proxy did not recognize the secret?"
)
sh_body_len = struct.unpack(">H", hdr[3:5])[0]
log.debug(f" [handshake] ServerHello record header OK, body length={sh_body_len}")
# parts123Size = 5 + L1 + 9 + 2 = 16 + L1; проверка > kMaxServerHelloLength.
if sh_body_len <= 0 or sh_body_len > _MAX_SERVER_HELLO_LENGTH - 16:
log.error(f" [handshake] Invalid ServerHello body length: {sh_body_len}")
raise ConnectionError(f"Invalid ServerHello body length: {sh_body_len}")
# Шаг 3: ServerHello body
log.debug(f" [handshake] Waiting for ServerHello body ({sh_body_len} bytes)...")
sh_body = await _read_exactly_logged(reader, sh_body_len, "ServerHello body")
if not sh_body or sh_body[0] != 0x02:
log.error(
f" [handshake] ServerHello body does not start with 0x02: "
f"{sh_body[0] if sh_body else 'empty'}"
)
raise ConnectionError("ServerHello body does not start with 0x02 (not a ServerHello)")
log.debug(" [handshake] ServerHello body OK (type=0x02)")
# Шаг 4: CCS + начало AppData (второй prefix из wait_hello_response, 9 байт) + 2 байта длины
log.debug(" [handshake] Waiting for CCS+AppData header (second prefix, 9 bytes)...")
ccs_appdata_prefix = await _read_exactly_logged(
reader, len(_CCS_APPDATA_PREFIX), "CCS+AppData header"
)
if ccs_appdata_prefix != _CCS_APPDATA_PREFIX:
log.error(
f" [handshake] CCS+AppData header (second prefix) not found, "
f"got {_hex(ccs_appdata_prefix)}"
)
raise ConnectionError(
f"CCS+AppData header not found (expected {_CCS_APPDATA_PREFIX.hex()}, "
f"got {ccs_appdata_prefix.hex()})"
)
log.debug(" [handshake] CCS+AppData header OK (second prefix)")
remaining_len_bytes = await _read_exactly_logged(reader, 2, "AppData length")
appdata_body_len = struct.unpack(">H", remaining_len_bytes)[0]
log.debug(f" [handshake] AppData body length={appdata_body_len}")
# full = parts123Size + part4Size = (16 + L1) + (2 + L2) ≤ 65536.
full_size = 16 + sh_body_len + 2 + appdata_body_len
if full_size > _MAX_SERVER_HELLO_LENGTH:
log.error(
f" [handshake] Total ServerHello size {full_size} > "
f"{_MAX_SERVER_HELLO_LENGTH} (L1={sh_body_len}, L2={appdata_body_len})"
)
raise ConnectionError(
f"ServerHello too large: {full_size} > {_MAX_SERVER_HELLO_LENGTH}"
)
# Шаг 5: AppData body
if appdata_body_len > 0:
log.debug(f" [handshake] Waiting for AppData body ({appdata_body_len} bytes)...")
appdata_body = await _read_exactly_logged(
reader, appdata_body_len, "AppData body"
)
log.debug(f" [handshake] AppData body received: {len(appdata_body)} bytes")
else:
appdata_body = b""
log.debug(" [handshake] AppData body empty (len=0)")
# Шаг 6: проверка server digest
log.debug(" [handshake] Verifying server digest (over full response)...")
server_full_response = (
hdr + sh_body + ccs_appdata_prefix + remaining_len_bytes + appdata_body
)
log.debug(f" [handshake] Server full response: {len(server_full_response)} bytes")
if (
len(server_full_response)
< _SERVER_HELLO_DIGEST_POSITION + _HELLO_DIGEST_LENGTH
):
log.error(
f" [handshake] Server response too short for digest: "
f"{len(server_full_response)} bytes"
)
raise ConnectionError("Server response too short to verify digest")
server_digest = server_full_response[
_SERVER_HELLO_DIGEST_POSITION : _SERVER_HELLO_DIGEST_POSITION
+ _HELLO_DIGEST_LENGTH
]
log.debug(f" [handshake] Server digest (pos 11): {_hex(server_digest, 32)}")
server_response_zeroed = (
server_full_response[:_SERVER_HELLO_DIGEST_POSITION]
+ b"\x00" * _HELLO_DIGEST_LENGTH
+ server_full_response[_SERVER_HELLO_DIGEST_POSITION + _HELLO_DIGEST_LENGTH :]
)
fulldata = hello.digest + server_response_zeroed
expected = hmac.new(secret_key, fulldata, hashlib.sha256).digest()
log.debug(f" [handshake] Expected digest: {_hex(expected, 32)}")
if not hmac.compare_digest(expected, server_digest):
log.error(" [handshake] Server HMAC mismatch!")
log.error(f" [handshake] server: {_hex(server_digest, 32)}")
log.error(f" [handshake] expected: {_hex(expected, 32)}")
raise ConnectionError(
"Server HMAC mismatch — proxy did not recognize the secret "
"(connection went to a domain-fronting fallback)"
)
log.info(" [handshake] FakeTLS handshake completed successfully")
return appdata_body
# ============================================================================
# TLS Application Data — запись
# ============================================================================
_CLIENT_PREFIX = b"\x14\x03\x03\x00\x01\x01" # ChangeCipherSpec record
_CLIENT_HEADER = b"\x17\x03\x03" # ApplicationData record header
_MAX_TLS_PACKET_LENGTH = 2878 # td/mtproto/TcpTransport.h:162
class TLSRecordWriter:
"""Обёртка байт в TLS Application Data records.
При ``send_ccs=True`` (по умолчанию) отправляет TDLib ``first_prefix``
перед первой записью, как TDLib (``ObfuscatedTransport::do_write_tls``,
td/mtproto/TcpTransport.cpp:206-210: ``Slice first_prefix("\x14\x03\x03\x00\x01\x01")``).
Opt-out через ``--no-ccs`` для прокси, не требующих CCS.
"""
def __init__(self, send_ccs: bool = True) -> None:
self._prefix_sent = False
self._send_ccs = send_ccs
def wrap(self, prefix: bytes, data: bytes) -> bytes:
"""Упаковывает ``prefix`` + ``data`` в TLS Application Data records.
``prefix`` — необязательные служебные байты (например, остаток
заголовка obfuscated2), которые приклеиваются к началу ``data`` в
первой TLS-записи. ``data`` дробится на куски не более
``_MAX_TLS_PACKET_LENGTH`` байт.
Returns:
Готовые к отправке байты (CCS + один или несколько AppData records).
"""
out = bytearray()
if self._send_ccs and prefix and not self._prefix_sent:
out += _CLIENT_PREFIX
self._prefix_sent = True
log.debug(" [tls-write] CCS prefix sent (6 bytes)")
if not data:
if prefix:
record = prefix
out += _CLIENT_HEADER + struct.pack(">H", len(record)) + record
log.debug(
f" [tls-write] AppData record: prefix={len(prefix)} bytes "
f"(no data)"
)
return bytes(out)
buf = data
cur_prefix = prefix
first_record = True
while buf:
if cur_prefix:
write_size = min(_MAX_TLS_PACKET_LENGTH - len(cur_prefix), len(buf))
record = cur_prefix + buf[:write_size]
buf = buf[write_size:]
cur_prefix = b""
else:
write_size = min(_MAX_TLS_PACKET_LENGTH, len(buf))
record = buf[:write_size]
buf = buf[write_size:]
out += _CLIENT_HEADER + struct.pack(">H", len(record)) + record
if first_record:
log.debug(
f" [tls-write] AppData record #1: prefix={len(prefix)} + "
f"data={write_size} = {len(record)} bytes"
)
first_record = False
else:
log.debug(f" [tls-write] AppData record: data={write_size} bytes")
return bytes(out)
# ============================================================================
# TLS Application Data — чтение
# ============================================================================
_SERVER_HEADER = b"\x17\x03\x03"
class TLSRecordUnwrapper:
"""Инкрементальный парсер TLS Application Data records.
Принимает произвольные порции байт через :meth:`feed`, разбирает TLS
record framing (5-байтный header + payload) и возвращает «чистый»
payload AppData records. Alert / неожиданный CCS / неизвестные типы
рвут соединение.
"""
def __init__(self) -> None:
self._buf = bytearray()
self._total_in = 0
self._total_out = 0