1 #!/usr/bin/env python3 2 # SPDX-License-Identifier: GPL-2.0-or-later 3 """Format, checksum and failure-path tests; no target or flash access. 4 5 python3 tests/test_y3_image.py build/y3-image 6 Add --vendor FILE.y3 for each optional legacy vendor image to repack. 7 """ 8 9 import argparse 10 import hashlib 11 import os 12 from pathlib import Path 13 import resource 14 import signal 15 import subprocess 16 import tempfile 17 import unittest 18 19 20 class Y3ImageTest(unittest.TestCase): 21 def setUp(self): 22 self.tmp = tempfile.TemporaryDirectory(prefix="test-y3-") 23 self.addCleanup(self.tmp.cleanup) 24 self.directory = Path(self.tmp.name) 25 self.input = self.directory / "input.ubi" 26 self.output = self.directory / "output.y3" 27 # Deliberately opaque after the EC header: the packager must not 28 # interpret or change filesystems, volumes or their checksums. 29 self.payload = b"UBI#\x01" + bytes(59) + bytes(range(256)) * 513 30 self.input.write_bytes(self.payload) 31 self.base = [str(BINARY), "-i", str(self.input), "-o", str(self.output), 32 "-c", "6846", "-m", "PANTHER", "-a", "all arm_xscale"] 33 34 def run_tool(self, *args, success=True, command=None, **kwargs): 35 result = subprocess.run((command or self.base) + list(args), 36 capture_output=True, timeout=30, **kwargs) 37 self.assertNotIn(b"Sanitizer", result.stderr) 38 self.assertNotIn(b"runtime error:", result.stderr) 39 self.assertEqual(result.returncode, 0 if success else 1, 40 result.stderr.decode(errors="replace")) 41 return result 42 43 def check_image(self, payload): 44 image = self.output.read_bytes() 45 header = image[:1024] 46 text, padding = header.split(b"\0", 1) 47 self.assertEqual(padding, bytes(len(padding))) 48 lines = text.decode("ascii").splitlines() 49 self.assertEqual(lines.pop(0), "IntenoIopY") 50 fields = dict(line.split(" ", 1) for line in lines) 51 self.assertEqual(len(fields), len(lines), "duplicate header keys") 52 self.assertEqual(fields["version"], "8") 53 self.assertEqual(fields["integrity"], "MD5SUM") 54 self.assertEqual(fields["flags"], "singlepureubi bpartit32") 55 self.assertEqual(int(fields["size"]), len(image)) 56 self.assertEqual(int(fields["md5ofs"]), len(image) - 32) 57 self.assertEqual(fields["md5"], "32") 58 self.assertEqual(image[-32:], hashlib.md5(image[:-32]).hexdigest().encode()) 59 self.assertEqual(int(fields["ubiofs"]), 1024) 60 self.assertEqual(int(fields["ubi"]), len(payload)) 61 self.assertEqual(image[1024:-32], payload) 62 for section in ("cfe", "rescue", "vmlinux", "ubifs", "pkginfo", "scr", "sig"): 63 self.assertEqual(fields[section], "0", section) 64 self.assertGreaterEqual(int(fields[section + "ofs"]), 1024) 65 self.assertLessEqual(int(fields[section + "ofs"]), len(image) - 32) 66 self.assertNotIn("loader", fields) 67 self.assertNotIn("cfever", fields) 68 # CFE's bounded scanner searches for newline-prefixed tags. 69 for key in ("version", "chip", "cfeofs", "cfe", "vmlinuxofs", 70 "ubiofs", "ubi", "md5ofs", "size"): 71 self.assertLess(header.index(b"\n" + key.encode() + b" "), 1005) 72 return fields 73 74 def test_help_and_required_options(self): 75 self.run_tool("-h", command=[str(BINARY)]) 76 for args in ([], ["-i", str(self.input)], ["-z"]): 77 self.run_tool(*args, command=[str(BINARY)], success=False) 78 self.run_tool("extra", success=False) 79 self.assertFalse(self.output.exists()) 80 81 def test_header_payload_and_checksum(self): 82 self.run_tool() 83 fields = self.check_image(self.payload) 84 self.assertEqual(fields["chip"], "6846") 85 self.assertEqual(fields["model"], "PANTHER") 86 self.assertEqual(fields["arch"], "all arm_xscale") 87 self.assertEqual(fields["release"], "OpenWrt") 88 self.assertEqual(fields["customer"], "OpenWrt") 89 self.assertEqual(fields["git"], "unknown") 90 91 def test_other_router_metadata(self): 92 self.run_tool("-c", "63138", "-m", "OTHER", "-a", "arm_cortex-a9", 93 "-r", "OpenWrt-test", "-u", "GNX", "-g", "0123456789") 94 fields = self.check_image(self.payload) 95 for key, value in dict(chip="63138", model="OTHER", arch="arm_cortex-a9", 96 release="OpenWrt-test", customer="GNX", 97 git="0123456789").items(): 98 self.assertEqual(fields[key], value) 99 100 def test_deterministic(self): 101 self.run_tool() 102 first = self.output.read_bytes() 103 self.run_tool(env=dict(os.environ, TZ="Pacific/Honolulu")) 104 self.assertEqual(first, self.output.read_bytes()) 105 106 def test_copy_boundaries(self): 107 for size in (64, 65535, 65536, 65537, 131072): 108 with self.subTest(size=size): 109 payload = self.payload[:size] 110 self.input.write_bytes(payload) 111 self.run_tool() 112 self.check_image(payload) 113 114 def test_size_limit_includes_header_and_checksum(self): 115 size = len(self.payload) + 1056 116 for limit in (str(size), hex(size), "0" + str(size)): 117 self.run_tool("-s", limit) 118 self.check_image(self.payload) 119 saved = self.output.read_bytes() 120 self.run_tool("-s", str(size - 1), success=False) 121 self.assertEqual(saved, self.output.read_bytes()) 122 123 def test_sparse_oversized_input(self): 124 for size in (0x03a20000, 2**32 + 64): 125 with self.input.open("r+b") as stream: 126 stream.truncate(size) 127 self.run_tool(success=False) 128 self.assertFalse(self.output.exists()) 129 130 def test_invalid_limits(self): 131 for limit in ("", "0", "1119", "-1", "+4096", " 4096", "0x", 132 "0x1000junk", "2147483648", "18446744073709551616"): 133 with self.subTest(limit=limit): 134 self.run_tool("-s", limit, success=False) 135 136 def test_invalid_chip_ids(self): 137 for chip in ("", "0x6846", "6846\ncfe 5", "123456789", "abcd"): 138 with self.subTest(chip=chip): 139 self.run_tool("-c", chip, success=False) 140 141 def test_metadata_injection_and_overflow(self): 142 self.output.write_bytes(b"old image") 143 for option in ("-m", "-a", "-r", "-u", "-g"): 144 for value in ("", "x\ncfe 1", "x\r", "x\t", "x\x7f", "\u00e5", "x" * 1024): 145 with self.subTest(option=option, value=value[:20]): 146 self.run_tool(option, value, success=False) 147 self.assertEqual(self.output.read_bytes(), b"old image") 148 149 def test_header_text_limit(self): 150 self.run_tool() 151 text = self.output.read_bytes()[:1024].split(b"\0", 1)[0] 152 release = "R" * (1004 - len(text) + len("OpenWrt")) 153 self.run_tool("-r", release) 154 self.check_image(self.payload) 155 saved = self.output.read_bytes() 156 self.run_tool("-r", release + "R", success=False) 157 self.assertEqual(self.output.read_bytes(), saved) 158 159 def test_invalid_inputs(self): 160 for payload in (b"", b"UBI#\x01", b"UBI#\x02" + bytes(59), bytes(128)): 161 self.input.write_bytes(payload) 162 self.run_tool(success=False) 163 self.run_tool("-i", str(self.directory / "absent"), success=False) 164 self.run_tool("-i", str(self.directory), success=False) 165 self.assertFalse(self.output.exists()) 166 167 def test_input_output_aliases(self): 168 self.run_tool("-o", str(self.input), success=False) 169 self.output.hardlink_to(self.input) 170 self.run_tool(success=False) 171 self.output.unlink() 172 self.output.symlink_to(self.input) 173 self.run_tool(success=False) 174 self.assertEqual(self.input.read_bytes(), self.payload) 175 176 def test_output_errors_leave_no_temporary(self): 177 self.output.mkdir() 178 self.run_tool(success=False) 179 self.assertTrue(self.output.is_dir()) 180 self.assertEqual(list(self.directory.glob("output.y3.*")), []) 181 self.run_tool("-o", str(self.directory / "missing" / "file"), success=False) 182 183 def test_write_failure_preserves_old_output(self): 184 def limit_output(): 185 signal.signal(signal.SIGXFSZ, signal.SIG_IGN) 186 resource.setrlimit(resource.RLIMIT_FSIZE, (1500, 1500)) 187 188 self.output.write_bytes(b"old image") 189 self.run_tool(success=False, preexec_fn=limit_output) 190 self.assertEqual(self.output.read_bytes(), b"old image") 191 self.assertEqual(list(self.directory.glob("output.y3.*")), []) 192 193 def test_output_permissions(self): 194 self.run_tool(preexec_fn=lambda: os.umask(0o027)) 195 self.assertEqual(self.output.stat().st_mode & 0o777, 0o640) 196 197 def test_vendor_payloads(self): 198 if not VENDORS: 199 self.skipTest("no optional --vendor images supplied") 200 for path in VENDORS: 201 with self.subTest(path=path): 202 vendor = path.read_bytes() 203 self.assertEqual(vendor[-32:], hashlib.md5(vendor[:-32]).hexdigest().encode()) 204 lines = vendor[:1024].split(b"\0", 1)[0].decode().splitlines() 205 self.assertEqual(lines.pop(0), "IntenoIopY") 206 tags = dict(line.split(" ", 1) for line in lines if line) 207 self.assertEqual(tags["version"], "8") 208 start, length = int(tags["ubiofs"]), int(tags["ubi"]) 209 payload = vendor[start:start + length] 210 self.assertEqual(len(payload), length) 211 self.input.write_bytes(payload) 212 self.run_tool("-c", tags["chip"], "-m", tags["model"], "-a", tags["arch"]) 213 self.check_image(payload) 214 215 216 if __name__ == "__main__": 217 parser = argparse.ArgumentParser(description=__doc__) 218 parser.add_argument("binary", type=Path) 219 parser.add_argument("--vendor", action="append", type=Path, default=[]) 220 args = parser.parse_args() 221 BINARY, VENDORS = args.binary.resolve(), args.vendor 222 unittest.main(argv=[__file__], verbosity=2)
This page was automatically generated by LXR 0.3.1. • OpenWrt