Skip to content

Commit 79584ce

Browse files
committed
trojan protocol
1 parent ac87924 commit 79584ce

3 files changed

Lines changed: 98 additions & 71 deletions

File tree

‎pproxy/__doc__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
__title__ = "pproxy"
2-
__version__ = "2.3.9"
2+
__version__ = "2.4.0"
33
__license__ = "MIT"
44
__description__ = "Proxy server that can tunnel among remote servers by regex rules."
55
__keywords__ = "proxy socks http shadowsocks shadowsocksr ssr redirect pf tunnel cipher ssl udp"

‎pproxy/proto.py‎

Lines changed: 92 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def name(self):
3333
return self.__class__.__name__.lower()
3434
def reuse(self):
3535
return False
36-
def udp_parse(self, data, **kw):
36+
def udp_accept(self, data, **kw):
3737
raise Exception(f'{self.name} don\'t support UDP server')
3838
def udp_connect(self, rauth, host_name, port, data, **kw):
3939
raise Exception(f'{self.name} don\'t support UDP client')
@@ -64,23 +64,53 @@ async def channel(self, reader, writer, stat_bytes, stat_conn):
6464
class Direct(BaseProtocol):
6565
pass
6666

67+
class Trojan(BaseProtocol):
68+
async def guess(self, reader, auth, authtable, **kw):
69+
header = await reader.read_w(56)
70+
toauth = hashlib.sha224(auth if auth else b'').hexdigest()
71+
if header == toauth.encode():
72+
authtable.set_authed()
73+
return True
74+
reader.rollback(header)
75+
async def accept(self, reader, **kw):
76+
assert await reader.read_n(3) == b'\x0d\x0a\x01'
77+
host_name, port, _ = await socks_address_stream(reader, (await reader.read_n(1))[0])
78+
assert await reader.read_n(2) == b'\x0d\x0a'
79+
return host_name, port
80+
async def connect(self, reader_remote, writer_remote, rauth, host_name, port, **kw):
81+
toauth = hashlib.sha224(rauth if rauth else b'').hexdigest().encode()
82+
writer_remote.write(toauth + b'\x0d\x0a\x01\x03' + packstr(host_name.encode()) + port.to_bytes(2, 'big') + b'\x0d\x0a')
83+
6784
class SSR(BaseProtocol):
68-
def correct_header(self, header, auth, **kw):
69-
return auth and header == auth[:1] or not auth and header and header[0] in (1, 3, 4)
70-
async def parse(self, header, reader, auth, authtable, **kw):
85+
async def guess(self, reader, auth, authtable, **kw):
7186
if auth:
72-
if (await reader.read_n(len(auth)-1)) != auth[1:]:
73-
raise Exception('Unauthorized SSR')
74-
authtable.set_authed()
75-
header = await reader.read_n(1)
76-
host_name, port, data = await socks_address_stream(reader, header[0])
87+
header = await reader.read_w(len(auth))
88+
if header == auth:
89+
authtable.set_authed()
90+
return True
91+
else:
92+
header = await reader.read_w(1)
93+
if header[0] in (1, 3, 4):
94+
return True
95+
reader.rollback(header)
96+
async def accept(self, reader, **kw):
97+
host_name, port, data = await socks_address_stream(reader, (await reader.read_n(1))[0])
7798
return host_name, port
7899
async def connect(self, reader_remote, writer_remote, rauth, host_name, port, **kw):
79100
writer_remote.write(rauth + b'\x03' + packstr(host_name.encode()) + port.to_bytes(2, 'big'))
80101

