附錄:零依賴唯讀 a99_pb_rodata_carver.py(已通過沙盒 --selftest,可直接拷入舊機私有目錄跑)
#!/usr/bin/env python3
"""
Read-only ELF/.so .rodata Google Protobuf FileDescriptorProto carver & schema dumper.
Zero external dependencies (pure Python 3 stdlib). No process attach, no memory scan.
Usage on target host:
python3 a99_pb_rodata_carver.py /opt/FTNN/lib/*.so* --filter TradeSection,Kline,Quote,Exright
"""
import re
import sys
from pathlib import Path
WIRE_TYPE_NAMES = {
1: "double", 2: "float", 3: "int64", 4: "uint64", 5: "int32",
6: "fixed64", 7: "fixed32", 8: "bool", 9: "string", 10: "group",
11: "message", 12: "bytes", 13: "uint32", 14: "enum",
15: "sfixed32", 16: "sfixed64", 17: "sint32", 18: "sint64",
}
def read_varint(buf: bytes, pos: int, limit: int):
val = 0
shift = 0
while pos < limit:
b = buf[pos]
pos += 1
val |= (b & 0x7F) << shift
if not (b & 0x80):
return val, pos
shift += 7
if shift > 70:
raise ValueError("varint too long")
raise ValueError("truncated varint")
def iter_fields(buf: bytes, start: int = 0, end: int | None = None):
pos = start
limit = len(buf) if end is None else end
while pos < limit:
tag, pos = read_varint(buf, pos, limit)
if tag == 0:
raise ValueError("zero tag")
fnum = tag >> 3
wtype = tag & 0x7
if wtype == 0:
val, pos = read_varint(buf, pos, limit)
yield fnum, wtype, val
elif wtype == 1:
if pos + 8 > limit:
raise ValueError("truncated fixed64")
yield fnum, wtype, buf[pos:pos + 8]
pos += 8
elif wtype == 2:
ln, pos = read_varint(buf, pos, limit)
if ln < 0 or pos + ln > limit:
raise ValueError("truncated bytes")
yield fnum, wtype, buf[pos:pos + ln]
pos += ln
elif wtype == 5:
if pos + 4 > limit:
raise ValueError("truncated fixed32")
yield fnum, wtype, buf[pos:pos + 4]
pos += 4
else:
raise ValueError(f"unsupported wire type {wtype}")
def parse_enum_value(b: bytes):
name, num = "", 0
for fnum, wt, val in iter_fields(b):
if fnum == 1 and wt == 2:
name = val.decode("utf-8", "replace")
elif fnum == 2 and wt == 0:
num = val if val < (1 << 31) else val - (1 << 64)
return name, num
def parse_enum(b: bytes, prefix: str = ""):
ename = ""
vals = []
for fnum, wt, val in iter_fields(b):
if fnum == 1 and wt == 2:
ename = val.decode("utf-8", "replace")
elif fnum == 2 and wt == 2:
vals.append(parse_enum_value(val))
full = f"{prefix}.{ename}" if prefix else ename
return {"name": full, "values": vals}
def parse_field(b: bytes):
fd = {"name": "", "number": 0, "type": 0, "type_name": ""}
for fnum, wt, val in iter_fields(b):
if fnum == 1 and wt == 2:
fd["name"] = val.decode("utf-8", "replace")
elif fnum == 3 and wt == 0:
fd["number"] = val
elif fnum == 5 and wt == 0:
fd["type"] = val
elif fnum == 6 and wt == 2:
fd["type_name"] = val.decode("utf-8", "replace")
return fd
def parse_message(b: bytes, prefix: str = ""):
mname = ""
fields, nested_msgs, nested_enums = [], [], []
raw_nested_m, raw_nested_e = [], []
for fnum, wt, val in iter_fields(b):
if fnum == 1 and wt == 2:
mname = val.decode("utf-8", "replace")
elif fnum == 2 and wt == 2:
fields.append(parse_field(val))
elif fnum == 3 and wt == 2:
raw_nested_m.append(val)
elif fnum == 4 and wt == 2:
raw_nested_e.append(val)
full = f"{prefix}.{mname}" if prefix else mname
for nm in raw_nested_m:
nested_msgs.extend(parse_message(nm, full))
for ne in raw_nested_e:
nested_enums.append(parse_enum(ne, full))
return [{"name": full, "fields": fields, "enums": nested_enums}] + nested_msgs
def parse_file_descriptor(buf: bytes, start: int):
# Try finding exact end of serialized FileDescriptorProto starting at `start` (0x0a <len> *.proto)
pos = start
limit = min(len(buf), start + 524288)
best = None
fname, pkg = "", ""
msgs, enums, deps = [], [], []
while pos < limit:
try:
tag, nxt = read_varint(buf, pos, limit)
fnum, wt = tag >> 3, tag & 0x7
if fnum == 0 or fnum > 20 or wt not in (0, 1, 2, 5):
break
if wt == 0:
val, nxt = read_varint(buf, nxt, limit)
elif wt == 1:
if nxt + 8 > limit:
break
val, nxt = buf[nxt:nxt + 8], nxt + 8
elif wt == 2:
ln, nxt = read_varint(buf, nxt, limit)
if ln < 0 or nxt + ln > limit:
break
val, nxt = buf[nxt:nxt + ln], nxt + ln
elif wt == 5:
if nxt + 4 > limit:
break
val, nxt = buf[nxt:nxt + 4], nxt + 4
if fnum == 1 and wt == 2:
s = val.decode("utf-8")
if not s.endswith(".proto"):
break
fname = s
elif fnum == 2 and wt == 2:
pkg = val.decode("utf-8")
elif fnum == 3 and wt == 2:
deps.append(val.decode("utf-8"))
elif fnum == 4 and wt == 2:
msgs.extend(parse_message(val, pkg))
elif fnum == 5 and wt == 2:
enums.append(parse_enum(val, pkg))
pos = nxt
if fname and (msgs or enums):
best = {"file": fname, "package": pkg, "deps": deps[:], "messages": msgs[:], "enums": enums[:], "bytes": pos - start}
except Exception:
break
return best
def carve_binary(data: bytes):
out = []
# Match 0x0a <len: 6..120> <ascii_filename.proto>
for m in re.finditer(rb"\x0a([\x06-\x7f])([A-Za-z0-9_./+-]{5,127}\.proto)", data):
decl_len = m.group(1)[0]
actual_name = m.group(2)
if decl_len != len(actual_name):
continue
fd = parse_file_descriptor(data, m.start())
if fd:
out.append(fd)
return out
if __name__ == "__main__":
if "--selftest" in sys.argv:
# Build synthetic serialized FileDescriptorProto inside random binary padding
def enc_varint(n):
out = bytearray()
while True:
b = n & 0x7F
n >>= 7
if n:
out.append(b | 0x80)
else:
out.append(b)
return bytes(out)
def enc_bytes(fnum, b):
return enc_varint((fnum << 3) | 2) + enc_varint(len(b)) + b
def enc_int(fnum, v):
return enc_varint((fnum << 3) | 0) + enc_varint(v)
ev1 = enc_bytes(1, b"TS_V2_REGULAR") + enc_int(2, 12)
ev2 = enc_bytes(1, b"TS_V2_OVERNIGHT") + enc_int(2, 20)
enum_pb = enc_bytes(1, b"TradeSectionV2") + enc_bytes(2, ev1) + enc_bytes(2, ev2)
fld_pb = enc_bytes(1, b"trade_section_v2") + enc_int(3, 14) + enc_int(5, 14) + enc_bytes(6, b".FTCmdKline.TradeSectionV2")
msg_pb = enc_bytes(1, b"KlineItem") + enc_bytes(2, fld_pb)
file_pb = enc_bytes(1, b"FTCmdKline.proto") + enc_bytes(2, b"FTCmdKline") + enc_bytes(4, msg_pb) + enc_bytes(5, enum_pb)
fake_so = b"\x7fELF\x00\x99garbage" + file_pb + b"\x00\xfftrailing_rodata"
carved = carve_binary(fake_so)
assert len(carved) == 1 and carved[0]["file"] == "FTCmdKline.proto", carved
assert carved[0]["enums"][0]["values"] == [("TS_V2_REGULAR", 12), ("TS_V2_OVERNIGHT", 20)], carved
assert carved[0]["messages"][0]["fields"][0]["type_name"] == ".FTCmdKline.TradeSectionV2", carved
print("SELFTEST_PASS:", carved)
sys.exit(0)
flt = []
paths = []
it = iter(sys.argv[1:])
for arg in it:
if arg == "--filter":
flt = [x.strip().lower() for x in next(it, "").split(",") if x.strip()]
else:
paths.append(Path(arg))
for p in paths:
if not p.is_file():
continue
data = p.read_bytes()
for fd in carve_binary(data):
blob_txt = repr(fd).lower()
if flt and not any(k in blob_txt for k in flt):
continue
print(f"=== {p.name} :: {fd['file']} (pkg={fd['package']}, {fd['bytes']} B) ===")
for en in fd["enums"]:
print(f" enum {en['name']}: {en['values']}")
for msg in fd["messages"]:
print(f" message {msg['name']}:")
for ne in msg["enums"]:
print(f" nested enum {ne['name']}: {ne['values']}")
for f in msg["fields"]:
tstr = WIRE_TYPE_NAMES.get(f["type"], str(f["type"]))
tn = f" ({f['type_name']})" if f["type_name"] else ""
print(f" {f['number']:3d}: {tstr}{tn} {f['name']}")