SPB Git

Repository Public

SECURITY.md 16.9 KB 200 lines markdown

1# SheetPython — security model23This document states what the Python integration of ORIX Sheet enforces, how each claim is verified, and what it4does **not** enforce. Claims marked ✔ are asserted by a test that runs a real interpreter; the test name is given.5Observations were made on macOS 27.0 (26A5425a), Apple Silicon, with Homebrew Python 3.14.4 and the Xcode Python63.9.6. Tests live in `Tests/SheetPythonTests` (engine) and `../FeaturePython/Tests/FeaturePythonTests` (app layer).78## 1. Design in one paragraph910Scripts run in a **separate process** of a Python interpreter already installed on the Mac (nothing is bundled or11embedded), started with `posix_spawn` in its own process group. The script talks to the app only through two12inherited pipes (fd 3 and 4) carrying newline-delimited JSON requests: read a range, list sheets, read the13selection, buffer a write, announce a figure or a table preview, report the end. The app answers reads from the live14workbook and **buffers writes**; they are applied as one undoable step only when the run succeeds. In *restricted15mode* (the default) the interpreter is wrapped in `/usr/bin/sandbox-exec -p <profile>`.1617## 2. Threat model1819Assets: the user's files and credentials, the network position of the Mac, the other processes of the user, the20content of the open workbook, the integrity of the workbook.2122Adversaries considered:23241. **A workbook received from someone else that contains a script** (the main threat). The script must not run25   without the user reading and approving it, and when it runs in restricted mode it must not reach files, network26   or other programs.272. **A script the user wrote or pasted that misbehaves**: infinite loop, huge output, fork bomb-like behaviour,28   memory exhaustion, attempts to keep running after the run.293. **A script attacking the app through the protocol**: malformed messages, oversized messages, forged requests,30   closing the pipes, never reading answers.3132Out of scope: a compromised interpreter or a malicious package already installed in the interpreter's33site-packages (it is code the user installed; in restricted mode it runs under the same restrictions as the34script), kernel or sandbox vulnerabilities, an attacker who already runs code as the user outside restricted mode.3536## 3. Never auto-executed3738- Scripts are stored as data (`Workbook.attachments["python/<id>.json"]`). `PythonScripts.load` only decodes JSON.39- Nothing in SheetPython or FeaturePython starts an interpreter on a script when a workbook is opened, when the40  Studio appears or when a script is selected. The only path to execution is `PythonStudioModel.run()` (the Run41  button / ⌘↩), which first evaluates consent.42  ✔ `StudioModelTests.scriptsFromAWorkbookNeverRunWithoutConsent` (opening + showing: console empty, sheet43  untouched, no audit entry for that code).44- Interpreter discovery does run the *interpreters* found at the standard locations (and the one the user chooses)45  with the bundled `probe.py` under `-I -B`, an 8 s timeout and a minimal environment — it runs no workbook46  content. `/usr/bin/python3` is only probed when developer tools are installed (otherwise the shim would open an47  install dialog). Note: an attacker able to plant an executable named `python3` in one of those locations already48  has the user's privileges.4950## 4. Consent5152Implemented by `PythonConsent` (FeaturePython) and `PythonTrust` (SheetPython).5354| Rule | Verified by |55|---|---|56| A script that arrived with a workbook shows the consent sheet (full code, interpreter, mode, time limit, SHA-256) before its first run in a session | `ConsentTests.scriptsFromAWorkbookAlwaysAsk`, `StudioModelTests.scriptsFromAWorkbookNeverRunWithoutConsent` |57| "Cancel" runs nothing | same model test |58| The answer is valid only for the exact text and mode that were displayed: if the script changed while the sheet was open, nothing runs | same model test (marker file never created) |59| "Run once" records nothing; a later session asks again | same model test |60| "Always trust this script" stores the SHA-256 of the exact text + the workbook identifier; any change of the text (in another editor, in the file) makes it untrusted again; another workbook asks again | `RecordsTests.trustIsKeyedByExactCodeWorkbookAndMode`, `ConsentTests.trustIsForTheExactTextAndMode`, model test (tampered copy) |61| Consent given for restricted mode never covers an unrestricted run | `RecordsTests…`, `ConsentTests.trustIsForTheExactTextAndMode`, `StudioModelTests.unrestrictedModeNeedsItsOwnConfirmations` |62| Turning restricted mode off needs an explicit confirmation, once per app launch; restricted mode is ON at every launch | `StudioModelTests.unrestrictedModeNeedsItsOwnConfirmations` |63| Even a script written in this session needs the consent sheet to run unrestricted | same |6465Deliberate usability choice (rule 2 of `PythonConsent`): once the user has reviewed a script in the sheet, or66created it in the current session, the edits they type afterwards run without a new prompt until the app quits.67The trust store is `~/Library/Application Support/ORIX Sheet/python-trust.json` (mode 0600).6869Limit: the trust store and the audit log are ordinary files of the user. A script run **unrestricted** could edit70them (and anything else). A restricted script can neither read nor write them (home directory denied).7172## 5. Restricted mode — what is enforced7374Profile: `PythonSandbox.profile` (SBPL, "allow default, then deny"). If `sandbox-exec` is missing or cannot apply a75profile (checked by really launching a sandboxed `/usr/bin/true` once per launch), **restricted runs are refused**;76they never fall back to unrestricted.77✔ `RestrictedModeTests.restrictedModeRefusesToRunWithoutTheSandbox` (missing launcher and failing launcher: error78`sandboxUnavailable`, marker file not created, audit entry `refused`).7980Every denial below is asserted by `RestrictedModeTests.restrictedModeDeniesWhatItClaims`, and the *same probe81script* is asserted to succeed without the sandbox by `RestrictedModeTests.unrestrictedModeAllowsTheSameThings`82(so the tests measure the sandbox, not an unrelated failure). Independent evidence is checked from the test process:83a local TCP listener counts connections, files are looked up on disk, a victim process is checked alive.8485| Enforced in restricted mode | Observed |86|---|---|87| ✔ No outbound TCP (even to 127.0.0.1), no UDP send, no listening socket (`(deny network*)`, `(deny system-socket)`) | `PermissionError: Operation not permitted`; listener saw 0 connections |88| ✔ No file creation/modification outside the run directory and explicitly granted writable paths: `~/Desktop`, `/tmp/…` denied | `PermissionError`; files absent |89| ✔ Writing inside the run directory (cwd, `TMPDIR`) works; it is deleted after the run | `write_run_dir`, `write_cwd` ok; `runPython` helper asserts removal after every test |90| ✔ No reading of `/Users/**` (the whole home: listing `~`, `~/.ssh`, `~/Library/Keychains`, `~/Documents`, `~/Library/Application Support`), nor of `/private/tmp`, `/Volumes`, nor of the user's per-user temp/cache tree outside the run directory | `PermissionError` for each probed path (`~`, `~/.ssh`, `~/Library/Keychains`, `~/Documents`, `~/Library/Application Support`, `/Volumes`, a directory in `/tmp`) |91| ✔ Explicitly granted paths: `readablePaths` readable but not writable, `writablePaths` writable | `granted_read` ok, `granted_read_write_refused` denied, `granted_write` ok |92| ✔ No other program can be executed: `/usr/bin/curl`, `/bin/ls`, a shell via `os.system`, `/usr/bin/osascript` (`(deny process-exec*)` except the interpreter's own tree) | `PermissionError` |93| ✔ The interpreter may re-execute itself (needed by `multiprocessing`); children inherit the sandbox | `spawn_self` ok |94| ✔ No signal to processes outside the sandbox | `os.kill` → `PermissionError`; victim still alive |95| ✔ Network can be re-enabled only by `PythonRunOptions.allowNetwork` (not exposed in the 1.0 UI); it opens nothing else | `networkCanBeGrantedExplicitly` |96| ✔ The scientific stack works under the profile (numpy, pandas, matplotlib, scipy, statsmodels, scikit-learn, polars, duckdb, pyarrow, sympy) | `scientificStackWorksRestricted` |97| ✔ Works with every interpreter found (Homebrew 3.14, Xcode 3.9, a venv) | `DiscoveryTests.restrictedModeWorksWithEveryDiscoveredInterpreter`, `managedVenvIsCreatedOffline` |9899Also in the profile but **not** covered by a dedicated test (do not present them to users as guarantees):100`(deny mach-lookup)` except a short allow-list (user database, logging, preferences, fonts), `(deny appleevent-send)`,101`(deny lsopen)`, `(deny job-creation)`, and read denials for `/private/var/tmp`, `/Network`, `/Library/Keychains`,102`/private/var/root`.103104## 6. Restricted mode — what is NOT enforced105106- **Reads outside the denied roots.** `/Applications`, `/usr`, `/opt`, `/Library` (except Keychains), `/System`,107  `/private/etc`… remain readable. The script can list running processes through system calls.108- **The workbook.** A script can read every sheet of the open workbook through `orix` (hidden sheets included) and109  print it or write it back into cells. Restricted mode stops it from sending that data over the network or to a110  file, not from reading it.111- **It is not a VM.** `sandbox-exec` is Apple's Seatbelt launcher; Apple marks it deprecated, it still ships and112  works on macOS 27. The script and native extension modules run on the real kernel.113- **Memory.** macOS refuses `RLIMIT_AS`, `RLIMIT_DATA` and `RLIMIT_RSS` for a running interpreter114  ("current limit exceeds maximum limit") and a 600 MB allocation succeeds regardless115  (✔ `addressSpaceLimitIsNotEnforceableButTheWatchdogIs` prints and asserts this). Instead the host samples the116  physical footprint of the script's process tree every 0.2 s and kills it above `maxMemoryBytes` (default 8 GB)117  (✔ same test: 400 MB cap, killed, audit outcome `killed`). A script can overshoot between two samples.118- **Processes that detach.** Termination signals the process group **and** every descendant seen during the run119  (process table sampled every 0.2 s), so `setsid` children that ignore SIGTERM are killed120  (✔ `cancelWithChildProcesses`, restricted and unrestricted). A process that daemonises faster than one sampling121  interval and is re-parented to launchd could survive; in restricted mode it stays inside the sandbox and under122  `RLIMIT_CPU`.123- **Disk space.** A script may fill the run directory up to `RLIMIT_FSIZE` per file (default 1 GB), with no cap on124  the number of files.125- **Unrestricted mode** has no sandbox at all: only §7 and §8 apply. The script has the user's full file and126  network access (subject to macOS TCC prompts attributed to ORIX Sheet).127128## 7. Resource limits (both modes)129130| Limit | Mechanism | Verified by |131|---|---|---|132| Wall-clock time (default 60 s) | host timer → SIGTERM to group + descendants, SIGKILL after 0.5 s | `timeoutKillsTheScript`, `killedWhileHostIsAnswering` |133| Stop button | same termination path, also on Swift task cancellation | `cancelInfiniteLoop`, `cancelSleeping`, `cancelCPUBoundNativeCode`, `cancelIgnoringSIGTERMGetsSIGKILL`, `cancelWithChildProcesses`, `taskCancellationStopsTheScript` (pids checked dead) |134| No orphans after a normal end | group + known descendants SIGKILLed when the interpreter exits | `childrenLeftBehindByAFinishedScriptAreKilled` |135| CPU time (default 300 s per process) | `RLIMIT_CPU` soft = n → SIGXCPU, hard = n+1 → SIGKILL, set by the runner before user code | `cpuLimitIsEnforcedByTheKernel` (restricted and unrestricted) |136| File size (default 1 GB) | `RLIMIT_FSIZE`, hard limit | `fileSizeAndOpenFileLimits` (`EFBIG`) |137| Open files (default 256) | `RLIMIT_NOFILE`, hard limit | same (`EMFILE`) |138| Limits cannot be raised again by the script | soft = hard | same (`setrlimit` refused) |139| Output (default 4 MB stdout+stderr) | host keeps and forwards the first N bytes, drains and drops the rest | `outputIsCappedAndStreamed` |140| Buffered writes | at most 20 000 000 cells per run; each write must fit 1 048 576 × 16 384 | `writesOfPlainPythonTypes`, `malformedMessagesAreIgnored` |141| Core dumps | `RLIMIT_CORE` = 0 | — |142| App quits while a script runs | `PythonRunner.killAllRunningScripts()` (called by FeaturePython on `NSApplication.willTerminate`): SIGKILL to every family, run directories removed | `AppExitTests.quittingTheAppKillsRunningScriptsAndRemovesTheirDirectories` |143| App crashes / is force-quit while a script runs | a watchdog thread in `runner.py` notices the re-parenting within 0.5 s and SIGKILLs the script's process group | `AppExitTests.scriptDoesNotOutliveACrashedApp` (restricted and unrestricted). The run directory of a crashed app is removed by `removeStaleRunDirectories()` at a later launch (after 24 h). A script that blocks the interpreter in native code without releasing the GIL delays this watchdog; `RLIMIT_CPU` still applies. |144145The rlimits are applied by `runner.py` (trusted code) before the user's code is compiled; `.pth` files of the146interpreter's own site-packages run earlier, inside the sandbox in restricted mode.147148## 8. Environment isolation (both modes)149150Launch line: `python -u -X utf8 -I -B runner.py <run-dir>`.151152- `-I`: `PYTHON*` variables ignored (no `PYTHONPATH`, `PYTHONSTARTUP`), no per-user site directory, the script153  directory is not on `sys.path`. Consequence: packages installed with `pip install --user` are not importable154  unless `PythonRunOptions.includeUserSite` is set (not exposed in the 1.0 UI; the launch line stays `-I` and the155  runner adds that single directory with `site.addsitedir`); packages in the interpreter's own156  site-packages (Homebrew, python.org, a venv with its system site-packages) are importable.157- Environment built from an allow-list: `LANG`, `LC_ALL`, `LC_CTYPE`, `TZ` copied; `PATH=/usr/bin:/bin:/usr/sbin:/sbin`,158  `HOME`, `TMPDIR` and `XDG_CACHE_HOME` inside the run directory (`XDG_CACHE_HOME` = `TMPDIR`), `MPLBACKEND=Agg`,159  `MPLCONFIGDIR` inside the run directory, and `ORIX_SHEET=1` (lets a script detect that it runs inside ORIX Sheet).160  `LANG` defaults to `en_US.UTF-8` when the app has none. Caller extras (`PythonRunOptions.extraEnvironment`) are161  applied last and may override these; those starting with `PYTHON` or `DYLD_` are dropped.162- Only fd 0 (/dev/null), 1, 2, 3, 4 are inherited (`POSIX_SPAWN_CLOEXEC_DEFAULT`).163- A fresh 0700 run directory per run, removed afterwards (figures are kept until the caller calls `discard()`).164  The only file that travels between runs is matplotlib's `fontlist-v*.json` cache, copied by the host (regular165  file, < 8 MB, never overwritten once present), with separate copies for restricted and unrestricted runs.166167✔ `environmentIsAnAllowList` (secret variable absent, flags, cwd/HOME/TMPDIR, inherited descriptors, directory168removed), ✔ every `runPython` call asserts no run directory is left, ✔ `staleRunDirectoriesAreSwept`.169170## 9. Protocol robustness171172✔ `malformedMessagesAreIgnored` (non-JSON, unknown operation, wrong shapes, ragged rows, out-of-sheet anchor, a173"figure" outside the run directory: refused, recorded as warnings, channel still usable),174✔ `scriptClosingThePipes`, ✔ `hostErrorsReachTheScript` (host exception → `orix.OrixError`),175✔ `scriptSpammingTheChannelAndExiting`, ✔ `killedWhileHostIsAnswering`.176A figure is accepted only if it is a `.png` directly inside the run's `figures` directory.177Writes are never applied by the engine. The app applies them only when `PythonRunResult.succeeded`, after178re-validating every target and parsing every formula; any invalid item cancels the whole batch179(✔ `WriteApplierTests.anInvalidBatchWritesNothing`, ✔ `StudioModelTests.failedRunWritesNothingAndMarksTheLine`).180A read made after a write in the same run sees the pre-run sheet (✔ `readAfterWriteSeesThePreRunSheet`).181182## 10. Audit log183184`PythonRunner.run` itself appends one JSON line per run — and per refused run — to185`~/Library/Application Support/ORIX Sheet/python-audit.jsonl` (mode 0600, bounded to 4 MB): timestamp, workbook186name, script name, SHA-256 of the code, interpreter path and version, restricted flag, network flag, duration, exit187status, outcome (`ok`, `error`, `timeout`, `cancelled`, `killed`, `refused`), error summary, number of writes.188✔ `RecordsTests.everyRunIsAudited`, plus the outcome assertions in the timeout/cancel/refusal/memory tests.189It is a record for the user, not a tamper-proof log (see §4).190191## 11. Packages192193Listing packages (`PythonEnvironmentManager.listPackages`) reads `importlib.metadata` only and reports each194distribution's install location, `INSTALLER` and provenance (✔ `packageListingHasProvenance`). Creating the managed195venv works offline (✔ `managedVenvIsCreatedOffline`). `PythonEnvironmentManager.install` is the **only** operation196that uses the network: it runs `pip install -- <requirement>` in the managed venv, unsandboxed, and pip executes197the package's build/installation code. The requirement is validated against a strict pattern (no options, URLs,198paths; ✔ `requirementValidation`) and the UI asks for an explicit confirmation that shows the exact command. Real199installs are not exercised by the tests.200
Files main
Menu

Theme