Plugins run only verified code. /JL
This commit was merged in pull request #6.
This commit is contained in:
1 parent
a91efef114
commit
aa5978ff92
6 files changed
+425
-35
No files matched your search
@@ -0,0 +1,252 @@
|
||||
"""
|
||||
tests/test_integrity.py — XtendR runs exactly the code it verified (0.5.4).
|
||||
|
||||
Real Ed25519 keys and whitelists, no mocks of the crypto. Covers:
|
||||
|
||||
- a signed plugin attaches, runs, and behaves like a normal module (__file__, dataclasses);
|
||||
- tampered, unsigned or re-pointed plugins (manifest naming another module/class) never execute;
|
||||
- a planted __pycache__/*.pyc with the signed source's header is ignored (it used to run);
|
||||
- files swapped on disk after verification can't change what runs (check-then-load race);
|
||||
- symlinked manifests/modules and oversized files are refused;
|
||||
- the digest is unchanged from 0.5.3, so existing whitelists stay valid;
|
||||
- private keys are created 0600 and whitelists are written atomically.
|
||||
|
||||
python3 -m pytest tests -v (or: python3 -m unittest discover tests)
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import py_compile
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from xtendr import signing as xs # noqa: E402
|
||||
from xtendr import xtendrsystem as xsys # noqa: E402
|
||||
from xtendr.xtendrsystem import SIG_INVALID, SIG_UNSIGNED, SIG_VERIFIED, XtendRSystem # noqa: E402
|
||||
|
||||
SOURCE = '''from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from xtendr.xtendrbase import XtendRBase
|
||||
|
||||
WHO = "{who}"
|
||||
HERE = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
@dataclass
|
||||
class Point:
|
||||
x: int = 1
|
||||
|
||||
|
||||
class {cls}(XtendRBase):
|
||||
def run(self, *args, **kwargs):
|
||||
return WHO
|
||||
def stop(self):
|
||||
pass
|
||||
def pre_load(self, callback=None):
|
||||
if callable(callback):
|
||||
callback()
|
||||
'''
|
||||
|
||||
|
||||
class IntegrityTest(unittest.TestCase):
|
||||
"""Attach behaviour around signatures."""
|
||||
|
||||
def setUp(self) -> None:
|
||||
"""A work folder with keys, a plugins/ folder and one signed plugin 'Demo'."""
|
||||
self._tmp = tempfile.TemporaryDirectory()
|
||||
self.work = Path(self._tmp.name)
|
||||
self._cwd = os.getcwd()
|
||||
os.chdir(self.work)
|
||||
self.addCleanup(os.chdir, self._cwd)
|
||||
xs.generate_keypair(self.work / "priv.pem", self.work / "pub.pem")
|
||||
self.private = xs.load_private_key(self.work / "priv.pem")
|
||||
self.whitelist = xs.Whitelist()
|
||||
self.plugin = self.make_plugin("Demo")
|
||||
|
||||
def tearDown(self) -> None:
|
||||
"""Forget loaded plugin modules and remove the folder."""
|
||||
for key in [k for k in sys.modules if k.startswith("xtendr_plugin_")]:
|
||||
del sys.modules[key]
|
||||
self._tmp.cleanup()
|
||||
|
||||
def make_plugin(self, name: str, who: str = "signed", sign: bool = True) -> Path:
|
||||
"""Write plugins/<name>/ and (optionally) sign it into the whitelist."""
|
||||
folder = self.work / "plugins" / name
|
||||
folder.mkdir(parents=True)
|
||||
(folder / f"{name}.json").write_text(json.dumps({"name": name, "module": name, "class": f"{name}Plugin"}))
|
||||
(folder / f"{name}.py").write_text(SOURCE.format(who=who, cls=f"{name}Plugin"))
|
||||
if sign:
|
||||
self.whitelist.add(xs.sign_plugin(self.private, folder))
|
||||
self.whitelist.save(self.work / "wl.json")
|
||||
return folder
|
||||
|
||||
def system(self) -> XtendRSystem:
|
||||
"""A system over plugins/ with the key and whitelist."""
|
||||
return XtendRSystem("plugins", public_key_path=str(self.work / "pub.pem"),
|
||||
whitelist_path=str(self.work / "wl.json"))
|
||||
|
||||
@staticmethod
|
||||
def loaded(system: XtendRSystem, name: str):
|
||||
"""The module object of an attached plugin, or None."""
|
||||
key = system.plugins[name]["module_key"]
|
||||
return sys.modules.get(key) if key else None
|
||||
|
||||
# ── Normal use ───────────────────────────────────────────────────────
|
||||
|
||||
def test_signed_plugin_runs_like_a_module(self) -> None:
|
||||
"""Verified, runs, __file__ points at the plugin, dataclasses work, the callback fires."""
|
||||
system = self.system()
|
||||
ready = []
|
||||
system.attach("Demo", lambda: ready.append(True))
|
||||
system.plugins["Demo"]["pre_load_thread"].join(5)
|
||||
self.assertEqual(system.plugins["Demo"]["signature"]["status"], SIG_VERIFIED)
|
||||
self.assertEqual(system.run("Demo"), "signed")
|
||||
module = self.loaded(system, "Demo")
|
||||
self.assertEqual(module.HERE, self.plugin.resolve())
|
||||
self.assertEqual(module.Point().x, 1)
|
||||
self.assertEqual(ready, [True])
|
||||
system.detach("Demo")
|
||||
self.assertNotIn("Demo", system.plugins)
|
||||
|
||||
def test_digest_unchanged(self) -> None:
|
||||
"""hash_plugin_bytes() equals hash_plugin_files(): 0.5.3 whitelists stay valid."""
|
||||
manifest = (self.plugin / "Demo.json").read_bytes()
|
||||
module = (self.plugin / "Demo.py").read_bytes()
|
||||
self.assertEqual(xs.hash_plugin_bytes("Demo", manifest, "Demo", module),
|
||||
xs.hash_plugin_files(self.plugin, "Demo", "Demo"))
|
||||
|
||||
def test_no_bytecode_written(self) -> None:
|
||||
"""Attaching leaves no __pycache__ in the plugin folder."""
|
||||
self.system().attach("Demo")
|
||||
self.assertFalse((self.plugin / "__pycache__").exists())
|
||||
|
||||
# ── Never executed ───────────────────────────────────────────────────
|
||||
|
||||
def test_tampered_module_never_runs(self) -> None:
|
||||
"""A changed module is SIG_INVALID and isn't executed."""
|
||||
(self.plugin / "Demo.py").write_text(SOURCE.format(who="EVIL", cls="DemoPlugin")
|
||||
+ "\nraise SystemExit('executed')\n")
|
||||
system = self.system()
|
||||
system.attach("Demo")
|
||||
self.assertEqual(system.plugins["Demo"]["signature"]["status"], SIG_INVALID)
|
||||
self.assertIsNone(self.loaded(system, "Demo"))
|
||||
|
||||
def test_unsigned_plugin_never_runs(self) -> None:
|
||||
"""No whitelist entry: SIG_UNSIGNED, not executed."""
|
||||
self.make_plugin("Other", sign=False)
|
||||
(self.work / "plugins" / "Other" / "Other.py").write_text("raise SystemExit('executed')\n")
|
||||
system = self.system()
|
||||
system.attach("Other")
|
||||
self.assertEqual(system.plugins["Other"]["signature"]["status"], SIG_UNSIGNED)
|
||||
|
||||
def test_manifest_repointed_to_unsigned_module(self) -> None:
|
||||
"""A manifest changed to load another (unsigned) module is refused."""
|
||||
(self.plugin / "Evil.py").write_text("raise SystemExit('executed')\n")
|
||||
(self.plugin / "Demo.json").write_text(json.dumps({"name": "Demo", "module": "Evil", "class": "DemoPlugin"}))
|
||||
system = self.system()
|
||||
system.attach("Demo")
|
||||
self.assertEqual(system.plugins["Demo"]["signature"]["status"], SIG_INVALID)
|
||||
|
||||
def test_planted_pyc_is_ignored(self) -> None:
|
||||
"""A .pyc with the signed source's mtime/size header (the 0.5.3 bypass) doesn't run."""
|
||||
evil = self.work / "evil.py"
|
||||
evil.write_text(SOURCE.format(who="EVIL", cls="DemoPlugin"))
|
||||
cache = Path(importlib.util.cache_from_source(str(self.plugin / "Demo.py")))
|
||||
cache.parent.mkdir()
|
||||
py_compile.compile(str(evil), cfile=str(cache))
|
||||
st = (self.plugin / "Demo.py").stat()
|
||||
data = bytearray(cache.read_bytes())
|
||||
data[8:16] = struct.pack("<II", int(st.st_mtime) & 0xFFFFFFFF, st.st_size & 0xFFFFFFFF)
|
||||
cache.write_bytes(bytes(data))
|
||||
system = self.system()
|
||||
system.attach("Demo")
|
||||
self.assertEqual(system.plugins["Demo"]["signature"]["status"], SIG_VERIFIED)
|
||||
self.assertEqual(self.loaded(system, "Demo").WHO, "signed")
|
||||
|
||||
def test_swap_after_verification_changes_nothing(self) -> None:
|
||||
"""Files replaced on disk right after the check: the verified bytes still run."""
|
||||
real = xs.verify_plugin_bytes
|
||||
|
||||
def verify_then_swap(*args, **kwargs):
|
||||
"""Verify, then let an 'attacker' replace module and manifest."""
|
||||
ok = real(*args, **kwargs)
|
||||
(self.plugin / "Demo.py").write_text(SOURCE.format(who="EVIL", cls="DemoPlugin"))
|
||||
(self.plugin / "Evil.py").write_text("raise SystemExit('executed')\n")
|
||||
(self.plugin / "Demo.json").write_text(json.dumps({"name": "Demo", "module": "Evil", "class": "X"}))
|
||||
return ok
|
||||
|
||||
with mock.patch.object(xs, "verify_plugin_bytes", verify_then_swap):
|
||||
system = self.system()
|
||||
system.attach("Demo")
|
||||
self.assertEqual(system.plugins["Demo"]["signature"]["status"], SIG_VERIFIED)
|
||||
self.assertEqual(system.run("Demo"), "signed")
|
||||
|
||||
def test_symlinks_refused(self) -> None:
|
||||
"""A symlinked module or manifest is never read (O_NOFOLLOW)."""
|
||||
for target in ("Demo.py", "Demo.json"):
|
||||
with self.subTest(target=target):
|
||||
path = self.plugin / target
|
||||
real = self.work / f"real-{target}"
|
||||
path.rename(real)
|
||||
path.symlink_to(real)
|
||||
system = self.system()
|
||||
system.attach("Demo")
|
||||
self.assertNotIn("Demo", system.plugins)
|
||||
path.unlink()
|
||||
real.rename(path)
|
||||
|
||||
def test_oversized_and_odd_manifests(self) -> None:
|
||||
"""Huge or non-object manifests are refused before anything else."""
|
||||
manifest = self.plugin / "Demo.json"
|
||||
for content in (b" " * (xsys.MAX_MANIFEST_BYTES + 1), b"[1, 2]", b"\xff\xfe"):
|
||||
with self.subTest(size=len(content)):
|
||||
manifest.write_bytes(content)
|
||||
system = self.system()
|
||||
system.attach("Demo")
|
||||
self.assertNotIn("Demo", system.plugins)
|
||||
|
||||
def test_reload_after_signing(self) -> None:
|
||||
"""An unsigned plugin signed afterwards loads on reload() (the Retry path)."""
|
||||
self.make_plugin("Late", sign=False)
|
||||
system = self.system()
|
||||
system.attach("Late")
|
||||
self.assertTrue(system.plugins["Late"]["disabled"])
|
||||
self.whitelist.add(xs.sign_plugin(self.private, self.work / "plugins" / "Late"))
|
||||
self.whitelist.save(self.work / "wl.json")
|
||||
self.assertTrue(system.reload("Late"))
|
||||
self.assertEqual(system.run("Late"), "signed")
|
||||
|
||||
|
||||
class FilesTest(unittest.TestCase):
|
||||
"""Key and whitelist files."""
|
||||
|
||||
def test_private_key_0600_and_atomic_whitelist(self) -> None:
|
||||
"""The private key is 0600 even over an existing 0644 file; whitelists keep their mode."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
folder = Path(tmp)
|
||||
priv = folder / "priv.pem"
|
||||
priv.write_text("old")
|
||||
priv.chmod(0o644)
|
||||
xs.generate_keypair(priv, folder / "pub.pem")
|
||||
self.assertEqual(priv.stat().st_mode & 0o777, 0o600)
|
||||
wl = xs.Whitelist()
|
||||
path = folder / "wl.json"
|
||||
wl.save(path)
|
||||
self.assertEqual(path.stat().st_mode & 0o777, 0o644)
|
||||
path.chmod(0o600)
|
||||
wl.save(path, passphrase="secret")
|
||||
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
|
||||
self.assertEqual(xs.Whitelist.load(path, "secret").entries, {})
|
||||
self.assertEqual(sorted(p.name for p in folder.iterdir()), ["priv.pem", "pub.pem", "wl.json"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user