|
| 1 | +import ctypes |
| 2 | +import sys |
| 3 | +import threading |
| 4 | +from pathlib import Path |
| 5 | +from typing import Callable, Iterable, Optional, Type, TypeVar |
| 6 | + |
| 7 | +from structlog import get_logger |
| 8 | +from unblob_native.sandbox import ( |
| 9 | + AccessFS, |
| 10 | + SandboxError, |
| 11 | + restrict_access, |
| 12 | +) |
| 13 | + |
| 14 | +if sys.version_info >= (3, 10): |
| 15 | + from typing import ParamSpec |
| 16 | +else: |
| 17 | + from typing_extensions import ParamSpec |
| 18 | + |
| 19 | +from unblob.processing import ExtractionConfig |
| 20 | + |
| 21 | +logger = get_logger() |
| 22 | + |
| 23 | +P = ParamSpec("P") |
| 24 | +R = TypeVar("R") |
| 25 | + |
| 26 | + |
| 27 | +class Sandbox: |
| 28 | + """Configures restricted file-systems to run functions in. |
| 29 | +
|
| 30 | + When calling ``run()``, a separate thread will be configured with |
| 31 | + minimum required file-system permissions. All subprocesses spawned |
| 32 | + from that thread will honor the restrictions. |
| 33 | + """ |
| 34 | + |
| 35 | + def __init__( |
| 36 | + self, |
| 37 | + config: ExtractionConfig, |
| 38 | + log_path: Path, |
| 39 | + report_file: Optional[Path], |
| 40 | + extra_passthrough: Iterable[AccessFS] = (), |
| 41 | + ): |
| 42 | + self.passthrough = [ |
| 43 | + # Python, shared libraries, extractor binaries and so on |
| 44 | + AccessFS.read("/"), |
| 45 | + # Multiprocessing |
| 46 | + AccessFS.read_write("/dev/shm"), # noqa: S108 |
| 47 | + # Extracted contents |
| 48 | + AccessFS.read_write(config.extract_root), |
| 49 | + AccessFS.make_dir(config.extract_root.parent), |
| 50 | + AccessFS.read_write(log_path), |
| 51 | + *extra_passthrough, |
| 52 | + ] |
| 53 | + |
| 54 | + if report_file: |
| 55 | + self.passthrough += [ |
| 56 | + AccessFS.read_write(report_file), |
| 57 | + AccessFS.make_reg(report_file.parent), |
| 58 | + ] |
| 59 | + |
| 60 | + def run(self, callback: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R: |
| 61 | + """Run callback with restricted filesystem access.""" |
| 62 | + exception = None |
| 63 | + result = None |
| 64 | + |
| 65 | + def _run_in_thread(callback, *args, **kwargs): |
| 66 | + nonlocal exception, result |
| 67 | + |
| 68 | + self._try_enter_sandbox() |
| 69 | + try: |
| 70 | + result = callback(*args, **kwargs) |
| 71 | + except BaseException as e: |
| 72 | + exception = e |
| 73 | + |
| 74 | + thread = threading.Thread( |
| 75 | + target=_run_in_thread, args=(callback, *args), kwargs=kwargs |
| 76 | + ) |
| 77 | + thread.start() |
| 78 | + |
| 79 | + try: |
| 80 | + thread.join() |
| 81 | + except KeyboardInterrupt: |
| 82 | + raise_in_thread(thread, KeyboardInterrupt) |
| 83 | + thread.join() |
| 84 | + |
| 85 | + if exception: |
| 86 | + raise exception # pyright: ignore[reportGeneralTypeIssues] |
| 87 | + return result # pyright: ignore[reportReturnType] |
| 88 | + |
| 89 | + def _try_enter_sandbox(self): |
| 90 | + try: |
| 91 | + restrict_access(*self.passthrough) |
| 92 | + except SandboxError: |
| 93 | + logger.warning( |
| 94 | + "Sandboxing FS access is unavailable on this system, skipping." |
| 95 | + ) |
| 96 | + |
| 97 | + |
| 98 | +def raise_in_thread(thread: threading.Thread, exctype: Type) -> None: |
| 99 | + if thread.ident is None: |
| 100 | + raise RuntimeError("Thread is not started") |
| 101 | + |
| 102 | + res = ctypes.pythonapi.PyThreadState_SetAsyncExc( |
| 103 | + ctypes.c_ulong(thread.ident), ctypes.py_object(exctype) |
| 104 | + ) |
| 105 | + |
| 106 | + # success |
| 107 | + if res == 1: |
| 108 | + return |
| 109 | + |
| 110 | + # Need to revert the call to restore interpreter state |
| 111 | + ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_ulong(thread.ident), None) |
| 112 | + |
| 113 | + # Thread could have exited since |
| 114 | + if res == 0: |
| 115 | + return |
| 116 | + |
| 117 | + # Something bad have happened |
| 118 | + raise RuntimeError("Could not raise exception in thread", thread.ident) |
0 commit comments