diff options
| author | Narek Shaghoyan <narekshagoyan7@gmail.com> | 2026-11-22 17:10:56 +0000 |
|---|---|---|
| committer | Narek Shaghoyan <narekshagoyan7@gmail.com> | 2026-11-22 17:10:56 +0000 |
| commit | f616da931f782dc9c753b2a9d2fe4fbaff831f9a (patch) | |
| tree | 4d5c275cffddce4a83c4ebc8999c6a4296f1cb83 /tools/rbf0_encode.py | |
| parent | 49475796c226c8511b9470bf97a4daf57b8af323 (diff) | |
rbf0_encode: fail closed on malformed reports, bool indices, direct NaN, and float32 overflow
Harden tools/rbf0_encode.py so edited/malformed trees and JSON reports raise clean EncodeError / SystemExit messages instead of tracebacks: reject bool for descriptor/attrs_declared, catch direct math.nan and struct.pack OverflowError in float_bits(), reject non-dict documents and non-str text, and validate report JSON/shape/offsets/OSError in write_all(). Synthetic tests added in tests/test_rbf0_encode.py.
Diffstat (limited to 'tools/rbf0_encode.py')
| -rw-r--r-- | tools/rbf0_encode.py | 64 |
1 files changed, 45 insertions, 19 deletions
diff --git a/tools/rbf0_encode.py b/tools/rbf0_encode.py index 7bc8ddce5..eaf9d9c04 100644 --- a/tools/rbf0_encode.py +++ b/tools/rbf0_encode.py | |||
| @@ -61,7 +61,7 @@ class _Writer: | |||
| 61 | 61 | ||
| 62 | def record(self, node, kind): | 62 | def record(self, node, kind): |
| 63 | index = node.get("descriptor") | 63 | index = node.get("descriptor") |
| 64 | if not isinstance(index, int) or not 0 <= index < 0xFD: | 64 | if not isinstance(index, int) or isinstance(index, bool) or not 0 <= index < 0xFD: |
| 65 | raise EncodeError("descriptor", f"descriptor index {index!r} cannot be written") | 65 | raise EncodeError("descriptor", f"descriptor index {index!r} cannot be written") |
| 66 | if index > self.emitted: | 66 | if index > self.emitted: |
| 67 | raise EncodeError("descriptor", f"descriptor {index} is used before descriptor {self.emitted}") | 67 | raise EncodeError("descriptor", f"descriptor {index} is used before descriptor {self.emitted}") |
| @@ -87,7 +87,13 @@ class _Writer: | |||
| 87 | raise EncodeError("value", f"float spelling {special!r}") | 87 | raise EncodeError("value", f"float spelling {special!r}") |
| 88 | if not isinstance(value, (int, float)) or isinstance(value, bool): | 88 | if not isinstance(value, (int, float)) or isinstance(value, bool): |
| 89 | raise EncodeError("value", f"float value {value!r}") | 89 | raise EncodeError("value", f"float value {value!r}") |
| 90 | return struct.pack("<d" if self.wide else "<f", float(value)) | 90 | fval = float(value) |
| 91 | if math.isnan(fval): | ||
| 92 | raise EncodeError("nan", "a NaN float's bits are not in the tree") | ||
| 93 | try: | ||
| 94 | return struct.pack("<d" if self.wide else "<f", fval) | ||
| 95 | except OverflowError: | ||
| 96 | raise EncodeError("value", f"float value {value!r} overflows {'double' if self.wide else 'float32'}") from None | ||
| 91 | 97 | ||
| 92 | def value(self, node): | 98 | def value(self, node): |
| 93 | kind = node.get("type") | 99 | kind = node.get("type") |
| @@ -129,16 +135,19 @@ class _Writer: | |||
| 129 | def text(self, node): | 135 | def text(self, node): |
| 130 | if node.get("utf8_valid") is False: | 136 | if node.get("utf8_valid") is False: |
| 131 | raise EncodeError("utf8", "a text record had invalid UTF-8") | 137 | raise EncodeError("utf8", "a text record had invalid UTF-8") |
| 132 | raw = node.get("text", "").encode("utf-8") + (b"\x00" if node.get("nul_terminated") else b"") | 138 | text = node.get("text", "") |
| 133 | if "length" in node and len(raw) != node["length"]: | 139 | if not isinstance(text, str): |
| 134 | raise EncodeError("length", f"text of {len(raw)} bytes, recorded {node['length']}") | 140 | raise EncodeError("value", f"text value {text!r}") |
| 141 | raw = text.encode("utf-8") + (b"\x00" if node.get("nul_terminated") else b"") | ||
| 142 | if len(raw) > 0xFFFFFFFF or ("length" in node and len(raw) != node["length"]): | ||
| 143 | raise EncodeError("length", f"text of {len(raw)} bytes, recorded {node.get('length')}") | ||
| 135 | self.out += b"\xfd\xff" + struct.pack("<I", len(raw)) + raw | 144 | self.out += b"\xfd\xff" + struct.pack("<I", len(raw)) + raw |
| 136 | 145 | ||
| 137 | def element(self, node): | 146 | def element(self, node): |
| 138 | if node.get("attribute_order_violation"): | 147 | if node.get("attribute_order_violation"): |
| 139 | raise EncodeError("order", f"element {node.get('name')!r} has a value attribute after its content") | 148 | raise EncodeError("order", f"element {node.get('name')!r} has a value attribute after its content") |
| 140 | attrs = node.get("attrs_declared", len(node.get("attributes", []))) | 149 | attrs = node.get("attrs_declared", len(node.get("attributes", []))) |
| 141 | if not isinstance(attrs, int) or not 0 <= attrs <= 0xFFFF: | 150 | if not isinstance(attrs, int) or isinstance(attrs, bool) or not 0 <= attrs <= 0xFFFF: |
| 142 | raise EncodeError("value", f"attribute count {attrs!r}") | 151 | raise EncodeError("value", f"attribute count {attrs!r}") |
| 143 | self.record(node, 0x00) | 152 | self.record(node, 0x00) |
| 144 | self.out += struct.pack("<HHH", 0, 0, attrs) | 153 | self.out += struct.pack("<HHH", 0, 0, attrs) |
| @@ -159,12 +168,14 @@ class _Writer: | |||
| 159 | 168 | ||
| 160 | def encode(doc): | 169 | def encode(doc): |
| 161 | """The RBF0 bytes of one rbf0_tree document. Raises EncodeError when they would not be the original's.""" | 170 | """The RBF0 bytes of one rbf0_tree document. Raises EncodeError when they would not be the original's.""" |
| 171 | if not isinstance(doc, dict): | ||
| 172 | raise EncodeError("value", f"resource document {doc!r}") | ||
| 162 | if doc.get("status") != "ok": | 173 | if doc.get("status") != "ok": |
| 163 | raise EncodeError("status", f"the parse status is {doc.get('status')!r}") | 174 | raise EncodeError("status", f"the parse status is {doc.get('status')!r}") |
| 164 | if doc.get("layout") not in ("wide-64", "narrow-32"): | 175 | if doc.get("layout") not in ("wide-64", "narrow-32"): |
| 165 | raise EncodeError("value", f"layout {doc.get('layout')!r}") | 176 | raise EncodeError("value", f"layout {doc.get('layout')!r}") |
| 166 | tree = doc.get("tree") | 177 | tree = doc.get("tree") |
| 167 | if not tree or tree.get("kind") != "element": | 178 | if not isinstance(tree, dict) or tree.get("kind") != "element": |
| 168 | raise EncodeError("status", "no root element") | 179 | raise EncodeError("status", "no root element") |
| 169 | w = _Writer(doc) | 180 | w = _Writer(doc) |
| 170 | w.element(tree) | 181 | w.element(tree) |
| @@ -207,25 +218,40 @@ def check(source, limit=None): | |||
| 207 | 218 | ||
| 208 | def write_all(report, out_dir): | 219 | def write_all(report, out_dir): |
| 209 | """Encode every resource of an rbf0_tree JSON report into out_dir. Returns (written, refused).""" | 220 | """Encode every resource of an rbf0_tree JSON report into out_dir. Returns (written, refused).""" |
| 210 | with open(report, encoding="utf-8") as f: | 221 | try: |
| 211 | data = json.load(f) | 222 | with open(report, encoding="utf-8") as f: |
| 212 | if data.get("tool") != "rbf0_tree": | 223 | data = json.load(f) |
| 224 | except (OSError, json.JSONDecodeError) as e: | ||
| 225 | raise SystemExit(f"{report}: cannot read report: {e}") from None | ||
| 226 | if not isinstance(data, dict) or data.get("tool") != "rbf0_tree": | ||
| 213 | raise SystemExit(f"{report}: not an rbf0_tree.py JSON report") | 227 | raise SystemExit(f"{report}: not an rbf0_tree.py JSON report") |
| 214 | if os.path.exists(out_dir) and (not os.path.isdir(out_dir) or os.listdir(out_dir)): | 228 | items = data.get("resources", []) |
| 215 | raise SystemExit(f"refusing to write into an existing non-empty path: {out_dir}") | 229 | if not isinstance(items, list): |
| 216 | os.makedirs(out_dir, exist_ok=True) | 230 | raise SystemExit(f"{report}: 'resources' must be a list") |
| 231 | try: | ||
| 232 | if os.path.exists(out_dir) and (not os.path.isdir(out_dir) or os.listdir(out_dir)): | ||
| 233 | raise SystemExit(f"refusing to write into an existing non-empty path: {out_dir}") | ||
| 234 | os.makedirs(out_dir, exist_ok=True) | ||
| 235 | except OSError as e: | ||
| 236 | raise SystemExit(f"{out_dir}: cannot prepare output directory: {e.strerror or e}") from None | ||
| 217 | written, refused = 0, [] | 237 | written, refused = 0, [] |
| 218 | for i, doc in enumerate(data.get("resources", [])): | 238 | for i, doc in enumerate(items): |
| 239 | raw_offset = doc.get("offset", i) if isinstance(doc, dict) else i | ||
| 219 | try: | 240 | try: |
| 220 | blob = encode(doc) | 241 | blob = encode(doc) |
| 221 | except EncodeError as e: | 242 | except EncodeError as e: |
| 222 | refused.append((doc.get("offset", i), str(e))) | 243 | refused.append((raw_offset, str(e))) |
| 223 | continue | 244 | continue |
| 224 | name = f"{doc.get('offset', i):08x}.rbf" | 245 | file_offset = raw_offset if isinstance(raw_offset, int) and not isinstance(raw_offset, bool) and raw_offset >= 0 else i |
| 246 | name = f"{file_offset:08x}.rbf" | ||
| 225 | if os.path.exists(os.path.join(out_dir, name)): | 247 | if os.path.exists(os.path.join(out_dir, name)): |
| 226 | name = f"{doc.get('offset', i):08x}-{i:04d}.rbf" | 248 | name = f"{file_offset:08x}-{i:04d}.rbf" |
| 227 | with open(os.path.join(out_dir, name), "xb") as f: | 249 | target = os.path.join(out_dir, name) |
| 228 | f.write(blob) | 250 | try: |
| 251 | with open(target, "xb") as f: | ||
| 252 | f.write(blob) | ||
| 253 | except OSError as e: | ||
| 254 | raise SystemExit(f"{target}: cannot write: {e.strerror or e}") from None | ||
| 229 | written += 1 | 255 | written += 1 |
| 230 | return written, refused | 256 | return written, refused |
| 231 | 257 | ||