81102
class SS(BaseProtocol):
82-
def correct_header(self, header, auth, **kw):
83-
return auth and header == auth[:1] or not auth and header and header[0] in (1, 3, 4, 17, 19, 20)
103+
async def guess(self, reader, auth, authtable, **kw):
104+
if auth:
105+
header = await reader.read_w(len(auth))
106+
if header == auth:
107+
authtable.set_authed()
108+
return True
109+
else:
110+
header = await reader.read_w(1)
111+
if header[0] in (1, 3, 4, 17, 19, 20):
112+
return True
113+
reader.rollback(header)
84114
def patch_ota_reader(self, cipher, reader):
85115
chunk_id, data_len, _buffer = 0, None, bytearray()
86116
def decrypt(s):
@@ -115,12 +145,8 @@ def write(data, o=writer.write):
115145
chunk_id += 1
116146
return o(len(data).to_bytes(2, 'big') + checksum[:10] + data)
117147
writer.write = write
118-
async def parse(self, header, reader, auth, authtable, reader_cipher, **kw):
119-
if auth:
120-
if (await reader.read_n(len(auth)-1)) != auth[1:]:
121-
raise Exception('Unauthorized SS')
122-
authtable.set_authed()
123-
header = await reader.read_n(1)
148+
async def accept(self, reader, reader_cipher, **kw):
149+
header = await reader.read_n(1)
124150
ota = (header[0] & 0x10 == 0x10)
125151
host_name, port, data = await socks_address_stream(reader, header[0])
126152
assert ota or not reader_cipher or not reader_cipher.ota, 'SS client must support OTA'
@@ -138,7 +164,7 @@ async def connect(self, reader_remote, writer_remote, rauth, host_name, port, wr
138164
self.patch_ota_writer(writer_cipher_r, writer_remote)
139165
else:
140166
writer_remote.write(b'\x03' + packstr(host_name.encode()) + port.to_bytes(2, 'big'))
141-
def udp_parse(self, data, auth, **kw):
167+
def udp_accept(self, data, auth, **kw):
142168
reader = io.BytesIO(data)
143169
if auth and reader.read(len(auth)) != auth:
144170
return
@@ -162,9 +188,12 @@ def udp_connect(self, rauth, host_name, port, data, **kw):
162188
return rauth + b'\x03' + packstr(host_name.encode()) + port.to_bytes(2, 'big') + data
163189

164190
class Socks4(BaseProtocol):
165-
def correct_header(self, header, **kw):
166-
return header == b'\x04'
167-
async def parse(self, reader, writer, auth, authtable, **kw):
191+
async def guess(self, reader, **kw):
192+
header = await reader.read_w(1)
193+
if header == b'\x04':
194+
return True
195+
reader.rollback(header)
196+
async def accept(self, reader, writer, auth, authtable, **kw):
168197
assert await reader.read_n(1) == b'\x01'
169198
port = int.from_bytes(await reader.read_n(2), 'big')
170199
ip = await reader.read_n(4)
@@ -182,9 +211,12 @@ async def connect(self, reader_remote, writer_remote, rauth, host_name, port, **
182211
await reader_remote.read_n(6)
183212

184213
class Socks5(BaseProtocol):
185-
def correct_header(self, header, **kw):
186-
return header == b'\x05'
187-
async def parse(self, reader, writer, auth, authtable, **kw):
214+
async def guess(self, reader, **kw):
215+
header = await reader.read_w(1)
216+
if header == b'\x05':
217+
return True
218+
reader.rollback(header)
219+
async def accept(self, reader, writer, auth, authtable, **kw):
188220
methods = await reader.read_n((await reader.read_n(1))[0])
189221
if auth and (b'\x00' not in methods or not authtable.authed()):
190222
writer.write(b'\x05\x02')
@@ -205,16 +237,18 @@ async def parse(self, reader, writer, auth, authtable, **kw):
205237
return host_name, port
206238
async def connect(self, reader_remote, writer_remote, rauth, host_name, port, **kw):
207239
if rauth:
208-
writer_remote.write(b'\x05\x01\x02\x01' + b''.join(packstr(i) for i in rauth.split(b':', 1)))
209-
assert await reader_remote.read_n(2) == b'\x01\x00'
240+
writer_remote.write(b'\x05\x01\x02')
241+
assert await reader_remote.read_n(2) == b'\x05\x02'
242+
writer_remote.write(b'\x01' + b''.join(packstr(i) for i in rauth.split(b':', 1)))
243+
assert await reader_remote.read_n(2) == b'\x01\x00', 'Unknown SOCKS auth'
210244
else:
211245
writer_remote.write(b'\x05\x01\x00')
212246
assert await reader_remote.read_n(2) == b'\x05\x00'
213247
writer_remote.write(b'\x05\x01\x00\x03' + packstr(host_name.encode()) + port.to_bytes(2, 'big'))
214248
assert await reader_remote.read_n(3) == b'\x05\x00\x00'
215249
header = (await reader_remote.read_n(1))[0]
216250
await reader_remote.read_n(6 if header == 1 else (18 if header == 4 else (await reader_remote.read_n(1))[0]+2))
217-
def udp_parse(self, data, **kw):
251+
def udp_accept(self, data, **kw):
218252
reader = io.BytesIO(data)
219253
if reader.read(3) != b'\x00\x00\x00':
220254
return
@@ -227,10 +261,12 @@ def udp_connect(self, rauth, host_name, port, data, **kw):
227261
return b'\x00\x00\x00\x03' + packstr(host_name.encode()) + port.to_bytes(2, 'big') + data
228262

229263
class HTTP(BaseProtocol):
230-
def correct_header(self, header, **kw):
231-
return header and header.isalpha()
232-
async def parse(self, header, reader, writer, auth, authtable, httpget=None, **kw):
233-
lines = header + await reader.read_until(b'\r\n\r\n')
264+
async def guess(self, reader, **kw):
265+
header = await reader.read_w(4)
266+
reader.rollback(header)
267+
return header in (b'GET ', b'HEAD', b'POST', b'PUT ', b'DELE', b'CONN', b'OPTI', b'TRAC', b'PATC')
268+
async def accept(self, reader, writer, auth, authtable, httpget=None, **kw):
269+
lines = await reader.read_until(b'\r\n\r\n')
234270
headers = lines[:-4].decode().split('\r\n')
235271
method, path, ver = HTTP_LINE.match(headers.pop(0)).groups()
236272
lines = '\r\n'.join(i for i in headers if not i.startswith('Proxy-'))
@@ -321,24 +357,15 @@ async def connect(self, reader_remote, writer_remote, rauth, host_name, port, my
321357
pass
322358

323359
class Transparent(BaseProtocol):
324-
def correct_header(self, header, auth, sock, **kw):
360+
async def guess(self, reader, sock, **kw):
325361
remote = self.query_remote(sock)
326-
if remote is None or sock.getsockname() == remote:
327-
return False
328-
return auth and header == auth[:1] or not auth
329-
async def parse(self, reader, auth, authtable, sock, **kw):
330-
if auth:
331-
if (await reader.read_n(len(auth)-1)) != auth[1:]:
332-
raise Exception(f'Unauthorized {self.name}')
333-
authtable.set_authed()
362+
return remote is not None and sock.getsockname() != remote
363+
async def accept(self, reader, sock, **kw):
334364
remote = self.query_remote(sock)
335365
return remote[0], remote[1]
336-
def udp_parse(self, data, auth, sock, **kw):
337-
reader = io.BytesIO(data)
338-
if auth and reader.read(len(auth)) != auth:
339-
return
366+
def udp_accept(self, data, auth, sock, **kw):
340367
remote = self.query_remote(sock)
341-
return remote[0], remote[1], reader.read()
368+
return remote[0], remote[1], data
342369

343370
SO_ORIGINAL_DST = 80
344371
SOL_IPV6 = 41
@@ -383,13 +410,15 @@ def query_remote(self, sock):
383410
port = int(port) if port else dst[1]
384411
return host, port
385412
async def connect(self, reader_remote, writer_remote, rauth, host_name, port, **kw):
386-
writer_remote.write(rauth)
413+
pass
387414
def udp_connect(self, rauth, host_name, port, data, **kw):
388-
return rauth + data
415+
return data
389416

390417
class WS(BaseProtocol):
391-
def correct_header(self, header, **kw):
392-
return header and header.isalpha()
418+
async def guess(self, reader, **kw):
419+
header = await reader.read_w(4)
420+
reader.rollback(header)
421+
return reader == b'GET '
393422
def patch_ws_stream(self, reader, writer, masked=False):
394423
data_len, mask_key, _buffer = None, None, bytearray()
395424
def feed_data(s, o=reader.feed_data):
@@ -430,8 +459,8 @@ def write(data, o=writer.write):
430459
else:
431460
return o(b'\x02' + (bytes([data_len]) if data_len < 126 else b'\x7e'+data_len.to_bytes(2, 'big') if data_len < 65536 else b'\x7f'+data_len.to_bytes(4, 'big')) + data)
432461
writer.write = write
433-
async def parse(self, header, reader, writer, auth, authtable, sock, **kw):
434-
lines = header + await reader.read_until(b'\r\n\r\n')
462+
async def accept(self, reader, writer, auth, authtable, sock, **kw):
463+
lines = await reader.read_until(b'\r\n\r\n')
435464
headers = lines[:-4].decode().split('\r\n')
436465
method, path, ver = HTTP_LINE.match(headers.pop(0)).groups()
437466
lines = '\r\n'.join(i for i in headers if not i.startswith('Proxy-'))
@@ -548,31 +577,27 @@ def sendto(data):
548577
writer.get_extra_info('socket').setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
549578
return Handler()
550579

551-
async def parse(protos, reader, **kw):
552-
proto = next(filter(lambda p: p.correct_header(None, **kw), protos), None)
553-
if proto is None:
580+
async def accept(protos, reader, **kw):
581+
for proto in protos:
554582
try:
555-
header = await reader.read_n(1)
583+
ok = await proto.guess(reader, **kw)
556584
except Exception:
557585
raise Exception('Connection closed')
558-
proto = next(filter(lambda p: p.correct_header(header, **kw), protos), None)
559-
else:
560-
header = None
561-
if proto is not None:
562-
ret = await proto.parse(header=header, reader=reader, **kw)
563-
while len(ret) < 4:
564-
ret += (b'',)
565-
return (proto,) + ret
566-
raise Exception(f'Unsupported protocol {header}')
586+
if ok:
587+
ret = await proto.accept(reader, **kw)
588+
while len(ret) < 4:
589+
ret += (b'',)
590+
return (proto,) + ret
591+
raise Exception(f'Unsupported protocol')
567592

568-
def udp_parse(protos, data, **kw):
593+
def udp_accept(protos, data, **kw):
569594
for proto in protos:
570-
ret = proto.udp_parse(data, **kw)
595+
ret = proto.udp_accept(data, **kw)
571596
if ret:
572597
return (proto,) + ret
573598
raise Exception(f'Unsupported protocol {data[:10]}')
574599

575-
MAPPINGS = dict(direct=Direct, http=HTTP, httponly=HTTPOnly, ssh=SSH, socks5=Socks5, socks4=Socks4, socks=Socks5, ss=SS, ssr=SSR, redir=Redir, pf=Pf, tunnel=Tunnel, echo=Echo, pack=Pack, ws=WS, ssl='', secure='')
600+
MAPPINGS = dict(direct=Direct, http=HTTP, httponly=HTTPOnly, ssh=SSH, socks5=Socks5, socks4=Socks4, socks=Socks5, ss=SS, ssr=SSR, redir=Redir, pf=Pf, tunnel=Tunnel, echo=Echo, pack=Pack, ws=WS, trojan=Trojan, ssl='', secure='')
576601
MAPPINGS['in'] = ''
577602

578603
def get_protos(rawprotos):

‎pproxy/server.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,10 @@
88
DUMMY = lambda s: s
99

1010
asyncio.StreamReader.read_ = lambda self: self.read(PACKET_SIZE)
11+
asyncio.StreamReader.read_w = lambda self, n: asyncio.wait_for(self.read(n), timeout=SOCKET_TIMEOUT)
1112
asyncio.StreamReader.read_n = lambda self, n: asyncio.wait_for(self.readexactly(n), timeout=SOCKET_TIMEOUT)
1213
asyncio.StreamReader.read_until = lambda self, s: asyncio.wait_for(self.readuntil(s), timeout=SOCKET_TIMEOUT)
14+
asyncio.StreamReader.rollback = lambda self, s: self._buffer.__setitem__(slice(0, 0), s)
1315

1416
class AuthTable(object):
1517
_auth = {}
@@ -63,7 +65,7 @@ async def stream_handler(reader, writer, unix, lbind, protos, rserver, cipher, s
6365
remote_text = f'{remote_ip}:{remote_port}'
6466
local_addr = None if server_ip in ('127.0.0.1', '::1', None) else (server_ip, 0)
6567
reader_cipher, _ = await prepare_ciphers(cipher, reader, writer, server_side=False)
66-
lproto, host_name, port, lbuf, rbuf = await proto.parse(protos, reader=reader, writer=writer, authtable=AuthTable(remote_ip, authtime), reader_cipher=reader_cipher, sock=writer.get_extra_info('socket'), **kwargs)
68+
lproto, host_name, port, lbuf, rbuf = await proto.accept(protos, reader=reader, writer=writer, authtable=AuthTable(remote_ip, authtime), reader_cipher=reader_cipher, sock=writer.get_extra_info('socket'), **kwargs)
6769
if host_name == 'echo':
6870
asyncio.ensure_future(lproto.channel(reader, writer, DUMMY, DUMMY))
6971
elif host_name == 'empty':
@@ -150,7 +152,7 @@ async def datagram_handler(writer, data, addr, protos, urserver, block, cipher,
150152
remote_ip, remote_port, *_ = addr
151153
remote_text = f'{remote_ip}:{remote_port}'
152154
data = cipher.datagram.decrypt(data) if cipher else data
153-
lproto, host_name, port, data = proto.udp_parse(protos, data, sock=writer.get_extra_info('socket'), **kwargs)
155+
lproto, host_name, port, data = proto.udp_accept(protos, data, sock=writer.get_extra_info('socket'), **kwargs)
154156
if host_name == 'echo':
155157
writer.sendto(data, addr)
156158
elif host_name == 'empty':
@@ -231,7 +233,7 @@ async def server_run(self, handler):
231233
except asyncio.TimeoutError:
232234
data = None
233235
if data and data[0] != 0:
234-
reader._buffer[0:0] = data
236+
reader.rollback(data)
235237
asyncio.ensure_future(handler(reader, writer))
236238
else:
237239
writer.close()

0 commit comments

Comments
 (0)