Skip to content

[ML] Add Sandbox2 security integration for PyTorch inference - #2873

Open
valeriy42 wants to merge 56 commits into
elastic:mainfrom
valeriy42:enhancement/sandbox2
Open

[ML] Add Sandbox2 security integration for PyTorch inference#2873
valeriy42 wants to merge 56 commits into
elastic:mainfrom
valeriy42:enhancement/sandbox2

Conversation

@valeriy42

@valeriy42 valeriy42 commented Oct 28, 2025

Copy link
Copy Markdown
Contributor

PyTorch inference runs untrusted TorchScript models supplied by Elasticsearch users, so the native process must be treated as hostile. Today pytorch_inference relies largely on in-process seccomp and graph validation, but that still leaves a large syscall and filesystem surface exposed inside the same address space as libtorch. This PR hardens the Linux production path by spawning pytorch_inference inside Google Sandbox2 from the ML controller, so isolation, syscall policy, and filesystem access are enforced before the model binary starts executing.

The implementation lives primarily in CDetachedProcessSpawner_Linux: controller-spawned pytorch_inference processes get a Sandbox2 policy tailored to the real ES wire-up (named pipes, restore streams, libtorch threading, and long-lived daemon behaviour), while other controller children continue to use the existing posix_spawn path. Build support vendors Abseil and the Sandboxed API on Linux, wires them into CMake, and adds the required license files. Supporting changes cover controller/pytorch command-line handling, clearer IO setup errors, seccomp filter alignment for the legacy path, and a gated --skipModelValidation build option that stays off in distributed builds.

Validation adds Linux unit coverage for the spawner and Sandbox2 spawn path, extends the existing evil-model tests, and introduces an end-to-end attack-defense integration test run from the Docker test entrypoint. CI debugging during development surfaced several practical constraints—clone3 on older build headers, futex operations under load, FIFO visibility across mount namespaces, and Sandbox2’s default wall-time limits on a daemon process—and the policy and spawner logic were adjusted accordingly so sandboxed inference can start and stay up in real ES deployments.

