Skip to content

Commit 383c516

Browse files
authored
pproxy 1.4.1
1 parent bf1a7bf commit 383c516

5 files changed

Lines changed: 221 additions & 23 deletions

File tree

‎pproxy/__init__.py‎

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@
22
from pproxy import proto
33

44
__title__ = 'pproxy'
5-
__version__ = "1.3.1"
5+
__version__ = "1.4.1"
66
__description__ = "Proxy server that can tunnel among remote servers by regex rules."
77
__author__ = "Qian Wenjie"
88
__license__ = "MIT License"
99

1010
SOCKET_TIMEOUT = 300
1111
PACKET_SIZE = 65536
12-
DUMMY = lambda s: None
12+
DUMMY = lambda s: s
1313

1414
asyncio.StreamReader.read_ = lambda self: self.read(PACKET_SIZE)
1515
asyncio.StreamReader.read_n = lambda self, n: asyncio.wait_for(self.readexactly(n), timeout=SOCKET_TIMEOUT)
@@ -28,7 +28,14 @@ def set_authed(self):
2828
async def proxy_handler(reader, writer, protos, rserver, block, cipher, verbose=DUMMY, modstat=lambda r,h:lambda i:DUMMY, **kwargs):
2929
try:
3030
remote_ip = (writer.get_extra_info('peername') or ['local'])[0]
31-
reader_cipher = cipher(reader, writer)[0] if cipher else None
31+
if cipher:
32+
reader.plugin_decrypt = reader.plugin_decrypt2 = writer.plugin_encrypt = writer.plugin_encrypt2 = DUMMY
33+
for plugin in cipher.plugins:
34+
await plugin.init_client_data(reader, writer, cipher)
35+
plugin.apply_cipher(reader, writer)
36+
reader_cipher = cipher(reader, writer)[0]
37+
else:
38+
reader_cipher = None
3239
lproto, host_name, port, initbuf = await proto.parse(protos, reader=reader, writer=writer, authtable=AuthTable(remote_ip), reader_cipher=reader_cipher, sock=writer.get_extra_info('socket'), **kwargs)
3340
if host_name is None:
3441
writer.close()
@@ -49,7 +56,14 @@ async def proxy_handler(reader, writer, protos, rserver, block, cipher, verbose=
4956
raise Exception(f'Connection timeout {rserver}')
5057
try:
5158
if viaproxy:
52-
writer_cipher_r = roption.cipher(reader_remote, writer_remote)[1] if roption.cipher else None
59+
if roption.cipher:
60+
reader_remote.plugin_decrypt = reader_remote.plugin_decrypt2 = writer_remote.plugin_encrypt = writer_remote.plugin_encrypt2 = DUMMY
61+
for plugin in roption.cipher.plugins:
62+
await plugin.init_server_data(reader_remote, writer_remote, roption.cipher, roption.bind)
63+
plugin.apply_cipher(reader_remote, writer_remote)
64+
writer_cipher_r = roption.cipher(reader_remote, writer_remote)[1]
65+
else:
66+
writer_cipher_r = None
5367
await roption.rproto.connect(reader_remote=reader_remote, writer_remote=writer_remote, rauth=roption.auth, host_name=host_name, port=port, initbuf=initbuf, writer_cipher_r=writer_cipher_r, sock=writer_remote.get_extra_info('socket'))
5468
else:
5569
writer_remote.write(initbuf)
@@ -96,8 +110,6 @@ def uri_compile(uri):
96110
raise argparse.ArgumentTypeError(err_str)
97111
if 'ssl' in rawprotos or 'secure' in rawprotos:
98112
import ssl
99-
if not hasattr(ssl, 'Purpose'):
100-
raise argparse.ArgumentTypeError('ssl support is available for Python 3.4 and above')
101113
sslserver = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
102114
sslclient = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
103115
if 'ssl' in rawprotos:
@@ -112,6 +124,15 @@ def uri_compile(uri):
112124
err_str, cipher = get_cipher(cipher)
113125
if err_str:
114126
raise argparse.ArgumentTypeError(err_str)
127+
if url.path:
128+
from pproxy.plugin import get_plugin
129+
plugins = url.path.lstrip('/').split(',')
130+
for name in plugins:
131+
if not name: continue
132+
err_str, plugin = get_plugin(name)
133+
if err_str:
134+
raise argparse.ArgumentTypeError(err_str)
135+
cipher.plugins.append(plugin)
115136
match = pattern_compile(url.query) if url.query else None
116137
if loc:
117138
host, _, port = loc.partition(':')
@@ -164,7 +185,7 @@ def main():
164185
verbose.setup(loop, args)
165186
servers = []
166187
for option in args.listen:
167-
print('Serving on', option.bind, 'by', ",".join(i.name for i in option.protos) + ('(SSL)' if option.sslclient else ''), '({})'.format(option.cipher.name) if option.cipher else '')
188+
print('Serving on', option.bind, 'by', ",".join(i.name for i in option.protos) + ('(SSL)' if option.sslclient else ''), '({}{})'.format(option.cipher.name, ' '+','.join(i.name() for i in option.cipher.plugins) if option.cipher and option.cipher.plugins else '') if option.cipher else '')
168189
handler = functools.partial(functools.partial(proxy_handler, **vars(args)), **vars(option))
169190
try:
170191
server = loop.run_until_complete(option.server(handler))

‎pproxy/cipher.py‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ def get_cipher(cipher_key):
119119
if not key:
120120
return 'empty key', None
121121
if cipher_name not in MAP and cipher_name not in MAP_PY:
122-
return 'existing ciphers: {}'.format(sorted(set(MAP)|set(MAP_PY))), None
122+
return f'existing ciphers: {sorted(set(MAP)|set(MAP_PY))}', None
123123
key, ota = key.encode(), bool(ota) if ota else False
124124
cipher = MAP.get(cipher_name)
125125
if cipher:
@@ -135,29 +135,33 @@ def apply_cipher(reader, writer):
135135
reader_cipher, writer_cipher = cipher(key, ota=ota), cipher(key, ota=ota)
136136
reader_cipher._buffer = b''
137137
def feed_data(s, o=reader.feed_data):
138+
s = reader.plugin_decrypt2(s)
138139
if not reader_cipher.iv:
139140
s = reader_cipher._buffer + s
140141
if len(s) >= reader_cipher.IV_LENGTH:
141142
reader_cipher.setup_iv(s[:reader_cipher.IV_LENGTH])
142-
o(reader_cipher.decrypt(s[reader_cipher.IV_LENGTH:]))
143+
o(reader.plugin_decrypt(reader_cipher.decrypt(s[reader_cipher.IV_LENGTH:])))
143144
else:
144145
reader_cipher._buffer = s
145146
else:
146-
o(reader_cipher.decrypt(s))
147+
o(reader.plugin_decrypt(reader_cipher.decrypt(s)))
147148
def write(s, o=writer.write):
148149
if not writer_cipher.iv:
149150
writer_cipher.setup_iv()
150-
o(writer_cipher.iv)
151+
o(writer.plugin_encrypt2(writer_cipher.iv))
151152
if not s:
152153
return
153-
return o(writer_cipher.encrypt(s))
154+
return o(writer.plugin_encrypt2(writer_cipher.encrypt(writer.plugin_encrypt(s))))
154155
reader.feed_data = feed_data
155156
writer.write = write
156157
if reader._buffer:
157158
reader._buffer, buf = bytearray(), reader._buffer
158159
feed_data(buf)
159160
return reader_cipher, writer_cipher
161+
apply_cipher.cipher = cipher
162+
apply_cipher.key = key
160163
apply_cipher.name = cipher_name + ('-py' if cipher.PYTHON else '')
161164
apply_cipher.ota = ota
165+
apply_cipher.plugins = []
162166
return None, apply_cipher
163167

‎pproxy/cipherpy.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -205,11 +205,11 @@ class Blowfish(RAW):
205205
P = None
206206
@staticmethod
207207
def hex_pi():
208-
N, n, d = 0, 0, 1
209-
for N in range(1<<20):
210-
xn, xd = 120*N**2 + 151*N + 47, 512*N**4 + 1024*N**3 + 712*N**2 + 194*N + 15
211-
n, d = ((16 * n * xd) + (xn * d)) % (d * xd), d * xd
212-
yield '%x' % (16 * n // d)
208+
n, d = -3, 1
209+
for xn, xd in ((120*N**2+151*N+47, 512*N**4+1024*N**3+712*N**2+194*N+15) for N in range(1<<32)):
210+
n, d = n * xd + d * xn, d * xd
211+
o, n = divmod(16 * n, d)
212+
yield '%x' % o
213213
def __init__(self, key):
214214
if not self.P:
215215
pi = self.hex_pi()

‎pproxy/plugin.py‎

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
import datetime, zlib, os, binascii, hmac, hashlib, time, random, collections
2+
3+
packstr = lambda s, n=2: len(s).to_bytes(n, 'big') + s
4+
toint = lambda s, o='big': int.from_bytes(s, o)
5+
6+
class BasePlugin(object):
7+
async def init_client_data(self, reader, writer, cipher):
8+
pass
9+
async def init_server_data(self, reader, writer, cipher, raddr):
10+
pass
11+
def apply_cipher(self, reader, writer):
12+
pass
13+
@classmethod
14+
def name(cls):
15+
return cls.__name__.replace('_Plugin', '').replace('__', '.').lower()
16+
17+
class Plain_Plugin(BasePlugin):
18+
pass
19+
20+
class Origin_Plugin(BasePlugin):
21+
pass
22+
23+
class Http_Simple_Plugin(BasePlugin):
24+
async def init_client_data(self, reader, writer, cipher):
25+
buf = await reader.read_until(b'\r\n\r\n')
26+
data = buf.split(b' ')[:2]
27+
data = bytes.fromhex(data[1][1:].replace(b'%',b'').decode())
28+
reader._buffer[0:0] = data
29+
writer.write(b'HTTP/1.1 200 OK\r\nConnection: keep-alive\r\nContent-Encoding: gzip\r\nContent-Type: text/html\r\nDate: ' + datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S GMT').encode() + b'\r\nServer: nginx\r\nVary: Accept-Encoding\r\n\r\n')
30+
async def init_server_data(self, reader, writer, cipher, raddr):
31+
writer.write(f'GET / HTTP/1.1\r\nHost: {raddr}\r\nUser-Agent: curl\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\n\r\n'.encode())
32+
await reader.read_until(b'\r\n\r\n')
33+
34+
TIMESTAMP_TOLERANCE = 5 * 60
35+
36+
class Tls1__2_Ticket_Auth_Plugin(BasePlugin):
37+
CACHE = collections.deque(maxlen = 100)
38+
async def init_client_data(self, reader, writer, cipher):
39+
key = cipher.cipher(cipher.key).key
40+
assert await reader.read_n(3) == b'\x16\x03\x01'
41+
header = await reader.read_n(toint(await reader.read_n(2)))
42+
assert header[:2] == b'\x01\x00'
43+
assert header[4:6] == b'\x03\x03'
44+
cacheid = header[6:28]
45+
sessionid = header[39:39+header[38]]
46+
assert cacheid not in self.CACHE
47+
self.CACHE.append(cacheid)
48+
utc_time = int(time.time())
49+
assert hmac.new(key+sessionid, cacheid, hashlib.sha1).digest()[:10] == header[28:38]
50+
assert abs(toint(header[6:10]) - utc_time) < TIMESTAMP_TOLERANCE
51+
addhmac = lambda s: s + hmac.new(key+sessionid, s, hashlib.sha1).digest()[:10]
52+
writer.write(addhmac((b"\x16\x03\x03" + packstr(b"\x02\x00" + packstr(b'\x03\x03' + addhmac(utc_time.to_bytes(4, 'big') + os.urandom(18)) + b'\x20' + sessionid + b'\xc0\x2f\x00\x00\x05\xff\x01\x00\x01\x00')) + (b"\x16\x03\x03" + packstr(b"\x04\x00" + packstr(os.urandom(random.randrange(164)*2+64))) if random.randint(0, 8) < 1 else b'') + b"\x14\x03\x03\x00\x01\x01\x16\x03\x03" + packstr(os.urandom(random.choice((32, 40)))))[:-10]))
53+
54+
async def init_server_data(self, reader, writer, cipher, raddr):
55+
key = cipher.cipher(cipher.key).key
56+
sessionid = os.urandom(32)
57+
addhmac = lambda s: s + hmac.new(key+sessionid, s, hashlib.sha1).digest()[:10]
58+
writer.write(b"\x16\x03\x01" + packstr(b"\x01\x00" + packstr(b'\x03\x03' + addhmac(int(time.time()).to_bytes(4, 'big') + os.urandom(18)) + b"\x20" + sessionid + b"\x00\x1c\xc0\x2b\xc0\x2f\xcc\xa9\xcc\xa8\xcc\x14\xcc\x13\xc0\x0a\xc0\x14\xc0\x09\xc0\x13\x00\x9c\x00\x35\x00\x2f\x00\x0a\x01\x00" + packstr(b"\xff\x01\x00\x01\x00\x00\x00" + packstr(packstr(b"\x00" + packstr(raddr.encode()))) + b"\x00\x17\x00\x00\x00\x23" + packstr(os.urandom((random.randrange(17)+8)*16)) + b"\x00\x0d\x00\x16\x00\x14\x06\x01\x06\x03\x05\x01\x05\x03\x04\x01\x04\x03\x03\x01\x03\x03\x02\x01\x02\x03\x00\x05\x00\x05\x01\x00\x00\x00\x00\x00\x12\x00\x00\x75\x50\x00\x00\x00\x0b\x00\x02\x01\x00\x00\x0a\x00\x06\x00\x04\x00\x17\x00\x18"))))
59+
writer.write(addhmac(b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00\x20' + os.urandom(22)))
60+
61+
def apply_cipher(self, reader, writer):
62+
self.buf = bytearray()
63+
def decrypt(s):
64+
self.buf.extend(s)
65+
ret = b''
66+
while len(self.buf) >= 5:
67+
l = int.from_bytes(self.buf[3:5], 'big')
68+
if len(self.buf) < l:
69+
break
70+
if self.buf[:3] in (b'\x16\x03\x03', b'\x14\x03\x03'):
71+
del self.buf[:5+l]
72+
continue
73+
assert self.buf[:3] == b'\x17\x03\x03'
74+
data = self.buf[5:5+l]
75+
ret += data
76+
del self.buf[:5+l]
77+
return ret
78+
def pack(s):
79+
return b'\x17\x03\x03' + packstr(s)
80+
def encrypt(s):
81+
ret = b''
82+
while len(s) > 2048:
83+
size = min(random.randrange(4096)+100, len(s))
84+
ret += pack(s[:size])
85+
s = s[size:]
86+
if s:
87+
ret += pack(s)
88+
return ret
89+
reader.plugin_decrypt2 = decrypt
90+
writer.plugin_encrypt2 = encrypt
91+
92+
class Verify_Simple_Plugin(BasePlugin):
93+
def apply_cipher(self, reader, writer):
94+
self.buf = bytearray()
95+
def decrypt(s):
96+
self.buf.extend(s)
97+
ret = b''
98+
while len(self.buf) >= 2:
99+
l = int.from_bytes(self.buf[:2], 'big')
100+
if len(self.buf) < l:
101+
break
102+
data = self.buf[2+self.buf[2]:l-4]
103+
crc = (-1 - binascii.crc32(self.buf[:l-4])) & 0xffffffff
104+
assert int.from_bytes(self.buf[l-4:l], 'little') == crc
105+
ret += data
106+
del self.buf[:l]
107+
return ret
108+
def pack(s):
109+
rnd_data = os.urandom(os.urandom(1)[0] % 16)
110+
data = bytes([len(rnd_data)+1]) + rnd_data + s
111+
data = (len(data)+6).to_bytes(2, 'big') + data
112+
crc = (-1 - binascii.crc32(data)) & 0xffffffff
113+
return data + crc.to_bytes(4, 'little')
114+
def encrypt(s):
115+
ret = b''
116+
while len(s) > 8100:
117+
ret += pack(s[:8100])
118+
s = s[8100:]
119+
if s:
120+
ret += pack(s)
121+
return ret
122+
reader.plugin_decrypt = decrypt
123+
writer.plugin_encrypt = encrypt
124+
125+
class Verify_Deflate_Plugin(BasePlugin):
126+
def apply_cipher(self, reader, writer):
127+
self.buf = bytearray()
128+
def decrypt(s):
129+
self.buf.extend(s)
130+
ret = b''
131+
while len(self.buf) >= 2:
132+
l = int.from_bytes(self.buf[:2], 'big')
133+
if len(self.buf) < l:
134+
break
135+
ret += zlib.decompress(b'x\x9c' + self.buf[2:l])
136+
del self.buf[:l]
137+
return ret
138+
def pack(s):
139+
packed = zlib.compress(s)
140+
return len(packed).to_bytes(2, 'big') + packed[2:]
141+
def encrypt(s):
142+
ret = b''
143+
while len(s) > 32700:
144+
ret += pack(s[:32700])
145+
s = s[32700:]
146+
if s:
147+
ret += pack(s)
148+
return ret
149+
reader.plugin_decrypt = decrypt
150+
writer.plugin_encrypt = encrypt
151+
152+
PLUGIN = {cls.name(): cls for name, cls in globals().items() if name.endswith('_Plugin')}
153+
154+
def get_plugin(plugin_name):
155+
if plugin_name not in PLUGIN:
156+
return f'existing plugins: {sorted(PLUGIN.keys())}', None
157+
return None, PLUGIN[plugin_name]()
158+

‎pproxy/proto.py‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,21 @@ async def channel(self, reader, writer, stat_bytes, stat_conn):
3737
writer.close()
3838
rchannel = channel
3939

40+
class ShadowsocksR(BaseProtocol):
41+
name = 'ssr'
42+
def correct_header(self, header, auth, **kw):
43+
return auth and header == auth[:1] or not auth and header and header[0] in (1, 3, 4)
44+
async def parse(self, header, reader, auth, authtable, reader_cipher, **kw):
45+
if auth:
46+
if (await reader.read_n(len(auth)-1)) != auth[1:]:
47+
raise Exception('Unauthorized SSR')
48+
authtable.set_authed()
49+
header = await reader.read_n(1)
50+
host_name, port, data = await socks_address_process(reader, header[0])
51+
return host_name, port, b''
52+
async def connect(self, reader_remote, writer_remote, rauth, host_name, port, initbuf, writer_cipher_r, **kw):
53+
writer_remote.write(rauth + b'\x03' + packstr(host_name.encode()) + port.to_bytes(2, 'big') + initbuf)
54+
4055
class Shadowsocks(BaseProtocol):
4156
name = 'ss'
4257
def correct_header(self, header, auth, **kw):
@@ -51,7 +66,7 @@ async def patched_read():
5166
return None
5267
checksum_client = await reader.readexactly(10)
5368
data = await reader.readexactly(data_len)
54-
checksum = hmac.digest(cipher.iv+chunk_id.to_bytes(4, 'big'), data, hashlib.sha1)
69+
checksum = hmac.new(cipher.iv+chunk_id.to_bytes(4, 'big'), data, hashlib.sha1).digest()
5570
assert checksum[:10] == checksum_client
5671
chunk_id += 1
5772
return data
@@ -62,7 +77,7 @@ def patch_ota_writer(self, cipher, writer):
6277
def patched_write(data):
6378
nonlocal chunk_id
6479
if not data: return
65-
checksum = hmac.digest(cipher.iv+chunk_id.to_bytes(4, 'big'), data, hashlib.sha1)
80+
checksum = hmac.new(cipher.iv+chunk_id.to_bytes(4, 'big'), data, hashlib.sha1).digest()
6681
chunk_id += 1
6782
return write(len(data).to_bytes(2, 'big') + checksum[:10] + data)
6883
writer.write = patched_write
@@ -76,15 +91,15 @@ async def parse(self, header, reader, auth, authtable, reader_cipher, **kw):
7691
host_name, port, data = await socks_address_process(reader, header[0])
7792
assert ota or not reader_cipher or not reader_cipher.ota, 'SS client must support OTA'
7893
if ota and reader_cipher:
79-
checksum = hmac.digest(reader_cipher.iv+reader_cipher.key, header+data, hashlib.sha1)
94+
checksum = hmac.new(reader_cipher.iv+reader_cipher.key, header+data, hashlib.sha1).digest()
8095
assert checksum[:10] == (await reader.read_n(10)), 'Unknown OTA checksum'
8196
self.patch_ota_reader(reader_cipher, reader)
8297
return host_name, port, b''
8398
async def connect(self, reader_remote, writer_remote, rauth, host_name, port, initbuf, writer_cipher_r, **kw):
8499
writer_remote.write(rauth)
85100
if writer_cipher_r and writer_cipher_r.ota:
86101
rdata = b'\x13' + packstr(host_name.encode()) + port.to_bytes(2, 'big')
87-
checksum = hmac.digest(writer_cipher_r.iv+writer_cipher_r.key, rdata, hashlib.sha1)
102+
checksum = hmac.new(writer_cipher_r.iv+writer_cipher_r.key, rdata, hashlib.sha1).digest()
88103
writer_remote.write(rdata + checksum[:10])
89104
self.patch_ota_writer(writer_cipher_r, writer_remote)
90105
else:
@@ -139,7 +154,7 @@ async def parse(self, header, reader, writer, auth, authtable, httpget, **kw):
139154
text = (text % dict(host=headers["Host"])).encode()
140155
writer.write(f'{ver} 200 OK\r\nConnection: close\r\nContent-Type: text/plain\r\nCache-Control: max-age=900\r\nContent-Length: {len(text)}\r\n\r\n'.encode() + text)
141156
return None, None, None
142-
raise Exception(f'404 {method} {path}')
157+
raise Exception(f'404 {method} {url.path}')
143158
if auth:
144159
pauth = headers.get('Proxy-Authorization', None)
145160
httpauth = 'Basic ' + base64.b64encode(auth).decode()
@@ -220,7 +235,7 @@ async def parse(protos, reader, **kw):
220235
return (proto,) + ret
221236
raise Exception(f'Unsupported protocol {header}')
222237

223-
MAPPINGS = dict(http=HTTP(), socks=Socks(), ss=Shadowsocks(), redir=Redirect(), ssl='', secure='')
238+
MAPPINGS = dict(http=HTTP(), socks=Socks(), ss=Shadowsocks(), ssr=ShadowsocksR(), redir=Redirect(), ssl='', secure='')
224239

225240
def get_protos(rawprotos):
226241
protos = []

0 commit comments

Comments
 (0)