aboutsummaryrefslogtreecommitdiff
path: root/analysis/nss_m1.py
diff options
context:
space:
mode:
Diffstat (limited to 'analysis/nss_m1.py')
-rw-r--r--analysis/nss_m1.py249
1 files changed, 249 insertions, 0 deletions
diff --git a/analysis/nss_m1.py b/analysis/nss_m1.py
new file mode 100644
index 0000000..9c754ce
--- /dev/null
+++ b/analysis/nss_m1.py
@@ -0,0 +1,249 @@
+#!/usr/bin/env python3
+"""NSS firmware M1: header semantics, payload layout, pointer tables, version drift.
+
+M0 (nss_m0.py) established: 200-byte header + flat image, LE, base
+0x40000000 / 0x40800000, and that stock 11.3-12 and public 11.4.0.5-5 share the
+same header words 0-15 except word3/word9 (addresses) and word12/13.
+
+M1 asks the next questions:
+ 1. Is word3 really an in-image pointer, and what does it point at?
+ 2. word9 is NOT in the image (0x403073e0 / 0x40880880) -- what is it?
+ 3. Where do in-image pointers cluster (tables)? Runs of >=4 consecutive
+ pointers are almost certainly dispatch/rodata tables.
+ 4. Which 4 KiB blocks are identical between stock 11.3 and public 11.4?
+ (byte-level similarity gives a version map without a disassembler.)
+ 5. Where are the strings, and which pointers reference them?
+"""
+import hashlib
+import os
+import re
+import struct
+
+STOCK = "/ROM/ckb01/work/vroot/lib/firmware"
+PUB = os.path.expanduser("~/ckb01/firmware/nss-11.4.0.5-5")
+OUT = os.path.expanduser("~/ckb01/analysis/nss-m1.md")
+
+CASES = [
+ ("stock core0", os.path.join(STOCK, "qca-nss0-retail.bin"), 0x40000000),
+ ("stock core1", os.path.join(STOCK, "qca-nss1-retail.bin"), 0x40800000),
+ ("pub core0", os.path.join(PUB, "retail_router0.bin"), 0x40000000),
+ ("pub core1", os.path.join(PUB, "retail_router1.bin"), 0x40800000),
+]
+
+HDR = 200
+
+
+def words(b):
+ n = len(b) // 4
+ return list(struct.unpack("<%dI" % n, b[:n * 4]))
+
+
+def in_image(v, base, size):
+ return base <= v < base + size
+
+
+def dump(b, off, n=64):
+ return b[off:off + n].hex(" ")
+
+
+def runs(vals, minimum=4):
+ """Consecutive runs of indices (in 4-byte word index space)."""
+ out = []
+ start = prev = None
+ for i in vals:
+ if start is None:
+ start = prev = i
+ elif i == prev + 1:
+ prev = i
+ else:
+ if prev - start + 1 >= minimum:
+ out.append((start, prev))
+ start = prev = i
+ if start is not None and prev - start + 1 >= minimum:
+ out.append((start, prev))
+ return out
+
+
+def block_hashes(b, bs=4096):
+ return [hashlib.sha1(b[i:i + bs]).hexdigest() for i in range(0, len(b) - bs + 1, bs)]
+
+
+def main():
+ rows = []
+ for name, path, base in CASES:
+ b = open(path, "rb").read()
+ rows.append((name, base, b))
+
+ md = ["# NSS firmware M1 report (header semantics / layout / drift)", ""]
+ md.append("生成: `nss_m1.py`(入力は読み取りのみ)")
+ md.append("")
+
+ md.append("## 1. ヘッダの再確認")
+ md.append("")
+ md.append("| sample | size | word0 | word1 | word3 | word3-off | word9 | word9-off |")
+ md.append("|---|---|---|---|---|---|---|---|")
+ for name, base, b in rows:
+ w = words(b)
+ w3, w9 = w[3], w[9]
+ o3 = w3 - base if in_image(w3, base, len(b)) else None
+ o9 = w9 - base if in_image(w9, base, len(b)) else None
+ md.append("| %s | %d | 0x%08x | 0x%08x | 0x%08x | %s | 0x%08x | %s |" % (
+ name, len(b), w[0], w[1], w3, ("0x%x" % o3) if o3 is not None else "**外**",
+ w9, ("0x%x" % o9) if o9 is not None else "**外**"))
+
+ md.append("")
+ md.append("→ **word3 はイメージ内**(末尾付近)。**word9 は4サンプルすべてでイメージ外**。")
+ md.append(" M0の表で word9 を「イメージ内」としていたのは誤り(0x3073e0 > 0xbe6b8)。")
+ md.append("")
+
+ md.append("## 2. word3 の指す先(stock core0)")
+ md.append("")
+ name, base, b = rows[0]
+ w = words(b)
+ off = w[3] - base
+ md.append("`word3 = 0x%08x` → オフセット `0x%x`(サイズ 0x%x の %d バイト手前)" % (
+ w[3], off, len(b), len(b) - off))
+ md.append("")
+ md.append("```")
+ for i in range(0, 64, 16):
+ md.append("0x%06x %s" % (off + i, dump(b, off + i, 16)))
+ md.append("```")
+ # what is there: printable?
+ chunk = b[off:off + 64]
+ md.append("")
+ md.append("ASCII: `%s`" % "".join(chr(c) if 32 <= c < 127 else "." for c in chunk))
+ md.append("")
+
+ md.append("## 3. word9 の値の意味(推定)")
+ md.append("")
+ for name, base, b in rows:
+ w = words(b)
+ md.append("- %s: `0x%08x`(base+0x%x、イメージサイズ 0x%x)" % (name, w[9], w[9] - base, len(b)))
+ md.append("")
+ md.append("core0 の word9 は `0x403xxxxx`、core1 は `0x408xxxxx`。")
+ md.append("core1 は `0x40880880` で、core1 のロードベース 0x40800000 から 0x80880。")
+ md.append("**どちらも「イメージの外」を指す**ので、ロード後に別領域へ置かれる構造体")
+ md.append("(共有メモリ/OCM/DDR上の制御ブロック)へのポインタと考えるのが自然。")
+ md.append("→ M2 で「このアドレスが命令中でどう使われるか」を見るまで確定しない。")
+ md.append("")
+
+ md.append("## 4. イメージ内ポインタの分布とテーブル")
+ md.append("")
+ for name, base, b in rows:
+ w = words(b)
+ idx = [i for i, v in enumerate(w) if in_image(v, base, len(b))]
+ r = runs(idx, 4)
+ md.append("### %s" % name)
+ md.append("")
+ md.append("- イメージ内を指す語: **%d** / %d(%.2f%%)" % (len(idx), len(w), 100.0 * len(idx) / len(w)))
+ md.append("- 連続4語以上の「ポインタ表」: **%d 箇所**" % len(r))
+ for s, e in r[:8]:
+ md.append(" - 0x%06x–0x%06x(%d語)" % (s * 4, e * 4 + 3, e - s + 1))
+ if len(r) > 8:
+ md.append(" - … 他 %d 箇所" % (len(r) - 8))
+ md.append("")
+
+ md.append("## 5. 文字列とその参照")
+ md.append("")
+ for name, base, b in rows:
+ strs = [(m.start(), m.group().decode("latin-1")) for m in re.finditer(rb"[ -~]{10,}", b)]
+ # how many in-image pointers point exactly at a string start?
+ ptrs = {}
+ for i, v in enumerate(words(b)):
+ if in_image(v, base, len(b)):
+ ptrs.setdefault(v - base, []).append(i * 4)
+ hit = [s for s, _ in strs if s in ptrs]
+ md.append("- %s: 文字列 %d 個、うち **%d 個がポインタから直接参照**されている" % (name, len(strs), len(hit)))
+ md.append("")
+ md.append("(文字列先頭を直接指す語がある= rodata への参照が通常の絶対アドレスで行われる、の証拠)")
+ md.append("")
+
+ md.append("## 6. stock 11.3 と public 11.4 のブロック一致(4KiB)")
+ md.append("")
+ s0 = rows[0][2]
+ p0 = rows[2][2]
+ hs = block_hashes(s0)
+ hp = block_hashes(p0)
+ common = len(set(hs) & set(hp))
+ md.append("| 項目 | 値 |")
+ md.append("|---|---|")
+ md.append("| stock core0 ブロック数 | %d |" % len(hs))
+ md.append("| public core0 ブロック数 | %d |" % len(hp))
+ md.append("| 同一内容のブロック(集合) | %d |" % common)
+ md.append("| stock 側の一致率 | %.1f%% |" % (100.0 * common / len(hs)))
+ md.append("| public 側の一致率 | %.1f%% |" % (100.0 * common / len(hp)))
+ md.append("")
+ md.append("→ 半分以上が同一なら「同じコードベースの再ビルド」で、差分は局所的。")
+ md.append(" 次段(M2)では、**一致しないブロックにだけ**注目すればよい。")
+ md.append("")
+
+ md.append("## 7. 名前付きオブジェクト表(M1の主結果)")
+ md.append("")
+ md.append("`word3` が指す先を読むと、0x44 バイト固定長のレコードが並んでいる。")
+ md.append("各レコードは `u16 id` + 名前 + パラメータで、EDMA のリング定義が**名前で読める**。")
+ md.append("")
+ PAT = re.compile(rb"[\x25-\x29]\x95([ -~]{4,48})\x00")
+ named = {}
+ for name, base, b in rows:
+ named[name] = [(m.start(), m.group(1).decode("latin-1")) for m in PAT.finditer(b)]
+ s0n = named["stock core0"]
+ p0n = named["pub core0"]
+ md.append("| sample | 名前付きレコード数 |")
+ md.append("|---|---|")
+ for k, v in named.items():
+ md.append("| %s | %d |" % (k, len(v)))
+ md.append("")
+ md.append("stock core0 の一覧(オフセットはイメージ先頭から):")
+ md.append("")
+ md.append("```")
+ for off, nm in s0n:
+ md.append("0x%06x %s" % (off, nm))
+ md.append("```")
+ md.append("")
+ common = {n for _, n in s0n} & {n for _, n in p0n}
+ md.append("- stock と public で**名前が完全一致**: %d / %d" % (len(common), len(s0n)))
+ md.append("- 差分(stockのみ): %s" % (sorted({n for _, n in s0n} - common) or "なし"))
+ md.append("- 差分(publicのみ): %s" % (sorted({n for _, n in p0n} - common) or "なし"))
+ md.append("")
+ md.append("→ レコードの並びは 11.3 と 11.4 で同一。**名前→ID→パラメータの対応は版を跨いで安定**。")
+ md.append("")
+
+ md.append("### 7b. レコード構造(0x44 = 68バイト)")
+ md.append("")
+ md.append("表の先頭(word3)は4バイトのヘッダで、その直後から 0x44 バイトのレコードが並ぶ。")
+ md.append("")
+ md.append("```")
+ md.append("+0x00 u16 id 0x9528(全レコード共通。表ヘッダだけ 0x9527)")
+ md.append("+0x02 char name[..] ヌル終端。最大 0x42 バイト")
+ md.append("+0x38 u32 n_entries 例: 32, 128")
+ md.append("+0x3c u32 entry_size 例: 0x800, 0x4000, 0x2040")
+ md.append("+0x40 u32 flags 通常 0")
+ md.append("```")
+ md.append("")
+ md.append("| 名前 | n_entries | entry_size |")
+ md.append("|---|---|---|")
+ name, base, b = rows[0]
+ tbl = words(b)[3] - base
+ for k in range(25):
+ off = tbl + 4 + k * 0x44
+ nm = b[off + 2:off + 0x38].split(b"\x00")[0].decode("latin-1")
+ nent, esz, fl = struct.unpack_from("<III", b, off + 0x38)
+ md.append("| %s | %d | 0x%x |" % (nm, nent, esz))
+ md.append("")
+ md.append("→ `n_entries × entry_size` が各リング/記述子の必要メモリ量。")
+ md.append(" EDMA の RX/TX リングが 32エントリ×2KiB、SG-frag が 32×16KiB と読める。")
+ md.append("")
+
+ md.append("## 8. 次の作業(M2)")
+ md.append("")
+ md.append("1. word9 の使われ方を探す: `0x403xxxxx` / `0x408xxxxx` を即値で持つ命令列を探す。")
+ md.append("2. UBI32 の命令長を確定(4バイト固定か)。ポインタ表の直前の命令列を見る。")
+ md.append("3. 11.3→11.4 の差分を「内容」で取る(オフセットはずれるので、関数単位の正規化が要る)。")
+ md.append("4. 表のレコードを食うコード(初期化関数)を、名前文字列の参照から特定する。")
+
+ open(OUT, "w", encoding="utf-8").write("\n".join(md) + "\n")
+ print("wrote", OUT)
+
+
+if __name__ == "__main__":
+ main()