Repository navigation
Expand file tree
/
Copy pathmake-rootfs.py
More file actions
253 lines (233 loc) · 12.5 KB
/
Copy pathmake-rootfs.py
File metadata and controls
253 lines (233 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
"""Assemble an auditable Debian library subset; preserve metadata for every copied component."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import stat
import subprocess
BASE = Path("/rootfs")
TEST = Path("/test-rootfs")
PREFIX = "/opt/php-cve/"
STORE = "/usr/local/share/php-cve/build"
def sha(path: Path) -> str:
value = hashlib.sha256()
with path.open("rb") as stream:
for data in iter(lambda: stream.read(1024 * 1024), b""):
value.update(data)
return value.hexdigest()
class Assembler:
def __init__(self, root: Path, records: dict | None = None) -> None:
self.root = root
self.files: dict = records or {}
self.visited: set[str] = set()
self.native = json.loads(Path("/native-evidence/components.json").read_text())["components"]
self.native_owners = {f["path"]: item["package"] for item in self.native
for f in item["installed_files"]}
def owner(self, path: Path) -> list[str]:
candidates = [str(path), str(path.resolve(strict=True))]
for candidate in candidates:
if candidate in self.native_owners:
return [self.native_owners[candidate]]
attempts = list(candidates)
for candidate in candidates:
for directory in ("lib", "lib64", "bin", "sbin"):
if candidate.startswith("/usr/" + directory + "/"):
attempts.append(candidate[4:])
elif candidate.startswith("/" + directory + "/"):
attempts.append("/usr" + candidate)
attempts = list(dict.fromkeys(attempts))
for attempt in attempts:
result = subprocess.run(["dpkg-query", "-S", attempt], capture_output=True,
text=True, timeout=15)
if result.returncode == 0:
owners = {name.strip() for line in result.stdout.splitlines() if ": " in line
for name in line.rsplit(": ", 1)[0].split(",")}
owners = {name for name in owners
if re.fullmatch(r"[a-z0-9][a-z0-9+.-]*(?::[a-z0-9]+)?", name)}
if owners:
return sorted(owners)
if str(path).startswith(("/runtime/", "/work/")):
return ["php-cve-project"]
return []
def copy(self, source: Path, target: str | None = None) -> None:
if not source.is_absolute() or ".." in source.parts:
raise ValueError("Unbounded source path")
target = target or str(source)
if not target.startswith("/") or ".." in Path(target).parts:
raise ValueError("Unbounded destination path")
key = str(source) + ":" + target
if key in self.visited:
return
self.visited.add(key)
destination = self.root / target.lstrip("/")
if source.is_dir() and not source.is_symlink():
destination.mkdir(parents=True, exist_ok=True)
for item in sorted(source.iterdir()):
self.copy(item, target.rstrip("/") + "/" + item.name)
return
if not source.exists():
raise FileNotFoundError(source)
destination.parent.mkdir(parents=True, exist_ok=True)
if source.is_symlink():
link = os.readlink(source)
if destination.is_symlink():
if os.readlink(destination) != link:
raise RuntimeError("Test tool would replace runtime symlink: " + target)
elif destination.exists():
raise RuntimeError("Destination type conflict: " + target)
else:
destination.symlink_to(link)
# Preserve intermediate links too (for example zoneinfo/localtime -> /etc/localtime).
linked = Path(link) if link.startswith("/") else source.parent / link
self.copy(Path(os.path.normpath(str(linked))))
resolved = source.resolve(strict=True)
checksum = sha(resolved) if resolved.is_file() else None
else:
checksum = sha(source)
if destination.exists():
if sha(destination) != checksum:
raise RuntimeError("Test tool would replace runtime bytes: " + target)
else:
shutil.copy2(source, destination)
destination.chmod(stat.S_IMODE(source.stat().st_mode) & ~0o6000)
with source.open("rb") as stream:
elf = stream.read(4) == b"\x7fELF"
if elf:
if not self.owner(source):
raise RuntimeError("ELF component has no inventory owner: " + str(source))
result = subprocess.run(["ldd", str(source)], capture_output=True, text=True, timeout=30)
if "not found" in result.stdout:
raise RuntimeError("Unresolved ELF dependency: " + result.stdout)
if result.returncode and "not a dynamic executable" not in result.stderr + result.stdout:
raise RuntimeError("ELF inspection failed: " + result.stderr)
for line in result.stdout.splitlines():
match = re.search(r"=>\s+(/[^\s]+)", line) or re.match(r"\s*(/[^\s]+)\s+\(", line)
if match:
self.copy(Path(match.group(1)))
self.files[target] = {"source": str(source), "sha256": checksum,
"owners": self.owner(source),
"symlink": os.readlink(source) if source.is_symlink() else None}
def metadata(self) -> None:
directory = self.root / STORE.lstrip("/")
directory.mkdir(parents=True, exist_ok=True)
(directory / "runtime-files.json").write_text(json.dumps(self.files, indent=2) + "\n")
shipped_native = []
for item in self.native:
record = {key: value for key, value in item.items() if key != "installed_files"}
record["runtime_files"] = [{"path": path, "sha256": file["sha256"]}
for path, file in self.files.items() if item["package"] in file["owners"]]
shipped_native.append(record)
(directory / "native-components.json").write_text(json.dumps({"components": shipped_native}, indent=2) + "\n")
(directory / "native-source-lock.json").write_bytes(Path("/native-evidence/source-lock.json").read_bytes())
packages = sorted({p for entry in self.files.values() for p in entry["owners"]
if p != "php-cve-project"})
status_entries = []
package_lines = []
native = {item["package"]: item for item in self.native}
for package in packages:
if package in native:
component = native[package]
entry = ("Package: " + package + "\nStatus: install ok installed\n"
"Architecture: amd64\nVersion: " + component["version"] + "+local1\n"
"Source: " + component["source_package"] + " (" + component["version"] + ")\n"
"Description: PHP-CVE source-built native component; see native-source-lock.json\n")
version = component["version"] + "+local1"
else:
entry = subprocess.run(["dpkg-query", "--status", package], check=True, capture_output=True,
text=True, timeout=15).stdout
version = subprocess.run(["dpkg-query", "-W", "-f=" + "$" + "{Version}", package],
check=True, capture_output=True, text=True, timeout=15).stdout
status_entries.append(entry.strip())
package_lines.append(package + "=" + version)
info = self.root / "var/lib/dpkg/info"
info.mkdir(parents=True, exist_ok=True)
paths = sorted(path for path, record in self.files.items() if package in record["owners"])
(info / (package + ".list")).write_text("\n".join(paths) + "\n")
status_path = self.root / "var/lib/dpkg/status"
status_path.parent.mkdir(parents=True, exist_ok=True)
status_path.write_text("\n\n".join(status_entries) + "\n")
(directory / "runtime-packages.txt").write_text("\n".join(package_lines) + "\n")
# Include redistribution notices for every copied Debian component.
for package in packages:
if package not in native:
license_path = Path("/usr/share/doc") / package.split(":")[0] / "copyright"
if license_path.is_file():
output = self.root / "usr/local/share/php-cve/licenses/debian" / package
output.mkdir(parents=True, exist_ok=True)
shutil.copy2(license_path, output / "copyright")
def layout(root: Path) -> None:
root.mkdir()
for name in ("bin", "sbin", "lib", "lib64"):
(root / "usr" / name).mkdir(parents=True, exist_ok=True)
(root / name).symlink_to("usr/" + name)
(root / "etc").mkdir()
(root / "etc/passwd").write_text("root:x:0:0:root:/root:/bin/sh\nphp:x:10001:10001:PHP:/app:/bin/sh\n")
(root / "etc/group").write_text("root:x:0:\nphp:x:10001:\n")
(root / "etc/nsswitch.conf").write_text("passwd: files\ngroup: files\nhosts: files dns\n")
(root / "tmp").mkdir(mode=0o1777)
(root / "tmp").chmod(0o1777)
(root / "app").mkdir()
os.chown(root / "app", 10001, 10001)
def loader_cache(root: Path) -> None:
(root / "etc/ld.so.conf").write_text("/opt/php-cve/lib\n/usr/lib/x86_64-linux-gnu\n")
subprocess.run(["ldconfig", "-r", str(root)], check=True, timeout=30)
def runtime() -> None:
layout(BASE)
assembly = Assembler(BASE)
assembly.copy(Path("/runtime"), "/")
for executable in ("/bin/sh", "/usr/bin/mkdir", "/usr/bin/grep", "/usr/bin/tr",
"/usr/bin/env", "/usr/bin/id", "/usr/bin/cgi-fcgi"):
assembly.copy(Path(executable))
for path in ("/etc/os-release", "/etc/debian_version", "/etc/ssl/certs",
"/etc/ssl/openssl.cnf", "/usr/share/ca-certificates", "/usr/share/zoneinfo",
"/usr/share/common-licenses"):
assembly.copy(Path(path))
for path in ("/usr/lib/x86_64-linux-gnu/libnss_dns.so.2",
"/usr/lib/x86_64-linux-gnu/libnss_files.so.2",
"/opt/php-cve/lib/ossl-modules",
"/usr/lib/x86_64-linux-gnu/sasl2",
"/usr/lib/x86_64-linux-gnu/krb5/plugins",
"/usr/lib/ssl/cert.pem", "/usr/lib/ssl/certs", "/usr/lib/ssl/openssl.cnf",
"/etc/services", "/etc/protocols", "/etc/krb5.conf", "/etc/ldap/ldap.conf"):
if Path(path).exists():
assembly.copy(Path(path))
for component in assembly.native:
assembly.copy(Path(PREFIX) / "share/licenses" / component["name"])
for name in ("entrypoint.sh", "healthcheck.sh"):
assembly.copy(Path("/work/scripts") / name, "/usr/local/bin/" + name)
(BASE / "usr/local/bin" / name).chmod(0o755)
for name, target in (("php.ini", "/usr/local/etc/php/php.ini"),
("php-fpm.conf", "/usr/local/etc/php-fpm.conf")):
assembly.copy(Path("/work/config") / name, target)
(BASE / "usr/local/etc/php/conf.d").mkdir(parents=True, exist_ok=True)
assembly.metadata()
loader_cache(BASE)
def tests() -> None:
shutil.copytree(BASE, TEST, symlinks=True)
records = json.loads((BASE / STORE.lstrip("/") / "runtime-files.json").read_text())
assembly = Assembler(TEST, dict(records))
for path in ("/usr/bin/python3", "/usr/lib/python3.11"):
assembly.copy(Path(path))
assembly.copy(Path('/opt/php-cve/bin/openssl'), '/usr/bin/openssl')
assembly.metadata()
loader_cache(TEST)
# Export a complete test root in one layer. Verify every runtime file survives unchanged.
for path, record in records.items():
original, tested = BASE / path.lstrip("/"), TEST / path.lstrip("/")
if record["sha256"] is not None and sha(original) != sha(tested):
raise RuntimeError("Test root differs from runtime: " + path)
for source, target in (("/usr/bin/python3.11", "/usr/bin/python3.11"),
("/opt/php-cve/bin/openssl", "/usr/bin/openssl")):
if sha(Path(source)) != sha(TEST / target.lstrip("/")):
raise RuntimeError("Incomplete test tool: " + source)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("mode", choices=["runtime", "test"])
args = parser.parse_args()
(runtime if args.mode == "runtime" else tests)()
if __name__ == "__main__":
main()