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
+76
-20
@@ -1,4 +1,4 @@
|
||||
import importlib.util
|
||||
import importlib.machinery
|
||||
import sys
|
||||
import os
|
||||
import re
|
||||
@@ -6,11 +6,12 @@ import json
|
||||
import stat
|
||||
import logging
|
||||
import threading
|
||||
import types
|
||||
from pathlib import Path
|
||||
from xtendr.xtendrbase import XtendRBase
|
||||
from xtendr import signing as xsign
|
||||
|
||||
__version__ = "0.5.1"
|
||||
__version__ = "0.5.4"
|
||||
|
||||
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_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:
|
||||
"""Plugin system to manage plugins.
|
||||
@@ -37,7 +71,7 @@ class XtendRSystem:
|
||||
Example:
|
||||
>>> system = XtendRSystem()
|
||||
>>> system.version()
|
||||
XtendR v0.5.1
|
||||
XtendR v0.5.4
|
||||
>>> system.attach("example_plugin", lambda: None)
|
||||
>>> system.run("example_plugin")
|
||||
ExamplePlugin is running!
|
||||
@@ -128,10 +162,13 @@ class XtendRSystem:
|
||||
return False
|
||||
return True
|
||||
|
||||
def _verify_signature(self, name: str, plugin_path: str, module_name: str) -> dict:
|
||||
"""Check a plugin's signature against the loaded whitelist.
|
||||
def _verify_signature(self, name: str, manifest_bytes: bytes, module_bytes: bytes,
|
||||
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
|
||||
available, for display in the UI. Never raises.
|
||||
"""
|
||||
@@ -147,7 +184,8 @@ class XtendRSystem:
|
||||
result.update(sha256=entry.sha256, signature=entry.signature, signed_at=entry.signed_at)
|
||||
|
||||
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()
|
||||
logger.error("Signature verification raised for plugin '%s'.", name, exc_info=True)
|
||||
ok = False
|
||||
@@ -194,19 +232,27 @@ class XtendRSystem:
|
||||
|
||||
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:
|
||||
with open(info_path, "r", encoding="utf-8") as f:
|
||||
plugin_info = json.load(f)
|
||||
except (OSError, json.JSONDecodeError) as e:
|
||||
manifest_bytes = _read_regular_file(info_path, MAX_MANIFEST_BYTES)
|
||||
plugin_info = json.loads(manifest_bytes.decode("utf-8"))
|
||||
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as e:
|
||||
logger.error("Failed to read info file for plugin '%s': %s", name, e)
|
||||
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")
|
||||
class_name = plugin_info.get("class")
|
||||
if not module_name or not class_name:
|
||||
logger.error("Plugin '%s' info file is missing 'module' or 'class' key.", name)
|
||||
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)
|
||||
return
|
||||
|
||||
@@ -217,11 +263,17 @@ class XtendRSystem:
|
||||
|
||||
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.
|
||||
# Unsigned/tampered plugins still get a listing entry (built
|
||||
# from the manifest alone, which is inert JSON) but their .py
|
||||
# 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_INVALID:
|
||||
logger.error(
|
||||
@@ -245,17 +297,21 @@ class XtendRSystem:
|
||||
}
|
||||
return
|
||||
|
||||
# Load the module directly from its file path instead of
|
||||
# mutating sys.path. This prevents a plugin from shadowing
|
||||
# stdlib or third-party modules for the rest of the process.
|
||||
# Run the verified bytes themselves: compile them and execute
|
||||
# the code in a fresh module. No import machinery reads the file
|
||||
# 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}"
|
||||
try:
|
||||
spec = importlib.util.spec_from_file_location(qualified_name, module_file)
|
||||
if spec is None or spec.loader is None:
|
||||
raise ImportError(f"Could not create import spec for '{module_file}'")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
code = compile(module_bytes, module_file, "exec", dont_inherit=True)
|
||||
module = types.ModuleType(qualified_name)
|
||||
module.__file__ = module_file
|
||||
module.__spec__ = importlib.machinery.ModuleSpec(qualified_name, None, origin=module_file)
|
||||
module.__spec__.has_location = True
|
||||
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)
|
||||
instance = plugin_class()
|
||||
|
||||
Reference in new issue
Block a user