Review sequence recommendation
Review in this order (foundation → integration → tests → docs):

  1. lib/core/CDetachedProcessSpawner_Linux.cc — the new 719-line core; everything else supports it.
  2. lib/core/CDetachedProcessSpawner.cc — the non-Linux baseline, to contrast dispatch/tracking behavior.
  3. lib/seccomp/CSystemCallFilter_Linux.cc — legacy (non-sandboxed) syscall path that must stay coherent with the Sandbox2 policy.
  4. bin/pytorch_inference/Main.cc + bin/pytorch_inference/CCmdLineParser.cc — how the child decides seccomp-vs-sandbox and parses args.
  5. bin/controller/* + lib/api/CIoManager.cc — command-line threading and IO error reporting.
  6. 3rd_party/CMakeLists.txt, cmake/variables.cmake, cmake/functions.cmake, lib/core/CMakeLists.txt — build wiring / SANDBOX2_AVAILABLE gating.
  7. Tests: lib/core/unittest/CDetachedProcessSpawnerTest_Linux.cc, test/test_sandbox2_attack_defense.py, test/evil_model_generator.py.
  8. Docs: docs/changelog/2873.yaml, docs/CHANGELOG.asciidoc, license files.

ES companion PRs:

@prodsecmachine

prodsecmachine commented Oct 28, 2025

Copy link
Copy Markdown

Snyk checks have passed. No issues have been found so far.

Status Scanner Critical High Medium Low Total (0)
Open Source Security 0 0 0 0 0 issues
Licenses 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@valeriy42 valeriy42 changed the title Add Sandbox2 security integration for PyTorch inference [ML] Add Sandbox2 security integration for PyTorch inference Oct 28, 2025
@valeriy42
valeriy42 marked this pull request as draft October 28, 2025 14:00
- Added new tests for Sandbox2 functionality, including privilege validation, filesystem isolation, and syscall filtering.
- Introduced a TestCleanup class for managing temporary files during tests.
- Updated the CDetachedProcessSpawner_Linux.cc to support new command line arguments for log handling and model path.
- Renamed modelDir to modelPath for clarity and adjusted policy building to accommodate file access.
- Improved overall test coverage for Sandbox2 features and ensured graceful degradation when Sandbox2 is not available.
- Improved error handling for cases when Sandbox2 is disabled or unavailable for pytorch_inference processes.
- Enhanced logging to provide clearer feedback on spawning failures with Sandbox2.
- Updated comments for clarity regarding the fallback to standard posix_spawn for non-pytorch_inference processes.
- Added a new function to apply standard ML syscall restrictions using Sandbox2's PolicyBuilder, ensuring consistent security across ML processes.
- Updated the CDetachedProcessSpawner_Linux to utilize the new syscall policy for pytorch_inference, eliminating the need for seccomp filtering in this context.
- Enhanced comments and documentation to outline future migration plans for other ML processes to Sandbox2.
- Noted the gradual transition from seccomp filters to Sandbox2 policies in the CSystemCallFilter_Linux implementation.
- Removed SetUserAndGroup from PolicyBuilder due to updates in the sandboxed-api.
- Updated AddTmpfs to include a size parameter for better resource management.
- Refactored Sandbox2 instantiation to use unique_ptr for the executor, improving memory management.
- Enhanced comments to clarify changes and provide context for future updates.
- Removed outdated syscall number definitions and replaced them with fallback definitions for newer syscalls, ensuring compatibility with RHEL8 headers.
- Updated the handling of input pipes in the sandbox policy to allow read and write access, improving functionality.
- Enhanced comments for better clarity on syscall handling and future maintenance.
@valeriy42 valeriy42 added the ci:run-qa-tests Run a subset of the QA tests label Nov 6, 2025
…for Linux

- Deleted Sandbox2SecurityTest.cc as it is no longer needed.
- Updated CMakeLists.txt to remove references to the deleted test file.
- Introduced CDetachedProcessSpawnerTest_Linux.cc, which includes tests for process spawning and integration with Sandbox2.
- Enhanced CMakeLists.txt to link against Sandbox2 libraries for the new tests.
@valeriy42

Copy link
Copy Markdown
Contributor Author

buildkite run_qa_tests

Broaden the Sandbox2 futex policy beyond WAIT/WAKE so timed condition
variable waits and requeue paths used under sustained inference load are
not SIGSYS-killed. Also raise rlimit_nofile above Sandbox2's default.
…inference daemon

QA reproduction (appex-qa build 883) captured the real Sandbox2 diagnostic
that earlier CI runs lacked: pytorch_inference was being killed with
'Process TIMEOUT' by Sandbox2's default 120s wall-time limit (and 1024s
CPU-time limit), which are designed for run-to-completion sandboxees, not
a daemon that stays up for the lifetime of a deployed model. This surfaces
in Elasticsearch as 'inference native process died unexpectedly ... Unexpected
end of file'. Disarm both limits for pytorch_inference.

Also, while investigating:
- Rework checkForDeadChildren() in both CDetachedProcessSpawner and its
  Linux/Sandbox2 specialisation to waitpid() only tracked PIDs individually,
  rather than waitpid(-1, ...), avoiding interference with the async
  AwaitResult monitor thread used for sandboxed pytorch_inference.
- Restrict /dev mounts in the Sandbox2 policy to the specific device nodes
  needed (null/urandom/random) instead of the whole directory.
- Gate --skipModelValidation behind a new ML_ALLOW_SKIP_MODEL_VALIDATION
  build option (default OFF), so production/distributed builds cannot
  disable model graph validation.
- Make Sandbox2 a hard requirement on Linux (3rd_party/CMakeLists.txt)
  instead of silently disabling it if unavailable.
- Replace the placeholder Sandbox2Test suite (which only checked host
  filesystem permissions) with tests that actually spawn pytorch_inference
  under Sandbox2 and confirm it starts, runs, and terminates cleanly.
- Run the Sandbox2 attack-defense integration test from the Docker test
  entrypoint on Linux.
@valeriy42
valeriy42 force-pushed the enhancement/sandbox2 branch from 714f36a to 0d89fc4 Compare July 21, 2026 10:34
@valeriy42
valeriy42 force-pushed the enhancement/sandbox2 branch from af53f6c to facd362 Compare July 21, 2026 11:11
@valeriy42

Copy link
Copy Markdown
Contributor Author

buildkite run_qa_tests QAF_TESTS_TO_RUN=pytorch_tests

@valeriy42

Copy link
Copy Markdown
Contributor Author

buildkite run_qa_tests

@valeriy42
valeriy42 requested a review from edsavage July 22, 2026 06:58
Keep sandboxed pytorch_inference PIDs killable by tracking them outside the
waitpid reaper, gate in-process seccomp on an ML_SANDBOXED runtime marker,
and fix the attack-defense restore wire format plus leftover debug scaffolding.
@valeriy42
valeriy42 force-pushed the enhancement/sandbox2 branch from 0b7aec4 to 39940cb Compare July 22, 2026 07:50
Keep the harness as a manual local smoke test; CI coverage remains in
CModelGraphValidatorTest and CDetachedProcessSpawnerTest_Linux.
@valeriy42

Copy link
Copy Markdown
Contributor Author

buildkite run_pytorch_tests

Extract the pytorch_inference Sandbox2 policy builder, serialize TMPDIR
env mutation, filter ML_SANDBOXED from non-sandbox spawns, and improve
logging, tests, and maintainer comments for seccomp BPF offsets.
Add INFO-level spawn-context diagnostics, environment self-checks, and
sandbox2::Result capture so deployment failures are triageable from ES
logs alone, and propagate spawn failure reasons back to the controller.
Consume the operator kill-switch flag in macOS and Windows spawners
so it never reaches pytorch_inference, which does not register it.
…t pairing

CCommandProcessor now appends the spawner's failure reason to the START
response, so update the two CCommandProcessorTest expectations. The
non-existent process case asserts only the stable prefix because the exec
error text differs between POSIX (strerror) and Windows (CWindowsError).

Move CPytorchInferenceSyscallAllowlistTest out of the seccomp test
executable. CSystemCallFilterTest installs an irreversible seccomp filter,
and the parallel test runner packs two test cases per process, so any suite
scheduled after it dies with EPERM in Boost's per-test-case sigaltstack
setup. Also hoist sys/syscall.h out of the namespace in the allowlist header.
@valeriy42

Copy link
Copy Markdown
Contributor Author

buildkite run_pytorch_tests

@edsavage

edsavage commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Hi Valeriy, here's my high level first pass. As you suggested I'm starting the review with CDetachedProcessSpawner_Linux.cc. I'm happy overall with the security intent and the QA-driven policy fixes look solid. My main concerns are structure and layering rather than the Sandbox2 approach itself.

Layering - pytorch_inference in lib/core

CDetachedProcessSpawner is a generic permitted-path spawner, but the Linux implementation is deeply coupled to just the one executable (pytorch_inference appears throughout: dispatch via find("pytorch_inference"), policy building, ML_SANDBOXED, log text, etc.). That just doesn’t feel appropriate to belong in lib/core.

If Sandbox2 is genuinely PyTorch specific for now, the policy/dispatch shouldn’t live as hard-coded knowledge inside this library. Maybe we could devise something where the controller (or a dedicated helper it owns) decides Sandbox2 vs legacy spawn and supplies the policy, without core naming a particular binary. The “allowlist before substring check” comment mitigates a bypass, but it doesn’t fix the layering.

The size of spawn(... failureReason)

This overload is very large (~300+ lines). Please consider splitting it, e.g. kill-switch/arg normalisation, sandboxed spawn path, and legacy posix_spawn path (policy builder is already partly extracted, which helps). That would also make a later relocation of the Sandbox2 path easier.

Duplication

CTrackerThread and setupFileActions are largely duplicated across the platform spawner files (with Linux adding sandbox PID tracking). I think it'd be worth extracting the shared POSIX pieces rather than growing a third near-copy. I’d treat that as spawner-internal sharing, not a general-purpose thread utility.

The same for the local joinStrings helpers — CStringUtils::join already exists; the "(none)" empty case can wrap that.

Smaller nits

  • TFilteredEnviron -> SFilteredEnviron (or a small C class): T is for type aliases per the style guide.
  • extractArgDirs / spawn-context mount logging: These belong with the sandbox policy, not as generic spawner free functions. I'd strongly prefer named constants (and reuse the fixed-mount helpers) so that the log text can’t drift from the policy.
  • In a file this #ifdef-heavy, labelling matching #endifs (// SANDBOX2_AVAILABLE, etc.) would help navigation.
  • Optional: compare ML_SANDBOXED to "1" in pytorch_inference rather than “any value set”.

@edsavage edsavage left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Continuing on from the CDetachedProcessSpawner_Linux.cc notes. I'm reviewing the rest of the changes in the recommended review order (baseline -> seccomp -> pytorch -> controller/IO -> build > tests > docs). Tip reviewed: 6fcdecd30.

CDetachedProcessSpawner.cc (non-Linux)

The --disableSandbox stripping and the failureReason overload look good. There is one gap vs Linux: failureReason is set for allowlist/access failures, but not for setupFileActions / posix_spawnattr_init / posix_spawn failures (those only LOG_ERROR). So the controller START responses on macOS will be less informative for those cases.

Seccomp + CPytorchInferenceSyscallAllowlist.h

The BPF jump updates for __NR_dup look consistent, and sandbox2AllowsAllLegacySyscalls() is a nice drift guard. One clarification: the check asserts Sandbox2 is a superset of the legacy BPF, not full equality (Sandbox2 also allows epoll/renameat/prlimit64/etc.). The “keep in sync” wording could say that explicitly so future editors don’t assume a 1:1 list.

pytorch_inference Main + cmdline

  • Seccomp is skipped only when sandboxed. The kill-switch / non-Linux paths still install the filter - this looks correct.
  • Please compare ML_SANDBOXED to "1" rather than getenv(...) != nullptr, so that a stray ML_SANDBOXED=0 can’t disable both Sandbox2 and seccomp. The controller already sets =1.
  • The argv[0]-is-option workaround in CCmdLineParser is fragile. I'd prefer fixing the Executor argv construction (and documenting the Sandbox2 quirk) so this special case can go away. As a related note - inside the sandbox spawn branch, fullArgs is built from args rather than effectiveArgs. These are currently equivalent, but effectiveArgs would be clearer.
  • SANDBOX2_DISABLED is referenced in Main.cc guards but I don’t see it defined anywhere in the repo. Is this an intentional leftover escape hatch, or dead?

It's probably also worth flagging for awareness (related to #3098) the gating of --skipModelValidation behind ML_ALLOW_SKIP_MODEL_VALIDATION (default OFF) means distributed builds won’t recognise the flag ES may still send when graph validation is disabled. It's worth confirming the intended prod behaviour with the ES companion PRs before merge.

Controller + CIoManager

The propagation of spawn failure reasons into START responses is a clear ops win, and the per-pipe CIoManager errors will help with FIFO/mount-namespace failures. The propertiesFile on the controller looks orthogonal to sandboxing - I couldn't quite see why it's necessary - a one-line note on why it’s in this PR would help. The ${SANDBOX2_LIBRARIES} on the controller stays empty on the non-Linux path looks right to me.

Build wiring

The Linux FATAL_ERROR if Sandbox2 isn’t built / unity disabled around Abseil/SAPI / licenses/pins look good.

I'd suggest to save/restore BUILD_SHARED_LIBS in 3rd_party/CMakeLists.txt the same way as BUILD_TESTING / CMAKE_UNITY_BUILD - it’s currently forced OFF and left that way for the rest of configure. Configure-time string(REPLACE) / regex patches to SAPI CMake are acceptable while the GIT_TAG is pinned; a short comment block (or *.patch files) listing “required patches + why” would make the next bump safer.

Tests

As far as I can tell CDetachedProcessSpawnerTest_Linux.cc coverage looks solid (allowlist, substring bypass, kill-switch symlink, sandboxed start). The attack-defense harness is explicitly manual / not in CI - can you please confirm it was run on this tip, and consider a slim CI smoke test (benign start + one denied write) later if feasible. Leaving policy-violation coverage only in a manual harness is the main residual test gap.

Docs / cross-cutting questions

  • The changelog summary is fine. I'd consider mentioning Linux-only + the sandbox_enabled / --disableSandbox kill switch for support.
  • Networking: policy allows __NR_connect without an explicit network-allow helper. Is the Sandbox2 netns empty by default so IP egress is still blocked? If networking isn’t needed, dropping connect (and documenting netns isolation) would shrink the surface.
  • FS mounts: RO /etc + /sys plus RW parent dirs from absolute key=/path args: Can you please confirm why /etc//sys are required, and that ES only passes dedicated pipe dirs into those args.

These are all minor request / nits. My main concerns are the layering / size work from the earlier comment.

@valeriy42

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review, Ed. Addressed below by theme.

--skipModelValidation (regression)

You were right to flag this. The ML_ALLOW_SKIP_MODEL_VALIDATION gate in this PR was a regression: on main the flag is registered unconditionally, but the PR wrapped it in #ifdef with default OFF and no build ever enabling it — so production binaries would reject --skipModelValidation and break graph_validation_enabled: false. Reverted to main behaviour; design discussion continues in #3098.

Layering / structure

Sandbox2 dispatch and policy are relocated out of lib/core:

  • New MlSandbox static library (lib/sandbox/) owns CSandboxedProcessSpawner, CPytorchInferenceSandboxPolicy, and CSandbox2Diagnostics. SANDBOX2_AVAILABLE is scoped here, not on MlCore.
  • CDetachedProcessSpawner is generic POSIX spawn again (no pytorch_inference substring dispatch).
  • CProcessSpawnerRouter in the controller nominates ./pytorch_inference explicitly, strips --disableSandbox, and routes to sandbox vs legacy spawner.

This also subsumes the ~300-line spawn() split you suggested.

Accepted nits

  • ML_SANDBOXED compared to "1" (runtime-only gate in pytorch_inference; removed dead SANDBOX2_DISABLED / SANDBOX2_AVAILABLE compile guards).
  • Removed dead argv[0]-is-option workaround in CCmdLineParser (Executor already passes processPath at index 0).
  • SFilteredEnviron, CStringUtils::join, labelled #endifs, BUILD_SHARED_LIBS save/restore, unconditional BUILD_TESTING restore, SAPI patch rationale comments.
  • Superset wording on syscall allowlist drift guard.
  • Changelog mentions Linux-only + kill switch.
  • Dropped controller propertiesFile (only used by manual harness).
  • macOS failureReason on posix_spawn setup failures.

CI / test coverage (previously vacuous)

The replacement unit test never actually ran: wrong binary path relative to CTest WORKING_DIRECTORY, and silent BOOST_TEST_MESSAGE skips.

Fixed with:

  • New lib/sandbox/unittest suite registered in parallel test runner.
  • ML_SANDBOX2_EXPECT=enforced on aarch64 (re-run outside Docker, following seccomp precedent).
  • ML_SANDBOX2_EXPECT=fail_closed in x86_64 Docker entrypoint.
  • Hard-fail if expectation absent or contradicts unshare(CLONE_NEWUSER) probe.
  • Differential policy-violation test (unsandboxed write succeeds; sandboxed write blocked).
  • Fail-closed test asserts spawn failure names the kill switch.

Manual attack-defense harness was run on earlier tips; CI now has enforcing coverage on aarch64 and fail-closed assertions on x86_64.

Push back (with evidence)

__NR_connect: Sandbox2 default namespace includes CLONE_NEWNET and we never pass UnrestrictedNetworking, so egress is blocked despite connect being allowed. __NR_socket is not on the allowlist. Dropping connect from Sandbox2 alone would break sandbox2AllowsAllLegacySyscalls(); changing both filters is a separate PR. Added netns-isolation comment in policy.

argv[0] workaround: Already fixed at Executor construction; deleted the workaround rather than documenting it.

/etc + /sys mounts: Required for glibc (ld.so.cache, nsswitch.conf, localtime) and libtorch/OpenMP CPU topology under /sys/devices/system/cpu. RW mounts come only from absolute key=/path pipe args via extractArgDirs. Narrowing mounts is a follow-up with its own QA cycle.

Still open / follow-up

  • Slim CI policy-violation smoke in Docker if aarch64-outside-Docker proves flaky on some agents.
  • Follow-up to narrow /etc//sys bind mounts after QA.

@jan-elastic jan-elastic left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. This seems super solid and a huge improvement over the current security model.

Left a bunch of small comments, but nothing blocking.

For the record: I didn't completely parse the syscall lists (I don't know what half of them are, nor why they're needed). Should I invest some time in that?

return joined.empty() ? "(none)" : joined;
}

std::string joinStrings(const std::vector<std::string>& values) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's do

  template <typename Container>
  std::string joinStrings(const Container& values)

instead of the duplication

std::vector<std::string> m_PipeDirAliasMappings;
};

SArgDirExtraction extractArgDirs(const std::vector<std::string>& args) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please document what this method does


SArgDirExtraction extractArgDirs(const std::vector<std::string>& args) {
SArgDirExtraction extraction;
for (const auto& arg : args) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why auto?

I think

for (const string& ...)

is a lot easier to read


std::string path = arg.substr(eqPos + 1);
size_t lastSlash = path.rfind('/');
if (lastSlash == std::string::npos || lastSlash == 0) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

npos isn't possible, because it starts with a slash

return formatted.str();
}
#endif

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why close #ifdef SANDBOX2_AVAILABLE and open a new one?

TStrVec effectiveArgs;
effectiveArgs.reserve(args.size());
for (const auto& arg : args) {
if (arg != "--disableSandbox") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we define this constant nowhere? it's used across multiple files

("cacheMemorylimitBytes", boost::program_options::value<std::size_t>(),
"Optional memory in bytes that the inference cache can use - default is 0 which disables caching")
("validElasticLicenseKeyConfirmed", boost::program_options::value<bool>(),
("validElasticLicenseKeyConfirmed", boost::program_options::value<bool>()->implicit_value(true),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is this?

boost::program_options::store(parsed, vm);
// Workaround for Sandbox2: if argv[0] is an option (Sandbox2 sets it incorrectly),
// parse it as an option using a vector of strings
if (argc > 0 && std::string(argv[0]).substr(0, 2) == "--") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think c++20 has starts_with("--")

.options(desc)
.run();
boost::program_options::store(parsed, vm);
// Workaround for Sandbox2: if argv[0] is an option (Sandbox2 sets it incorrectly),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that's strange? it that a known bug? it so, please add a reference for tracking?


#ifdef SANDBOX2_AVAILABLE
//! Builds the syscall and filesystem policy for a sandboxed pytorch_inference.
//! Keep the syscall allowlist in sync with lib/seccomp/CSystemCallFilter_Linux.cc.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The file is called: CPytorchInferenceSyscallAllowlist.h

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants