Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa5978ff92 | ||
|
|
a91efef114 | ||
|
|
818cd44b3d | ||
|
|
c6b91303ad | ||
|
|
ad67becd91 |
No files matched your search
@@ -1,5 +1,5 @@
|
|||||||
# XtendR
|
# XtendR
|
||||||

|

|
||||||
|
|
||||||
A very basic Python 3.12 friendly plugin system based on the K.I.S.S principle.
|
A very basic Python 3.12 friendly plugin system based on the K.I.S.S principle.
|
||||||
|
|
||||||
@@ -30,3 +30,35 @@ The system expects a folder called 'plugins', placed at the root, along side you
|
|||||||
Each plugin should be placed in subfolders, named as the plugin, inside the 'plugins' folder.
|
Each plugin should be placed in subfolders, named as the plugin, inside the 'plugins' folder.
|
||||||
|
|
||||||
The example.py along with the plugins/example_plugin/example_plugin.py and plugins/example_plugin/example_plugin.json shows the workings of this plugin system.
|
The example.py along with the plugins/example_plugin/example_plugin.py and plugins/example_plugin/example_plugin.json shows the workings of this plugin system.
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
Plugins are Python code that runs with the host's full rights, so XtendR only runs a plugin whose
|
||||||
|
manifest (`<name>.json`) and module (`<module>.py`) match an Ed25519-signed whitelist entry.
|
||||||
|
Unsigned or tampered plugins are listed but never executed. Since 0.5.4 XtendR reads each file
|
||||||
|
exactly once, checks the signature over those bytes and runs those same bytes: no second read from
|
||||||
|
disk, no `__pycache__` bytecode, no symlinked files.
|
||||||
|
|
||||||
|
Signing proves a plugin is unchanged since it was signed, not that it is safe. Keep the private key
|
||||||
|
off shared machines and pin the public key in the host application.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
python3 -m pytest tests -v
|
||||||
|
|
||||||
|
## Changes
|
||||||
|
|
||||||
|
- **0.5.4** — Plugins run exactly the code that was verified.
|
||||||
|
- *Fixed:* a `__pycache__/<module>.cpython-*.pyc` carrying the signed source's mtime and size
|
||||||
|
ran instead of the verified `.py` (the import machinery preferred the cache). `attach()` now
|
||||||
|
compiles and executes the verified bytes itself and never consults or writes bytecode.
|
||||||
|
- *Fixed:* files were read once to verify and again to import, and the manifest was parsed
|
||||||
|
before it was hashed. A file swapped in between could run unverified code or point the import
|
||||||
|
at another module. Each file is now read once (`O_NOFOLLOW`, regular files only, size-capped),
|
||||||
|
and the manifest's `module`/`class` must equal the signed entry's.
|
||||||
|
- New `signing.hash_plugin_bytes()` and `verify_plugin_bytes()`; the digest is unchanged, so
|
||||||
|
existing whitelists stay valid. `generate_keypair()` creates the private key 0600 from the
|
||||||
|
start; `Whitelist.save()` writes atomically and keeps the file's permissions.
|
||||||
|
- `setup.py` declares `cryptography>=42`; `__version__` reports 0.5.4 (was a stale 0.5.1).
|
||||||
|
- New `tests/test_integrity.py` (real keys; fails on 0.5.3 for the bypasses above). The
|
||||||
|
`XtendRBase` doctest example implements `pre_load` so it runs again.
|
||||||
@@ -37,3 +37,6 @@ class ExamplePlugin(XtendRBase):
|
|||||||
def pre_load(self, callback):
|
def pre_load(self, callback):
|
||||||
time.sleep(5) # Indicate long running pre-load.
|
time.sleep(5) # Indicate long running pre-load.
|
||||||
callback()
|
callback()
|
||||||
|
|
||||||
|
def unload(self):
|
||||||
|
print("ExamplePlugin has unloaded!") # release signal handlers, timers, widgets, etc. here
|
||||||
@@ -6,9 +6,9 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
setup(
|
setup(
|
||||||
name="XtendR",
|
name="XtendR",
|
||||||
version="0.5.0",
|
version="0.5.4",
|
||||||
packages=find_packages(),
|
packages=find_packages(),
|
||||||
install_requires=[],
|
install_requires=["cryptography>=42"],
|
||||||
author="Jan Lerking",
|
author="Jan Lerking",
|
||||||
author_email="",
|
author_email="",
|
||||||
description="A modular plugin system for Python.",
|
description="A modular plugin system for Python.",
|
||||||
|
|||||||
@@ -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()
|
||||||
+60
-12
@@ -18,6 +18,10 @@ Design:
|
|||||||
for confidentiality only -- the signature is what provides integrity,
|
for confidentiality only -- the signature is what provides integrity,
|
||||||
and still verifies correctly whether or not the file on disk is
|
and still verifies correctly whether or not the file on disk is
|
||||||
encrypted.
|
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
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -25,6 +29,7 @@ import base64
|
|||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import tempfile
|
||||||
from dataclasses import dataclass, asdict
|
from dataclasses import dataclass, asdict
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -67,9 +72,12 @@ def generate_keypair(private_path: Path, public_path: Path) -> None:
|
|||||||
format=serialization.PublicFormat.SubjectPublicKeyInfo,
|
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:
|
try:
|
||||||
os.chmod(private_path, 0o600)
|
os.chmod(private_path, 0o600) # an existing file keeps its mode on O_TRUNC
|
||||||
except OSError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
public_path.write_bytes(pub_bytes)
|
public_path.write_bytes(pub_bytes)
|
||||||
@@ -115,6 +123,21 @@ class PluginEntry:
|
|||||||
return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
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:
|
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 the manifest + module file together, in a fixed order, so the
|
||||||
hash changes if either file is tampered with."""
|
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}")
|
raise FileNotFoundError(f"Manifest not found: {manifest_path}")
|
||||||
if not module_path.is_file():
|
if not module_path.is_file():
|
||||||
raise FileNotFoundError(f"Module file not found: {module_path}")
|
raise FileNotFoundError(f"Module file not found: {module_path}")
|
||||||
|
return hash_plugin_bytes(name, manifest_path.read_bytes(), module, module_path.read_bytes())
|
||||||
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()
|
|
||||||
|
|
||||||
|
|
||||||
def sign_plugin(private_key: Ed25519PrivateKey, plugin_dir: Path) -> PluginEntry:
|
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
|
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:
|
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
|
"""Full verification: signature is valid AND the files on disk still
|
||||||
match the hash that was signed."""
|
match the hash that was signed."""
|
||||||
@@ -211,7 +237,7 @@ class Whitelist:
|
|||||||
def save(self, path: Path, passphrase: Optional[str] = None) -> None:
|
def save(self, path: Path, passphrase: Optional[str] = None) -> None:
|
||||||
plaintext = self.to_json().encode("utf-8")
|
plaintext = self.to_json().encode("utf-8")
|
||||||
if passphrase is None:
|
if passphrase is None:
|
||||||
path.write_bytes(plaintext)
|
_atomic_write(path, plaintext)
|
||||||
return
|
return
|
||||||
|
|
||||||
salt = os.urandom(16)
|
salt = os.urandom(16)
|
||||||
@@ -224,7 +250,7 @@ class Whitelist:
|
|||||||
"salt": base64.b64encode(salt).decode("ascii"),
|
"salt": base64.b64encode(salt).decode("ascii"),
|
||||||
"data": base64.b64encode(token).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
|
@classmethod
|
||||||
def load(cls, path: Path, passphrase: Optional[str] = None) -> "Whitelist":
|
def load(cls, path: Path, passphrase: Optional[str] = None) -> "Whitelist":
|
||||||
@@ -249,6 +275,28 @@ class Whitelist:
|
|||||||
return cls.from_json(raw)
|
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:
|
def _derive_key(passphrase: str, salt: bytes, iterations: int = PBKDF2_ITERATIONS) -> bytes:
|
||||||
kdf = PBKDF2HMAC(
|
kdf = PBKDF2HMAC(
|
||||||
algorithm=hashes.SHA256(),
|
algorithm=hashes.SHA256(),
|
||||||
|
|||||||
@@ -3,18 +3,44 @@ from abc import ABC, abstractmethod
|
|||||||
class XtendRBase(ABC):
|
class XtendRBase(ABC):
|
||||||
"""Abstract base class for all plugins.
|
"""Abstract base class for all plugins.
|
||||||
|
|
||||||
|
Lifecycle: pre_load() -> run() -> stop() -> unload(). XtendRSystem calls
|
||||||
|
unload() exactly once, right before it drops its own references to the
|
||||||
|
plugin instance and removes its module from sys.modules. This is the
|
||||||
|
plugin's only chance to release anything it holds that XtendRSystem
|
||||||
|
doesn't know about and can't clean up on its own, for example:
|
||||||
|
|
||||||
|
- GObject/GTK signal handler ids from .connect() (disconnect them, or
|
||||||
|
the GObject side keeps a reference to the bound method, which keeps
|
||||||
|
the plugin instance -- and everything it references -- alive).
|
||||||
|
- Widgets the plugin inserted into the app's widget tree (remove them
|
||||||
|
from their parent; a parented widget is kept alive by GTK regardless
|
||||||
|
of what Python does with its own references).
|
||||||
|
- GLib.timeout_add / idle_add source ids (GLib.source_remove them).
|
||||||
|
- Any threads it started that aren't daemon threads, or open files/
|
||||||
|
sockets/subprocesses.
|
||||||
|
|
||||||
|
unload() has a default no-op implementation so existing plugins that
|
||||||
|
don't hold any such resources keep working unchanged; override it only
|
||||||
|
when there's something to release.
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
>>> class TestPlugin(XtendRBase):
|
>>> class TestPlugin(XtendRBase):
|
||||||
... def run(self):
|
... def run(self):
|
||||||
... print("Running TestPlugin")
|
... print("Running TestPlugin")
|
||||||
... def stop(self):
|
... def stop(self):
|
||||||
... print("Stopping TestPlugin")
|
... print("Stopping TestPlugin")
|
||||||
|
... def pre_load(self, *args):
|
||||||
|
... pass
|
||||||
|
... def unload(self):
|
||||||
|
... print("Unloading TestPlugin")
|
||||||
|
|
||||||
>>> plugin = TestPlugin()
|
>>> plugin = TestPlugin()
|
||||||
>>> plugin.run()
|
>>> plugin.run()
|
||||||
Running TestPlugin
|
Running TestPlugin
|
||||||
>>> plugin.stop()
|
>>> plugin.stop()
|
||||||
Stopping TestPlugin
|
Stopping TestPlugin
|
||||||
|
>>> plugin.unload()
|
||||||
|
Unloading TestPlugin
|
||||||
"""
|
"""
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def run(self, *args, **kwargs):
|
def run(self, *args, **kwargs):
|
||||||
@@ -28,3 +54,8 @@ class XtendRBase(ABC):
|
|||||||
def pre_load(self, *args):
|
def pre_load(self, *args):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
def unload(self):
|
||||||
|
"""Release any resources the plugin holds. Called once by
|
||||||
|
XtendRSystem.detach(), after stop(). Optional to override;
|
||||||
|
default is a no-op."""
|
||||||
|
pass
|
||||||
+260
-52
@@ -1,4 +1,4 @@
|
|||||||
import importlib.util
|
import importlib.machinery
|
||||||
import sys
|
import sys
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
@@ -6,11 +6,12 @@ import json
|
|||||||
import stat
|
import stat
|
||||||
import logging
|
import logging
|
||||||
import threading
|
import threading
|
||||||
|
import types
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from xtendr.xtendrbase import XtendRBase
|
from xtendr.xtendrbase import XtendRBase
|
||||||
from xtendr import signing as xsign
|
from xtendr import signing as xsign
|
||||||
|
|
||||||
__version__ = "0.5.0"
|
__version__ = "0.5.4"
|
||||||
|
|
||||||
logger = logging.getLogger("xtendr")
|
logger = logging.getLogger("xtendr")
|
||||||
|
|
||||||
@@ -25,6 +26,39 @@ SIG_VERIFIED = "verified" # whitelist entry present, signature and hash both c
|
|||||||
SIG_UNSIGNED = "unsigned" # no whitelist entry for this plugin at all
|
SIG_UNSIGNED = "unsigned" # no whitelist entry for this plugin at all
|
||||||
SIG_INVALID = "invalid" # whitelist entry present but signature/hash mismatch (tampered)
|
SIG_INVALID = "invalid" # whitelist entry present but signature/hash mismatch (tampered)
|
||||||
|
|
||||||
|
# Upper bounds for what attach() reads into memory.
|
||||||
|
MAX_MANIFEST_BYTES = 1024 * 1024
|
||||||
|
MAX_MODULE_BYTES = 16 * 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
|
def _read_regular_file(path: str, limit: int) -> bytes:
|
||||||
|
"""Read a whole regular file once, without following a symlink at `path`.
|
||||||
|
|
||||||
|
Raises OSError for a symlink (O_NOFOLLOW), anything but a regular file,
|
||||||
|
or a file larger than `limit` bytes.
|
||||||
|
"""
|
||||||
|
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0)
|
||||||
|
fd = os.open(path, flags)
|
||||||
|
try:
|
||||||
|
st = os.fstat(fd)
|
||||||
|
if not stat.S_ISREG(st.st_mode):
|
||||||
|
raise OSError(f"'{path}' is not a regular file")
|
||||||
|
if st.st_size > limit:
|
||||||
|
raise OSError(f"'{path}' is larger than {limit} bytes")
|
||||||
|
chunks = []
|
||||||
|
total = 0
|
||||||
|
while True:
|
||||||
|
chunk = os.read(fd, 1024 * 1024)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
total += len(chunk)
|
||||||
|
if total > limit:
|
||||||
|
raise OSError(f"'{path}' grew beyond {limit} bytes while reading")
|
||||||
|
chunks.append(chunk)
|
||||||
|
return b"".join(chunks)
|
||||||
|
finally:
|
||||||
|
os.close(fd)
|
||||||
|
|
||||||
|
|
||||||
class XtendRSystem:
|
class XtendRSystem:
|
||||||
"""Plugin system to manage plugins.
|
"""Plugin system to manage plugins.
|
||||||
@@ -37,7 +71,7 @@ class XtendRSystem:
|
|||||||
Example:
|
Example:
|
||||||
>>> system = XtendRSystem()
|
>>> system = XtendRSystem()
|
||||||
>>> system.version()
|
>>> system.version()
|
||||||
XtendR v0.5.0
|
XtendR v0.5.4
|
||||||
>>> system.attach("example_plugin", lambda: None)
|
>>> system.attach("example_plugin", lambda: None)
|
||||||
>>> system.run("example_plugin")
|
>>> system.run("example_plugin")
|
||||||
ExamplePlugin is running!
|
ExamplePlugin is running!
|
||||||
@@ -45,34 +79,43 @@ class XtendRSystem:
|
|||||||
ExamplePlugin has stopped!
|
ExamplePlugin has stopped!
|
||||||
>>> system.detach("example_plugin")
|
>>> system.detach("example_plugin")
|
||||||
Detached plugin 'example_plugin'.
|
Detached plugin 'example_plugin'.
|
||||||
|
|
||||||
|
A system can be marked `protected=True` for plugins that must stay
|
||||||
|
attached for the lifetime of the process (e.g. an application's
|
||||||
|
built-ins). Protected systems still attach/run/stop normally; only
|
||||||
|
detach() is restricted, and only for ordinary callers -- detach(...,
|
||||||
|
force=True) and detach_all(..., force=True) remain available for the
|
||||||
|
host application's own shutdown path. There is deliberately no way to
|
||||||
|
force a single detach() without also opting in via the same keyword a
|
||||||
|
UI action would have to expose, so "not detachable by the user" is a
|
||||||
|
property of the call site, not of hidden state.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, pluginpath="plugins", public_key_path=None, whitelist_path=None, whitelist_passphrase=None):
|
def __init__(self, pluginpath="plugins", public_key_path=None, whitelist_path=None,
|
||||||
|
whitelist_passphrase=None, protected=False):
|
||||||
self.pluginspath = pluginpath
|
self.pluginspath = pluginpath
|
||||||
self.plugins = {}
|
self.plugins = {}
|
||||||
|
self.protected = protected
|
||||||
self._lock = threading.RLock()
|
self._lock = threading.RLock()
|
||||||
|
|
||||||
# -- signature verification setup ---------------------------------
|
# -- signature verification setup ---------------------------------
|
||||||
|
# Paths are kept (not just the loaded key/whitelist objects) so
|
||||||
|
# reload() can re-read them from disk later -- e.g. after an admin
|
||||||
|
# re-signs a plugin or adds a whitelist entry for it -- without
|
||||||
|
# restarting the whole process.
|
||||||
|
#
|
||||||
# If either the public key or the whitelist can't be loaded, we
|
# If either the public key or the whitelist can't be loaded, we
|
||||||
# fail closed: self._public_key / self._whitelist stay None, and
|
# fail closed: self._public_key / self._whitelist stay None, and
|
||||||
# every plugin will come back as SIG_UNSIGNED (disabled) rather
|
# every plugin will come back as SIG_UNSIGNED (disabled) rather
|
||||||
# than silently skipping verification. This is deliberate -- an
|
# than silently skipping verification. This is deliberate -- an
|
||||||
# admin who wants unsigned plugins to run should not be able to
|
# admin who wants unsigned plugins to run should not be able to
|
||||||
# get there by accident (e.g. a missing/misspelled key path).
|
# get there by accident (e.g. a missing/misspelled key path).
|
||||||
|
self._public_key_path = public_key_path
|
||||||
|
self._whitelist_path = whitelist_path
|
||||||
|
self._whitelist_passphrase = whitelist_passphrase
|
||||||
self._public_key = None
|
self._public_key = None
|
||||||
self._whitelist = None
|
self._whitelist = None
|
||||||
|
self._reload_verification_material()
|
||||||
if public_key_path is not None:
|
|
||||||
try:
|
|
||||||
self._public_key = xsign.load_public_key(Path(public_key_path))
|
|
||||||
except (OSError, ValueError) as e:
|
|
||||||
logger.error("Could not load XtendR public key from '%s': %s", public_key_path, e)
|
|
||||||
|
|
||||||
if whitelist_path is not None:
|
|
||||||
try:
|
|
||||||
self._whitelist = xsign.Whitelist.load(Path(whitelist_path), whitelist_passphrase)
|
|
||||||
except (OSError, ValueError) as e:
|
|
||||||
logger.error("Could not load XtendR plugin whitelist from '%s': %s", whitelist_path, e)
|
|
||||||
|
|
||||||
if self._public_key is None or self._whitelist is None:
|
if self._public_key is None or self._whitelist is None:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
@@ -81,6 +124,30 @@ class XtendRSystem:
|
|||||||
pluginpath,
|
pluginpath,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def _reload_verification_material(self) -> None:
|
||||||
|
"""(Re-)read the public key and whitelist from disk into
|
||||||
|
self._public_key / self._whitelist. Called once from __init__,
|
||||||
|
and again from reload() so a freshly-signed plugin or updated
|
||||||
|
whitelist can be picked up without restarting the process.
|
||||||
|
|
||||||
|
Fails closed on error, same as __init__ did: a key/whitelist
|
||||||
|
that can't be (re)loaded leaves that half of verification as
|
||||||
|
None rather than keeping around whatever was previously loaded.
|
||||||
|
"""
|
||||||
|
self._public_key = None
|
||||||
|
if self._public_key_path is not None:
|
||||||
|
try:
|
||||||
|
self._public_key = xsign.load_public_key(Path(self._public_key_path))
|
||||||
|
except (OSError, ValueError) as e:
|
||||||
|
logger.error("Could not load XtendR public key from '%s': %s", self._public_key_path, e)
|
||||||
|
|
||||||
|
self._whitelist = None
|
||||||
|
if self._whitelist_path is not None:
|
||||||
|
try:
|
||||||
|
self._whitelist = xsign.Whitelist.load(Path(self._whitelist_path), self._whitelist_passphrase)
|
||||||
|
except (OSError, ValueError) as e:
|
||||||
|
logger.error("Could not load XtendR plugin whitelist from '%s': %s", self._whitelist_path, e)
|
||||||
|
|
||||||
def version(self) -> str:
|
def version(self) -> str:
|
||||||
return "XtendR v" + __version__
|
return "XtendR v" + __version__
|
||||||
|
|
||||||
@@ -95,10 +162,13 @@ class XtendRSystem:
|
|||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def _verify_signature(self, name: str, plugin_path: str, module_name: str) -> dict:
|
def _verify_signature(self, name: str, manifest_bytes: bytes, module_bytes: bytes,
|
||||||
"""Check a plugin's signature against the loaded whitelist.
|
module_name: str, class_name: str) -> dict:
|
||||||
|
"""Check a plugin's signature against the loaded whitelist, over the
|
||||||
|
manifest and module bytes attach() has already read (and will run).
|
||||||
|
|
||||||
Returns a dict with at least a "status" key (SIG_VERIFIED /
|
The manifest's module/class must also be the ones the whitelist entry
|
||||||
|
signs. Returns a dict with at least a "status" key (SIG_VERIFIED /
|
||||||
SIG_UNSIGNED / SIG_INVALID) plus whatever whitelist metadata is
|
SIG_UNSIGNED / SIG_INVALID) plus whatever whitelist metadata is
|
||||||
available, for display in the UI. Never raises.
|
available, for display in the UI. Never raises.
|
||||||
"""
|
"""
|
||||||
@@ -114,7 +184,8 @@ class XtendRSystem:
|
|||||||
result.update(sha256=entry.sha256, signature=entry.signature, signed_at=entry.signed_at)
|
result.update(sha256=entry.sha256, signature=entry.signature, signed_at=entry.signed_at)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
ok = xsign.verify_plugin_on_disk(self._public_key, Path(plugin_path), entry)
|
ok = (entry.module == module_name and entry.cls == class_name
|
||||||
|
and xsign.verify_plugin_bytes(self._public_key, entry, manifest_bytes, module_bytes))
|
||||||
except Exception: # noqa: BLE001 - never let a verification bug crash attach()
|
except Exception: # noqa: BLE001 - never let a verification bug crash attach()
|
||||||
logger.error("Signature verification raised for plugin '%s'.", name, exc_info=True)
|
logger.error("Signature verification raised for plugin '%s'.", name, exc_info=True)
|
||||||
ok = False
|
ok = False
|
||||||
@@ -161,19 +232,27 @@ class XtendRSystem:
|
|||||||
|
|
||||||
self._check_permissions(info_path)
|
self._check_permissions(info_path)
|
||||||
|
|
||||||
|
# Every file is read exactly once. The signature is checked over
|
||||||
|
# these bytes and the module is executed from these bytes, so
|
||||||
|
# nothing swapped on disk afterwards (and no __pycache__/*.pyc)
|
||||||
|
# can change what runs.
|
||||||
try:
|
try:
|
||||||
with open(info_path, "r", encoding="utf-8") as f:
|
manifest_bytes = _read_regular_file(info_path, MAX_MANIFEST_BYTES)
|
||||||
plugin_info = json.load(f)
|
plugin_info = json.loads(manifest_bytes.decode("utf-8"))
|
||||||
except (OSError, json.JSONDecodeError) as e:
|
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as e:
|
||||||
logger.error("Failed to read info file for plugin '%s': %s", name, e)
|
logger.error("Failed to read info file for plugin '%s': %s", name, e)
|
||||||
return
|
return
|
||||||
|
if not isinstance(plugin_info, dict):
|
||||||
|
logger.error("Plugin '%s' info file is not a JSON object.", name)
|
||||||
|
return
|
||||||
|
|
||||||
module_name = plugin_info.get("module")
|
module_name = plugin_info.get("module")
|
||||||
class_name = plugin_info.get("class")
|
class_name = plugin_info.get("class")
|
||||||
if not module_name or not class_name:
|
if not module_name or not class_name:
|
||||||
logger.error("Plugin '%s' info file is missing 'module' or 'class' key.", name)
|
logger.error("Plugin '%s' info file is missing 'module' or 'class' key.", name)
|
||||||
return
|
return
|
||||||
if not _MODULE_RE.match(module_name) or not _MODULE_RE.match(class_name):
|
if (not isinstance(module_name, str) or not isinstance(class_name, str)
|
||||||
|
or not _MODULE_RE.match(module_name) or not _MODULE_RE.match(class_name)):
|
||||||
logger.error("Plugin '%s' has an invalid module/class identifier.", name)
|
logger.error("Plugin '%s' has an invalid module/class identifier.", name)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -184,11 +263,17 @@ class XtendRSystem:
|
|||||||
|
|
||||||
self._check_permissions(module_file)
|
self._check_permissions(module_file)
|
||||||
|
|
||||||
|
try:
|
||||||
|
module_bytes = _read_regular_file(module_file, MAX_MODULE_BYTES)
|
||||||
|
except OSError as e:
|
||||||
|
logger.error("Failed to read module file for plugin '%s': %s", name, e)
|
||||||
|
return
|
||||||
|
|
||||||
# Verify the plugin's signature BEFORE we ever execute its code.
|
# Verify the plugin's signature BEFORE we ever execute its code.
|
||||||
# Unsigned/tampered plugins still get a listing entry (built
|
# Unsigned/tampered plugins still get a listing entry (built
|
||||||
# from the manifest alone, which is inert JSON) but their .py
|
# from the manifest alone, which is inert JSON) but their .py
|
||||||
# file is never imported, and they can never be run.
|
# file is never imported, and they can never be run.
|
||||||
sig = self._verify_signature(name, plugin_path, module_name)
|
sig = self._verify_signature(name, manifest_bytes, module_bytes, module_name, class_name)
|
||||||
if sig["status"] != SIG_VERIFIED:
|
if sig["status"] != SIG_VERIFIED:
|
||||||
if sig["status"] == SIG_INVALID:
|
if sig["status"] == SIG_INVALID:
|
||||||
logger.error(
|
logger.error(
|
||||||
@@ -208,20 +293,25 @@ class XtendRSystem:
|
|||||||
"module_key": None,
|
"module_key": None,
|
||||||
"disabled": True,
|
"disabled": True,
|
||||||
"signature": sig,
|
"signature": sig,
|
||||||
|
"pre_load_thread": None,
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
|
|
||||||
# Load the module directly from its file path instead of
|
# Run the verified bytes themselves: compile them and execute
|
||||||
# mutating sys.path. This prevents a plugin from shadowing
|
# the code in a fresh module. No import machinery reads the file
|
||||||
# stdlib or third-party modules for the rest of the process.
|
# again and no bytecode cache is consulted or written (a planted
|
||||||
|
# __pycache__/*.pyc used to win over the verified source). sys.path
|
||||||
|
# isn't touched, so a plugin can't shadow stdlib or third-party
|
||||||
|
# modules for the rest of the process.
|
||||||
qualified_name = f"xtendr_plugin_{name}_{module_name}"
|
qualified_name = f"xtendr_plugin_{name}_{module_name}"
|
||||||
try:
|
try:
|
||||||
spec = importlib.util.spec_from_file_location(qualified_name, module_file)
|
code = compile(module_bytes, module_file, "exec", dont_inherit=True)
|
||||||
if spec is None or spec.loader is None:
|
module = types.ModuleType(qualified_name)
|
||||||
raise ImportError(f"Could not create import spec for '{module_file}'")
|
module.__file__ = module_file
|
||||||
module = importlib.util.module_from_spec(spec)
|
module.__spec__ = importlib.machinery.ModuleSpec(qualified_name, None, origin=module_file)
|
||||||
|
module.__spec__.has_location = True
|
||||||
sys.modules[qualified_name] = module
|
sys.modules[qualified_name] = module
|
||||||
spec.loader.exec_module(module)
|
exec(code, module.__dict__) # noqa: S102 - the bytes just verified above
|
||||||
|
|
||||||
plugin_class = getattr(module, class_name)
|
plugin_class = getattr(module, class_name)
|
||||||
instance = plugin_class()
|
instance = plugin_class()
|
||||||
@@ -244,6 +334,7 @@ class XtendRSystem:
|
|||||||
"module_key": qualified_name,
|
"module_key": qualified_name,
|
||||||
"disabled": False,
|
"disabled": False,
|
||||||
"signature": sig,
|
"signature": sig,
|
||||||
|
"pre_load_thread": None,
|
||||||
}
|
}
|
||||||
logger.info("Attached plugin '%s'.", name)
|
logger.info("Attached plugin '%s'.", name)
|
||||||
logger.info("Running pre-load on '%s'.", name)
|
logger.info("Running pre-load on '%s'.", name)
|
||||||
@@ -255,45 +346,162 @@ class XtendRSystem:
|
|||||||
logger.error("Plugin '%s' raised during pre_load.", name, exc_info=True)
|
logger.error("Plugin '%s' raised during pre_load.", name, exc_info=True)
|
||||||
|
|
||||||
thread = threading.Thread(target=_pre_load_worker, daemon=True)
|
thread = threading.Thread(target=_pre_load_worker, daemon=True)
|
||||||
|
self.plugins[name]["pre_load_thread"] = thread
|
||||||
thread.start()
|
thread.start()
|
||||||
|
|
||||||
|
def reload(self, name: str, callback=None) -> bool:
|
||||||
|
"""Re-attempt attaching a plugin that's currently disabled due to
|
||||||
|
failed signature verification (SIG_UNSIGNED / SIG_INVALID) -- e.g.
|
||||||
|
after re-signing it or adding/fixing its whitelist entry.
|
||||||
|
|
||||||
|
This is specifically a recovery path for that one state, not a
|
||||||
|
general-purpose re-attach: a plugin that isn't currently attached,
|
||||||
|
or is attached but not disabled, is left alone and this returns
|
||||||
|
False without side effects.
|
||||||
|
|
||||||
|
The public key and whitelist are re-read from disk before
|
||||||
|
re-verifying -- __init__ only loads them once, so without this a
|
||||||
|
freshly-updated whitelist would never actually take effect and
|
||||||
|
reload() would just repeat the same failed check.
|
||||||
|
|
||||||
|
Returns True if the plugin ends up attached and enabled, False if
|
||||||
|
it's still disabled (or wasn't reloadable to begin with).
|
||||||
|
"""
|
||||||
|
with self._lock:
|
||||||
|
entry = self.plugins.get(name)
|
||||||
|
if entry is None:
|
||||||
|
logger.error("Plugin '%s' is not attached; nothing to reload.", name)
|
||||||
|
return False
|
||||||
|
if not entry.get("disabled"):
|
||||||
|
logger.info("Plugin '%s' is not disabled; reload() is a no-op.", name)
|
||||||
|
return False
|
||||||
|
# Drop the disabled placeholder so attach() below doesn't just
|
||||||
|
# see 'already attached' and bail out immediately.
|
||||||
|
self.plugins.pop(name, None)
|
||||||
|
|
||||||
|
self._reload_verification_material()
|
||||||
|
self.attach(name, callback)
|
||||||
|
|
||||||
|
with self._lock:
|
||||||
|
entry = self.plugins.get(name)
|
||||||
|
return entry is not None and not entry.get("disabled")
|
||||||
|
|
||||||
def run(self, name: str, *args, **kwargs):
|
def run(self, name: str, *args, **kwargs):
|
||||||
"""Run the plugin's 'run' method if available."""
|
"""Run the plugin's 'run' method if available."""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
entry = self.plugins.get(name)
|
entry = self.plugins.get(name)
|
||||||
if entry is None:
|
if entry is None:
|
||||||
logger.error("Plugin '%s' not found or has no 'run' method.", name)
|
logger.error("Plugin '%s' not found or has no 'run' method.", name)
|
||||||
return
|
return
|
||||||
if entry.get("disabled"):
|
if entry.get("disabled"):
|
||||||
logger.error("Plugin '%s' is disabled (failed signature verification) and cannot run.", name)
|
logger.error("Plugin '%s' is disabled (failed signature verification) and cannot run.", name)
|
||||||
return
|
return
|
||||||
entry["running"] = True
|
entry["running"] = True
|
||||||
|
instance = entry["instance"]
|
||||||
try:
|
try:
|
||||||
return entry["instance"].run(*args, **kwargs)
|
return instance.run(*args, **kwargs)
|
||||||
except Exception: # noqa: BLE001
|
except Exception: # noqa: BLE001
|
||||||
logger.error("Plugin '%s' raised during run.", name, exc_info=True)
|
logger.error("Plugin '%s' raised during run.", name, exc_info=True)
|
||||||
entry["running"] = False
|
with self._lock:
|
||||||
|
entry["running"] = False
|
||||||
|
|
||||||
def stop(self, name: str) -> None:
|
def stop(self, name: str) -> None:
|
||||||
"""Stop the plugin if it's running."""
|
"""Stop the plugin if it's running."""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
entry = self.plugins.get(name)
|
entry = self.plugins.get(name)
|
||||||
if entry is None or not entry["running"]:
|
if entry is None or not entry["running"]:
|
||||||
logger.info("Plugin '%s' is not running.", name)
|
logger.info("Plugin '%s' is not running.", name)
|
||||||
return
|
return
|
||||||
entry["running"] = False
|
entry["running"] = False
|
||||||
|
instance = entry["instance"]
|
||||||
try:
|
try:
|
||||||
entry["instance"].stop()
|
instance.stop()
|
||||||
except Exception: # noqa: BLE001
|
except Exception: # noqa: BLE001
|
||||||
logger.error("Plugin '%s' raised during stop.", name, exc_info=True)
|
logger.error("Plugin '%s' raised during stop.", name, exc_info=True)
|
||||||
|
|
||||||
def detach(self, name: str) -> None:
|
def detach(self, name: str, *, timeout: float = 5.0, force: bool = False) -> None:
|
||||||
"""Unload a plugin."""
|
"""Unload a plugin: stop it if running, let it release its own
|
||||||
|
resources via unload(), then drop every reference XtendRSystem
|
||||||
|
holds to it (dict entry, sys.modules entry) so nothing outside the
|
||||||
|
plugin's own cleanup keeps it alive.
|
||||||
|
|
||||||
|
Protected systems (see __init__) refuse this unless force=True is
|
||||||
|
passed explicitly -- the caller has to opt in on purpose, so a
|
||||||
|
generic "detach" UI action wired up against this system can't
|
||||||
|
accidentally (or maliciously) unload a built-in.
|
||||||
|
"""
|
||||||
|
if self.protected and not force:
|
||||||
|
logger.error(
|
||||||
|
"Refusing to detach '%s': this plugin system is protected "
|
||||||
|
"and cannot be detached from without force=True.", name,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
with self._lock:
|
with self._lock:
|
||||||
entry = self.plugins.pop(name, None)
|
entry = self.plugins.pop(name, None)
|
||||||
if entry is None:
|
if entry is None:
|
||||||
logger.info("Plugin '%s' is not attached.", name)
|
logger.info("Plugin '%s' is not attached.", name)
|
||||||
return
|
return
|
||||||
if entry.get("module_key"):
|
was_running = entry["running"]
|
||||||
sys.modules.pop(entry["module_key"], None)
|
entry["running"] = False
|
||||||
logger.info("Detached plugin '%s'.", name)
|
instance = entry["instance"]
|
||||||
|
thread = entry.get("pre_load_thread")
|
||||||
|
|
||||||
|
# pre_load() may still be running in its own thread (e.g. detach
|
||||||
|
# called right after attach). Give it a bounded chance to finish
|
||||||
|
# before we call stop()/unload(), so a plugin doesn't get stopped
|
||||||
|
# out from under itself mid pre_load. If it doesn't finish in
|
||||||
|
# time we proceed anyway -- it's a daemon thread and holds its
|
||||||
|
# own reference to the instance, so this is a correctness/race
|
||||||
|
# concern rather than a leak.
|
||||||
|
if thread is not None and thread.is_alive():
|
||||||
|
thread.join(timeout)
|
||||||
|
if thread.is_alive():
|
||||||
|
logger.warning(
|
||||||
|
"Plugin '%s' pre_load() did not finish within %.1fs; "
|
||||||
|
"detaching anyway.", name, timeout,
|
||||||
|
)
|
||||||
|
|
||||||
|
if instance is not None:
|
||||||
|
if was_running:
|
||||||
|
try:
|
||||||
|
instance.stop()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.error("Plugin '%s' raised during stop.", name, exc_info=True)
|
||||||
|
try:
|
||||||
|
instance.unload()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.error("Plugin '%s' raised during unload.", name, exc_info=True)
|
||||||
|
|
||||||
|
if entry.get("module_key"):
|
||||||
|
sys.modules.pop(entry["module_key"], None)
|
||||||
|
|
||||||
|
# Drop our own strong references explicitly rather than letting
|
||||||
|
# them idle until this frame unwinds -- entry/instance are the
|
||||||
|
# last references XtendRSystem holds, so this makes the plugin
|
||||||
|
# object (and anything it exclusively owns) collectible the
|
||||||
|
# moment its unload() has actually let go of its own resources.
|
||||||
|
entry["instance"] = None
|
||||||
|
entry["pre_load_thread"] = None
|
||||||
|
|
||||||
|
logger.info("Detached plugin '%s'.", name)
|
||||||
|
|
||||||
|
def detach_all(self, *, force: bool = False) -> None:
|
||||||
|
"""Detach every currently-attached plugin. Convenience for clean
|
||||||
|
shutdown; equivalent to calling detach() on every plugin name.
|
||||||
|
|
||||||
|
For a protected system this is a no-op unless force=True (see
|
||||||
|
detach()) -- shutdown code that genuinely needs to tear a
|
||||||
|
protected system down (e.g. the host application closing) passes
|
||||||
|
force=True explicitly; nothing else can.
|
||||||
|
"""
|
||||||
|
if self.protected and not force:
|
||||||
|
logger.error(
|
||||||
|
"Refusing detach_all(): this plugin system is protected "
|
||||||
|
"and cannot be detached from without force=True."
|
||||||
|
)
|
||||||
|
return
|
||||||
|
with self._lock:
|
||||||
|
names = list(self.plugins.keys())
|
||||||
|
for name in names:
|
||||||
|
self.detach(name, force=force)
|
||||||
Reference in new issue
Block a user