1 parent
639362fbf5
commit
bdd69f0aad
101 files changed
+22691
-531
No files matched your search
@@ -0,0 +1,240 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate an Echoion release tree without executing payload binaries."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import stat
|
||||
import tempfile
|
||||
|
||||
|
||||
IMMUTABLE_ROOTS = ("bin", "lib", "service", "share")
|
||||
UNSAFE_WRITABLE_MODE = stat.S_IWGRP | stat.S_IWOTH
|
||||
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as source:
|
||||
for block in iter(lambda: source.read(1024 * 1024), b""):
|
||||
digest.update(block)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def reject_unsafe_writable_mode(path: Path, metadata: os.stat_result) -> None:
|
||||
if metadata.st_mode & UNSAFE_WRITABLE_MODE:
|
||||
raise ValueError(
|
||||
f"immutable payload path is group- or world-writable: {path}"
|
||||
)
|
||||
|
||||
|
||||
def safe_relative_path(value: object) -> PurePosixPath:
|
||||
if not isinstance(value, str):
|
||||
raise ValueError("manifest file entry has no string path")
|
||||
relative = PurePosixPath(value)
|
||||
if (
|
||||
relative.is_absolute()
|
||||
or not relative.parts
|
||||
or relative.as_posix() != value
|
||||
or any(component in ("", ".", "..") for component in value.split("/"))
|
||||
or relative.parts[0] not in IMMUTABLE_ROOTS
|
||||
):
|
||||
raise ValueError(f"unsafe manifest path: {value!r}")
|
||||
return relative
|
||||
|
||||
|
||||
def collect_actual_entries(root: Path) -> set[str]:
|
||||
root_metadata = root.lstat()
|
||||
if not stat.S_ISDIR(root_metadata.st_mode) or root.is_symlink():
|
||||
raise ValueError(f"immutable payload root is not a directory: {root}")
|
||||
reject_unsafe_writable_mode(root, root_metadata)
|
||||
|
||||
actual: set[str] = set()
|
||||
pending = [root / name for name in IMMUTABLE_ROOTS]
|
||||
for directory in pending:
|
||||
try:
|
||||
metadata = directory.lstat()
|
||||
except FileNotFoundError as error:
|
||||
raise ValueError(
|
||||
f"missing immutable payload directory: {directory}"
|
||||
) from error
|
||||
if not stat.S_ISDIR(metadata.st_mode) or directory.is_symlink():
|
||||
raise ValueError(f"missing immutable payload directory: {directory}")
|
||||
reject_unsafe_writable_mode(directory, metadata)
|
||||
|
||||
while pending:
|
||||
directory = pending.pop()
|
||||
with os.scandir(directory) as iterator:
|
||||
children = sorted(iterator, key=lambda item: item.name)
|
||||
for child in children:
|
||||
path = Path(child.path)
|
||||
relative = path.relative_to(root).as_posix()
|
||||
metadata = path.lstat()
|
||||
if stat.S_ISDIR(metadata.st_mode):
|
||||
if path.is_symlink():
|
||||
raise ValueError(f"directory symlink is not allowed: {path}")
|
||||
reject_unsafe_writable_mode(path, metadata)
|
||||
pending.append(path)
|
||||
elif stat.S_ISREG(metadata.st_mode):
|
||||
reject_unsafe_writable_mode(path, metadata)
|
||||
actual.add(relative)
|
||||
elif stat.S_ISLNK(metadata.st_mode):
|
||||
actual.add(relative)
|
||||
else:
|
||||
raise ValueError(f"unsupported special file in payload: {path}")
|
||||
return actual
|
||||
|
||||
|
||||
def load_and_validate(root: Path, expected_version: str | None = None) -> dict:
|
||||
manifest_path = root / "manifest.json"
|
||||
with manifest_path.open("r", encoding="utf-8") as stream:
|
||||
manifest = json.load(stream)
|
||||
if not isinstance(manifest, dict) or manifest.get("schemaVersion") != 2:
|
||||
raise ValueError("release manifest must use schemaVersion 2")
|
||||
version = manifest.get("version")
|
||||
if not isinstance(version, str) or not version:
|
||||
raise ValueError("release manifest has no version")
|
||||
if expected_version is not None and version != expected_version:
|
||||
raise ValueError(
|
||||
f"release version mismatch: expected {expected_version!r}, got {version!r}"
|
||||
)
|
||||
|
||||
entries = manifest.get("files")
|
||||
if not isinstance(entries, list):
|
||||
raise ValueError("release manifest files must be an array")
|
||||
actual = collect_actual_entries(root)
|
||||
seen: set[str] = set()
|
||||
entry_types: dict[str, str] = {}
|
||||
for entry in entries:
|
||||
if not isinstance(entry, dict):
|
||||
raise ValueError("invalid release manifest file entry")
|
||||
relative = safe_relative_path(entry.get("path"))
|
||||
relative_text = relative.as_posix()
|
||||
if relative_text in seen:
|
||||
raise ValueError(f"duplicate manifest path: {relative_text}")
|
||||
seen.add(relative_text)
|
||||
path = root.joinpath(*relative.parts)
|
||||
try:
|
||||
metadata = path.lstat()
|
||||
except FileNotFoundError as error:
|
||||
raise ValueError(f"manifest entry is missing: {relative_text}") from error
|
||||
|
||||
entry_type = entry.get("type")
|
||||
if entry_type == "file":
|
||||
if not stat.S_ISREG(metadata.st_mode):
|
||||
raise ValueError(f"manifest regular file is missing: {relative_text}")
|
||||
reject_unsafe_writable_mode(path, metadata)
|
||||
if metadata.st_size != entry.get("size") or sha256(path) != entry.get(
|
||||
"sha256"
|
||||
):
|
||||
raise ValueError(f"manifest file verification failed: {relative_text}")
|
||||
mode = f"{stat.S_IMODE(metadata.st_mode):04o}"
|
||||
if mode != entry.get("mode"):
|
||||
raise ValueError(f"manifest mode verification failed: {relative_text}")
|
||||
elif entry_type == "symlink":
|
||||
if not stat.S_ISLNK(metadata.st_mode):
|
||||
raise ValueError(f"manifest symlink is missing: {relative_text}")
|
||||
target = entry.get("target")
|
||||
if not isinstance(target, str):
|
||||
raise ValueError(f"invalid manifest symlink target: {relative_text}")
|
||||
target_path = PurePosixPath(target)
|
||||
if (
|
||||
not target
|
||||
or target_path.is_absolute()
|
||||
or any(component in ("", ".", "..") for component in target.split("/"))
|
||||
or os.readlink(path) != target
|
||||
):
|
||||
raise ValueError(f"unsafe manifest symlink target: {relative_text}")
|
||||
try:
|
||||
path.resolve(strict=True).relative_to(root)
|
||||
except (FileNotFoundError, RuntimeError, ValueError) as error:
|
||||
raise ValueError(
|
||||
f"manifest symlink escapes release root: {relative_text}"
|
||||
) from error
|
||||
else:
|
||||
raise ValueError(f"invalid manifest entry type: {entry_type!r}")
|
||||
entry_types[relative_text] = entry_type
|
||||
|
||||
if seen != actual:
|
||||
details = []
|
||||
if undeclared := sorted(actual - seen):
|
||||
details.append("undeclared=" + ",".join(undeclared))
|
||||
if missing := sorted(seen - actual):
|
||||
details.append("missing=" + ",".join(missing))
|
||||
raise ValueError("immutable payload coverage mismatch: " + "; ".join(details))
|
||||
|
||||
required = {
|
||||
"executable": "bin/echoiond",
|
||||
"updater": "bin/echoion-updater",
|
||||
"core": "lib/Echoion.ts",
|
||||
"web dashboard": "share/echoion/web/index.html",
|
||||
"configuration template": "share/echoion/config.example.json",
|
||||
"manifest validator": "share/echoion/tools/validate-release-manifest.py",
|
||||
"service template": "service/echoion.service.in",
|
||||
"updater service template": "service/echoion-updater.service.in",
|
||||
"updater timer template": "service/echoion-updater.timer.in",
|
||||
}
|
||||
if manifest.get("executable") != required["executable"]:
|
||||
raise ValueError("manifest executable has a non-canonical path")
|
||||
if manifest.get("updater") != required["updater"]:
|
||||
raise ValueError("manifest updater has a non-canonical path")
|
||||
if manifest.get("core") != required["core"]:
|
||||
raise ValueError("manifest core has a non-canonical path")
|
||||
for description, path in required.items():
|
||||
if entry_types.get(path) != "file":
|
||||
raise ValueError(f"manifest {description} is not declared as a file")
|
||||
for description in ("executable", "updater"):
|
||||
executable = root / required[description]
|
||||
if stat.S_IMODE(executable.stat().st_mode) & 0o111 == 0:
|
||||
raise ValueError(f"manifest {description} is not executable")
|
||||
return manifest
|
||||
|
||||
|
||||
def write_pending(manifest: dict, version: str, output: Path) -> None:
|
||||
prefix = f"{version}/"
|
||||
pending = dict(manifest)
|
||||
pending["executable"] = prefix + str(manifest["executable"])
|
||||
pending["updater"] = prefix + str(manifest["updater"])
|
||||
pending["core"] = prefix + str(manifest["core"])
|
||||
pending["files"] = [
|
||||
dict(entry, path=prefix + str(entry["path"])) for entry in manifest["files"]
|
||||
]
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
descriptor, temporary_name = tempfile.mkstemp(
|
||||
prefix=f".{output.name}.", dir=output.parent
|
||||
)
|
||||
try:
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream:
|
||||
json.dump(pending, stream, ensure_ascii=False, indent=2)
|
||||
stream.write("\n")
|
||||
os.chmod(temporary_name, 0o644)
|
||||
os.replace(temporary_name, output)
|
||||
except BaseException:
|
||||
try:
|
||||
os.unlink(temporary_name)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--root", required=True, type=Path)
|
||||
parser.add_argument("--version")
|
||||
parser.add_argument("--pending-output", type=Path)
|
||||
arguments = parser.parse_args()
|
||||
try:
|
||||
root = arguments.root.resolve(strict=True)
|
||||
manifest = load_and_validate(root, arguments.version)
|
||||
if arguments.pending_output is not None:
|
||||
write_pending(manifest, str(manifest["version"]), arguments.pending_output)
|
||||
except (OSError, ValueError, json.JSONDecodeError) as error:
|
||||
parser.error(str(error))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user