Repository navigation
Expand file tree
/
Copy pathplugin.py
More file actions
207 lines (181 loc) · 9.02 KB
/
Copy pathplugin.py
File metadata and controls
207 lines (181 loc) · 9.02 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
"""Optional protocol framing plugins used by cipher connections."""
import binascii
import collections
import datetime
import hashlib
import hmac
import os
import random
import time
import zlib
from . import transport
from .errors import require
# Plugin class names mirror the existing wire-format registry keys.
# Serialized handshake records intentionally keep related bytes together.
# pylint: disable=invalid-name,line-too-long
def packstr(value, size=2):
"""Prefix bytes with a big-endian length field."""
return len(value).to_bytes(size, 'big') + value
def toint(value, order='big'):
"""Decode an integer from a byte string."""
return int.from_bytes(value, order)
class BasePlugin:
"""Base interface for optional cipher framing plugins."""
buf: bytearray
async def init_client_data(self, reader, writer, cipher):
"""Send or consume client-side handshake data when required."""
async def init_server_data(self, reader, writer, cipher, raddr):
"""Send or consume server-side handshake data when required."""
def add_cipher(self, cipher):
"""Attach plugin-specific framing callbacks to a cipher session."""
@classmethod
def name(cls):
"""Return the registry name derived from the plugin class name."""
return cls.__name__.replace('_Plugin', '').replace('__', '.').lower()
class Plain_Plugin(BasePlugin):
"""Plugin that leaves cipher payloads unframed."""
class Origin_Plugin(BasePlugin):
"""Plugin marker for the origin-compatible framing mode."""
class Http_Simple_Plugin(BasePlugin):
"""Wrap the initial exchange in a simple HTTP-looking handshake."""
async def init_client_data(self, reader, writer, cipher):
"""Decode the client preamble and send an HTTP response."""
buf = await transport.read_until(reader, b'\r\n\r\n')
data = buf.split(b' ')[:2]
data = bytes.fromhex(data[1][1:].replace(b'%',b'').decode())
transport.prepend(reader, data)
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')
async def init_server_data(self, reader, writer, cipher, raddr):
"""Send an HTTP request-looking preamble to the client."""
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())
await transport.read_until(reader, b'\r\n\r\n')
TIMESTAMP_TOLERANCE = 5 * 60
class Tls1__2_Ticket_Auth_Plugin(BasePlugin):
"""Implement the legacy TLS 1.2 ticket-authentication framing."""
CACHE = collections.deque(maxlen = 100)
async def init_client_data(self, reader, writer, cipher):
"""Validate a server preamble and send the client handshake."""
key = cipher.cipher(cipher.key).key
require(await transport.read_exactly(reader, 3) == b'\x16\x03\x01')
header = await transport.read_exactly(reader, toint(await transport.read_exactly(reader, 2)))
require(header[:2] == b'\x01\x00')
require(header[4:6] == b'\x03\x03')
cacheid = header[6:28]
sessionid = header[39:39+header[38]]
require(cacheid not in self.CACHE)
self.CACHE.append(cacheid)
utc_time = int(time.time())
require(hmac.new(key+sessionid, cacheid, hashlib.sha1).digest()[:10] == header[28:38])
require(abs(toint(header[6:10]) - utc_time) < TIMESTAMP_TOLERANCE)
def addhmac(data):
"""Append the ticket-authentication MAC to handshake data."""
return data + hmac.new(key+sessionid, data, hashlib.sha1).digest()[:10]
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]))
async def init_server_data(self, reader, writer, cipher, raddr):
"""Send a server-side TLS-looking handshake preamble."""
key = cipher.cipher(cipher.key).key
sessionid = os.urandom(32)
def addhmac(data):
"""Append the ticket-authentication MAC to handshake data."""
return data + hmac.new(key+sessionid, data, hashlib.sha1).digest()[:10]
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"))))
writer.write(addhmac(b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00\x20' + os.urandom(22)))
def add_cipher(self, cipher):
"""Install TLS-record extraction and packetization callbacks."""
self.buf = bytearray()
def decrypt(s):
self.buf.extend(s)
ret = b''
while len(self.buf) >= 5:
l = int.from_bytes(self.buf[3:5], 'big')
if len(self.buf) < l:
break
if self.buf[:3] in (b'\x16\x03\x03', b'\x14\x03\x03'):
del self.buf[:5+l]
continue
require(self.buf[:3] == b'\x17\x03\x03')
data = self.buf[5:5+l]
ret += data
del self.buf[:5+l]
return ret
def pack(s):
return b'\x17\x03\x03' + packstr(s)
def encrypt(s):
ret = b''
while len(s) > 2048:
size = min(random.randrange(4096)+100, len(s))
ret += pack(s[:size])
s = s[size:]
if s:
ret += pack(s)
return ret
cipher.pdecrypt2 = decrypt
cipher.pencrypt2 = encrypt
class Verify_Simple_Plugin(BasePlugin):
"""Add CRC-protected variable-length payload framing."""
def add_cipher(self, cipher):
"""Install CRC verification and payload framing callbacks."""
self.buf = bytearray()
def decrypt(s):
self.buf.extend(s)
ret = b''
while len(self.buf) >= 2:
l = int.from_bytes(self.buf[:2], 'big')
if len(self.buf) < l:
break
data = self.buf[2+self.buf[2]:l-4]
crc = (-1 - binascii.crc32(self.buf[:l-4])) & 0xffffffff
require(int.from_bytes(self.buf[l-4:l], 'little') == crc)
ret += data
del self.buf[:l]
return ret
def pack(s):
rnd_data = os.urandom(os.urandom(1)[0] % 16)
data = bytes([len(rnd_data)+1]) + rnd_data + s
data = (len(data)+6).to_bytes(2, 'big') + data
crc = (-1 - binascii.crc32(data)) & 0xffffffff
return data + crc.to_bytes(4, 'little')
def encrypt(s):
ret = b''
while len(s) > 8100:
ret += pack(s[:8100])
s = s[8100:]
if s:
ret += pack(s)
return ret
cipher.pdecrypt = decrypt
cipher.pencrypt = encrypt
class Verify_Deflate_Plugin(BasePlugin):
"""Add compressed variable-length payload framing."""
def add_cipher(self, cipher):
"""Install zlib decompression and compression callbacks."""
self.buf = bytearray()
def decrypt(s):
self.buf.extend(s)
ret = b''
while len(self.buf) >= 2:
l = int.from_bytes(self.buf[:2], 'big')
if len(self.buf) < l:
break
ret += zlib.decompress(b'x\x9c' + self.buf[2:l])
del self.buf[:l]
return ret
def pack(s):
packed = zlib.compress(s)
return len(packed).to_bytes(2, 'big') + packed[2:]
def encrypt(s):
ret = b''
while len(s) > 32700:
ret += pack(s[:32700])
s = s[32700:]
if s:
ret += pack(s)
return ret
cipher.pdecrypt = decrypt
cipher.pencrypt = encrypt
PLUGIN = {cls.name(): cls for name, cls in globals().items() if name.endswith('_Plugin')}
def get_plugin(plugin_name):
"""Resolve a plugin name to a fresh plugin instance."""
if plugin_name not in PLUGIN:
return f'existing plugins: {sorted(PLUGIN.keys())}', None
return None, PLUGIN[plugin_name]()