Plugins run only verified code. /JL

This commit was merged in pull request #6.
This commit is contained in:
Lerking committed 2026-11-22 21:55:15 +01:00
1 parent a91efef114
commit aa5978ff92
6 files changed
+425 -35

No files matched your search

+60 -12
View File
@@ -18,6 +18,10 @@ Design:
for confidentiality only -- the signature is what provides integrity,
and still verifies correctly whether or not the file on disk is
encrypted.
- 0.5.4: hash_plugin_bytes()/verify_plugin_bytes() check bytes already in
memory, so XtendRSystem can verify exactly the bytes it then executes
(no second read from disk, no bytecode cache). The digest is the same as
hash_plugin_files() gives, so existing whitelists stay valid.
"""
from __future__ import annotations
@@ -25,6 +29,7 @@ import base64
import hashlib
import json
import os
import tempfile
from dataclasses import dataclass, asdict
from datetime import datetime, timezone
from pathlib import Path
@@ -67,9 +72,12 @@ def generate_keypair(private_path: Path, public_path: Path) -> None:
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
private_path.write_bytes(priv_bytes)
# Created 0600 from the start: no moment where the key is readable by others.
fd = os.open(private_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "wb") as out:
out.write(priv_bytes)
try:
os.chmod(private_path, 0o600)
os.chmod(private_path, 0o600) # an existing file keeps its mode on O_TRUNC
except OSError:
pass
public_path.write_bytes(pub_bytes)
@@ -115,6 +123,21 @@ class PluginEntry:
return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
def hash_plugin_bytes(name: str, manifest_bytes: bytes, module: str, module_bytes: bytes) -> str:
"""Hash manifest + module contents that are already in memory.
Same digest as hash_plugin_files() for the same contents: each part is
its file name, NUL, its bytes, NUL, manifest first.
"""
h = hashlib.sha256()
for filename, data in ((f"{name}.json", manifest_bytes), (f"{module}.py", module_bytes)):
h.update(filename.encode("utf-8"))
h.update(b"\x00")
h.update(data)
h.update(b"\x00")
return h.hexdigest()
def hash_plugin_files(plugin_dir: Path, name: str, module: str) -> str:
"""Hash the manifest + module file together, in a fixed order, so the
hash changes if either file is tampered with."""
@@ -124,14 +147,7 @@ def hash_plugin_files(plugin_dir: Path, name: str, module: str) -> str:
raise FileNotFoundError(f"Manifest not found: {manifest_path}")
if not module_path.is_file():
raise FileNotFoundError(f"Module file not found: {module_path}")
h = hashlib.sha256()
for p in (manifest_path, module_path):
h.update(p.name.encode("utf-8"))
h.update(b"\x00")
h.update(p.read_bytes())
h.update(b"\x00")
return h.hexdigest()
return hash_plugin_bytes(name, manifest_path.read_bytes(), module, module_path.read_bytes())
def sign_plugin(private_key: Ed25519PrivateKey, plugin_dir: Path) -> PluginEntry:
@@ -168,6 +184,16 @@ def verify_entry(public_key: Ed25519PublicKey, entry: PluginEntry) -> bool:
return False
def verify_plugin_bytes(public_key: Ed25519PublicKey, entry: PluginEntry,
manifest_bytes: bytes, module_bytes: bytes) -> bool:
"""Full verification of contents in memory: the entry's signature is
valid AND these exact bytes hash to the signed digest. Whoever then
executes `module_bytes` runs precisely what was verified."""
if not verify_entry(public_key, entry):
return False
return hash_plugin_bytes(entry.name, manifest_bytes, entry.module, module_bytes) == entry.sha256
def verify_plugin_on_disk(public_key: Ed25519PublicKey, plugin_dir: Path, entry: PluginEntry) -> bool:
"""Full verification: signature is valid AND the files on disk still
match the hash that was signed."""
@@ -211,7 +237,7 @@ class Whitelist:
def save(self, path: Path, passphrase: Optional[str] = None) -> None:
plaintext = self.to_json().encode("utf-8")
if passphrase is None:
path.write_bytes(plaintext)
_atomic_write(path, plaintext)
return
salt = os.urandom(16)
@@ -224,7 +250,7 @@ class Whitelist:
"salt": base64.b64encode(salt).decode("ascii"),
"data": base64.b64encode(token).decode("ascii"),
}
path.write_text(json.dumps(container, indent=2), encoding="utf-8")
_atomic_write(path, json.dumps(container, indent=2).encode("utf-8"))
@classmethod
def load(cls, path: Path, passphrase: Optional[str] = None) -> "Whitelist":
@@ -249,6 +275,28 @@ class Whitelist:
return cls.from_json(raw)
def _atomic_write(path: Path, data: bytes) -> None:
"""Write `data` to `path` via a temp file + fsync + rename, keeping the
file's permissions (0644 for a new file). A crash never leaves half a
whitelist behind."""
path = Path(path)
mode = path.stat().st_mode & 0o777 if path.exists() else 0o644
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
try:
with os.fdopen(fd, "wb") as out:
out.write(data)
out.flush()
os.fsync(out.fileno())
os.chmod(tmp, mode)
os.replace(tmp, path)
except BaseException:
try:
os.unlink(tmp)
except FileNotFoundError:
pass
raise
def _derive_key(passphrase: str, salt: bytes, iterations: int = PBKDF2_ITERATIONS) -> bytes:
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),