diff --git a/cmake/AgenttyTests.cmake b/cmake/AgenttyTests.cmake index 28ce9c9e..a68ea340 100644 --- a/cmake/AgenttyTests.cmake +++ b/cmake/AgenttyTests.cmake @@ -310,8 +310,7 @@ target_compile_definitions(ws_bind_probe PRIVATE # exec_exit_probe: does a (sandboxed) command come back when it exits, or only # at its timeout? Same sources and rationale as ws_bind_probe; run by hand: # cmake --build build --target exec_exit_probe && ./build/exec_exit_probe [on|off] [syscall_mode] -add_executable(exec_exit_probe EXCLUDE_FROM_ALL - ${CMAKE_SOURCE_DIR}/tests/exec_exit_probe.cpp +set(_AGENTTY_EXEC_SANDBOX_SOURCES ${CMAKE_SOURCE_DIR}/tests/sandbox_config_race_stubs.cpp ${CMAKE_SOURCE_DIR}/src/tool/util/sandbox.cpp ${CMAKE_SOURCE_DIR}/src/tool/util/sandbox_claybin.cpp @@ -327,6 +326,9 @@ add_executable(exec_exit_probe EXCLUDE_FROM_ALL ${CMAKE_SOURCE_DIR}/src/util/home_dir.cpp ${CMAKE_SOURCE_DIR}/src/util/user_root.cpp ${CMAKE_SOURCE_DIR}/src/util/teardown.cpp) +add_executable(exec_exit_probe EXCLUDE_FROM_ALL + ${CMAKE_SOURCE_DIR}/tests/exec_exit_probe.cpp + ${_AGENTTY_EXEC_SANDBOX_SOURCES}) target_include_directories(exec_exit_probe PRIVATE ${CMAKE_SOURCE_DIR}/include) target_link_libraries(exec_exit_probe PRIVATE claybin nlohmann_json::nlohmann_json Threads::Threads maya::app) @@ -340,6 +342,27 @@ endif() target_compile_definitions(exec_exit_probe PRIVATE AGENTTY_MCP=0) +# Real native Linux x86_64 multilib enforcement, not a plan/mock test. +# Missing host multilib or sandbox capabilities are explicit CTest skips; +# run sandbox_multilib_test --require to make those failures instead. +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|AMD64)$" + AND NOT CMAKE_CROSSCOMPILING) + add_executable(sandbox_multilib_test + ${CMAKE_SOURCE_DIR}/tests/sandbox_multilib_test.cpp + ${_AGENTTY_EXEC_SANDBOX_SOURCES}) + target_include_directories(sandbox_multilib_test PRIVATE ${CMAKE_SOURCE_DIR}/include) + target_link_libraries(sandbox_multilib_test PRIVATE + claybin nlohmann_json::nlohmann_json Threads::Threads maya::app) + if(TARGET mcp::tools) + target_link_libraries(sandbox_multilib_test PRIVATE mcp::tools) + endif() + target_compile_definitions(sandbox_multilib_test PRIVATE AGENTTY_MCP=0) + agentty_test(sandbox_multilib_test MODE raw TIMEOUT 180 LABELS sandbox multilib) + add_test(NAME sandbox_multilib_test COMMAND sandbox_multilib_test) + set_tests_properties(sandbox_multilib_test PROPERTIES + SKIP_RETURN_CODE 77 TIMEOUT 180 LABELS "sandbox;multilib") +endif() + # sandbox_audit: what does agentty ACTUALLY enforce on THIS host? # # Not a test -- it asserts nothing. It prints the real posture, capability by diff --git a/src/tool/util/sandbox.cpp b/src/tool/util/sandbox.cpp index df1fd1dc..8969cf3a 100644 --- a/src/tool/util/sandbox.cpp +++ b/src/tool/util/sandbox.cpp @@ -406,6 +406,14 @@ void relax_wx_for_jit(claybin_backend::Posture& p, std::string_view cmd) { } #else for (const char* r : kSystemReadRoots) p.system_read_roots.emplace_back(r); +#if defined(__linux__) + // /usr/lib32 (and Debian's /usr/lib/i386-linux-gnu) are already under + // the read-only /usr bind. Separate top-level multilib roots are optional. + for (const char* r : {"/lib32", "/libx32"}) { + std::error_code ec; + if (fs::is_directory(r, ec)) p.system_read_roots.emplace_back(r); + } +#endif for (const char* f : kEtcReadable) p.etc_readable.emplace_back(f); if (cfg.fs_scope == sandbox_cfg::FsScope::Toolchain) { if (const char* home = std::getenv("HOME"); home && *home) { diff --git a/src/tool/util/sandbox_claybin.cpp b/src/tool/util/sandbox_claybin.cpp index 7c2a4049..f2ae094e 100644 --- a/src/tool/util/sandbox_claybin.cpp +++ b/src/tool/util/sandbox_claybin.cpp @@ -42,6 +42,7 @@ #include #include #include +#include #include #include #include @@ -66,6 +67,7 @@ extern "C" char** environ; #include "claybin/policy/profiles.hpp" #if defined(__linux__) +#include "claybin/policy/profiles_i386.hpp" #include #include #include "claybin/broker/notify.hpp" @@ -272,6 +274,25 @@ namespace { // ── the read set, from the SHARED lists ─────────────────────────────── for (const auto& root : p.system_read_roots) { +#if defined(__linux__) + // A bind follows the SOURCE symlink and creates a real directory at + // the destination. Flattening /lib -> usr/lib makes the loader's + // ../lib32/ld-linux.so.2 resolve to /lib32 rather than /usr/lib32. + // Recreate only the well-known merged-/usr aliases; /usr is already + // read-only. Never follow an alias into an unrelated host directory. + if (root == "/bin" || root == "/sbin" || root == "/lib" || + root == "/lib64" || root == "/lib32" || root == "/libx32") { + std::error_code ec; + const auto target = std::filesystem::read_symlink(root, ec); + if (!ec) { + const auto resolved = std::filesystem::canonical(root, ec); + if (!ec && resolved.string().starts_with("/usr/")) { + d = std::move(d).symlink(target.string(), root); + continue; + } + } + } +#endif // /usr and /bin must exist for a shell to run at all; the rest are // best-effort, matching --ro-bind-try. if (root == "/usr" || root == "/bin") @@ -520,6 +541,35 @@ namespace { std::span{kFamilies}, clay::SysAction::errno_, 97 /* EAFNOSUPPORT */); } +#endif +#if defined(__linux__) && defined(__x86_64__) + // Enabling the second ABI is explicit in Claybin; never reinterpret native + // syscall numbers as compatibility numbers. A kernel without IA32 emulation + // still rejects i386 exec with ENOEXEC, without changing native execution. + auto compat = p.syscall_mode == 0 ? SyscallPolicy::everything() + : (p.syscall_mode == 2 && p.net_mode == 1 + ? profiles_i386::compiler() : profiles_i386::compiler_with_network()); + if (p.wx_protect) { + // Legacy mmap hides prot behind a pointer and cannot be inspected. + compat.deny(90, 38 /* ENOSYS */); + for (auto nr : {192u /* mmap2 */, 125u /* mprotect */, 380u /* pkey_mprotect */}) + compat.deny_arg_all(nr, 2, 6, SysAction::errno_, 1); + } else { + for (auto nr : {192u, 125u, 380u}) compat.drop_arg_rules(nr, 2); + } + if (p.syscall_mode != 0) { + static constexpr std::uint32_t families[] = {1, 2, 10}; + compat.allow_arg32_only(359 /* socket */, 0, std::span{families}, + SysAction::errno_, 97); + compat.allow_arg32_only(360 /* socketpair */, 0, std::span{families}, + SysAction::errno_, 97); + // socketcall hides the socket family in guest memory; allowing it would + // bypass the family filter above. Modern i386 libc uses direct calls. + compat.deny(102 /* socketcall */, 38); + } + // Compatibility ptrace/signal calls remain denied, not sent to a broker + // whose syscall decoding currently understands only the native ABI. + d = std::move(d).syscall_profile_i386(std::move(compat)); #endif d = std::move(d).syscall_profile(std::move(sp)); diff --git a/tests/sandbox_multilib_test.cpp b/tests/sandbox_multilib_test.cpp new file mode 100644 index 00000000..dd5560cd --- /dev/null +++ b/tests/sandbox_multilib_test.cpp @@ -0,0 +1,213 @@ +// Native multilib coverage of the shipped set_config -> init -> shell path. +// Run with --require to treat missing host capabilities as failures. +#include "agentty/tool/util/sandbox.hpp" +#include "agentty/tool/util/subprocess.hpp" +#include "agentty/domain/sandbox_config.hpp" +#include "agentty/util/io.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(__linux__) +#include +#endif + +namespace sb = agentty::tools::util::sandbox; +namespace util = agentty::tools::util; +// Same narrow tool-layer stub as exec_exit_probe / sandbox_live_check. +namespace agentty::tools::util { void set_workspace_root(Io, std::filesystem::path); } + +namespace { +std::string quote(const std::string& s) { + std::string out = "'"; + for (char c : s) out += c == '\'' ? "'\\''" : std::string(1, c); + return out + "'"; +} +void save(const std::filesystem::path& p, const char* text) { + std::ofstream f(p); + f << text; + if (!f) throw std::runtime_error("cannot write fixture: " + p.string()); +} +bool expect(const char* label, const util::SubprocessResult& r, int code) { + if (r.started && !r.timed_out && r.exit_code == code) { + std::printf("PASS: %s (exit %d)\n", label, code); + return true; + } + std::fprintf(stderr, "FAIL: %s: started=%d timeout=%d exit=%d expected=%d\n%s%s\n", + label, int(r.started), int(r.timed_out), r.exit_code, code, + r.start_error.c_str(), r.output.c_str()); + return false; +} +int skip(bool require, const std::string& why) { + std::fprintf(stderr, "%s: %s\n", require ? "FAIL (--require)" : "SKIP", why.c_str()); + return require ? 1 : 77; +} +} + +int main(int argc, char** argv) { + bool require = false; + bool explicit_loader = false; + for (int i = 1; i < argc; ++i) { + const std::string arg(argv[i]); + if (arg == "--require") require = true; + else if (arg == "--explicit-loader") explicit_loader = true; + else { + std::fprintf(stderr, "usage: %s [--require] [--explicit-loader]\n", argv[0]); + return 1; + } + } +#if !defined(__linux__) || !defined(__x86_64__) + return skip(require, "requires native Linux x86_64"); +#else + std::string pattern = (std::filesystem::current_path() / "agentty-multilib-XXXXXX").string(); + const char* made = ::mkdtemp(pattern.data()); + if (!made) { std::perror("mkdtemp"); return 1; } + const std::filesystem::path root(made); + struct Cleanup { + std::filesystem::path p; + ~Cleanup() { + std::error_code ec; + std::filesystem::remove_all(p, ec); + std::filesystem::remove(p.string() + "-outside", ec); + } + } cleanup{root}; + try { + const std::string outside = root.string() + "-outside"; + save(outside, "host-writable sentinel\n"); + const auto host = [&](const std::string& cmd) { + return util::run_command_s("cd " + quote(root.string()) + " && " + cmd, + 64 * 1024, std::chrono::seconds{30}); + }; + // Do not customize PT_INTERP: the system's default i386 loader is the regression. + save(root / "baseline.c", "int main(void) { return 42; }\n"); + if (!expect("compile native baseline", host("gcc -m64 baseline.c -o baseline64"), 0)) return 1; + if (!expect("host native baseline", host("./baseline64"), 42)) return 1; + + save(root / "library.c", "int multilib_answer(void) { return 42; }\n"); + save(root / "dynamic.c", R"C( +#include +int main(void) { + void *h = dlopen("./libmultilib.so", RTLD_NOW); + if (!h) return 10; + int (*answer)(void) = (int (*)(void))dlsym(h, "multilib_answer"); + if (!answer) return 11; + int result = answer(); + return dlclose(h) == 0 ? result : 12; +} +)C"); + save(root / "restrictions.c", R"C( +#include +#include +#include +#include +#include +#include +#include +static int denied(void) { return errno == EPERM || errno == EACCES || errno == EROFS; } +int main(int argc, char **argv) { + if (argc != 3) return 20; + if (!strcmp(argv[1], "write")) { + int fd = open("workspace-write", O_WRONLY | O_CREAT | O_TRUNC, 0600); + if (fd < 0 || write(fd, "ok", 2) != 2 || close(fd)) return 21; + fd = open(argv[2], O_WRONLY | O_TRUNC); + if (fd >= 0) { close(fd); return 22; } + return denied() ? 0 : 23; + } + if (!strcmp(argv[1], "unshare")) { + (void)syscall(SYS_unshare, CLONE_NEWUSER); + return 24; /* Hard denied in both ABIs, not a brokered syscall. */ + } + if (!strcmp(argv[1], "rwx")) { + void *p = mmap(0, 4096, PROT_READ | PROT_WRITE | PROT_EXEC, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (p != MAP_FAILED) { munmap(p, 4096); return 25; } + return denied() ? 0 : 26; + } + if (!strcmp(argv[1], "mprotect")) { + void *p = mmap(0, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (p == MAP_FAILED) return 27; + errno = 0; + int ok = mprotect(p, 4096, PROT_READ | PROT_WRITE | PROT_EXEC) == -1 && denied(); + munmap(p, 4096); + return ok ? 0 : 28; + } + return 29; +} +)C"); + if (!expect("compile native restrictions", host("gcc -m64 restrictions.c -o restrictions64"), 0)) return 1; + + util::set_workspace_root(agentty::IoAccess::grant(), root); + agentty::sandbox_cfg::Config cfg; // Default balanced/compiler policy; no relaxed syscall overrides. + cfg.configured = true; + // Visible and host-writable, but deliberately not in write_paths. + cfg.read_paths.push_back(outside); + cfg.net_mode = agentty::sandbox_cfg::NetMode::None; + sb::set_config(cfg); + if (!sb::init(sb::Mode::On) || !sb::is_active()) + return skip(require, "real sandbox unavailable: " + sb::describe_state()); + if (sb::requested_mode() != sb::Mode::On || sb::detected_backend() != sb::Backend::Claybin) { + std::fprintf(stderr, "FAIL: expected Mode::On and claybin: %s\n", sb::describe_state().c_str()); + return 1; + } + const auto sandbox = [&](const std::string& cmd) { + return sb::run_shell_command("cd " + quote(root.string()) + " && " + cmd, + 64 * 1024, std::chrono::seconds{30}); + }; + // Once init claims a real backend, execution failures are not downgraded to skips. + bool ok = expect("sandbox native baseline", sandbox("./baseline64"), 42); + const auto restrictions = [&](const char* bits) { + bool passed = true; + for (const char* check : {"write", "rwx", "mprotect"}) { + const std::string cmd = "./restrictions" + std::string(bits) + " " + check + " " + quote(outside); + passed = expect(cmd.c_str(), sandbox(cmd), 0) && passed; + } + // unshare is deliberately KILL in both profiles: SIGSYS maps to 159. + const std::string cmd = "./restrictions" + std::string(bits) + " unshare " + quote(outside); + return expect(cmd.c_str(), sandbox(cmd), 159) && passed; + }; + ok = restrictions("64") && ok; + if (!ok) return 1; + + // Only i386 coverage may be skipped after the native sandbox checks pass. + const auto multilib = host("gcc -m32 baseline.c -o baseline32"); + if (!multilib.started || multilib.timed_out) { + expect("multilib compiler invocation", multilib, 0); + return 1; + } + if (multilib.exit_code != 0) + return skip(require, "i386 coverage only: gcc -m32 cannot build the minimal libc fixture:\n" + multilib.output); + const auto runtime = host("./baseline32"); + if (runtime.started && !runtime.timed_out && + (runtime.exit_code == 126 || runtime.exit_code == 127)) { + if (explicit_loader) { + std::fprintf(stderr, "DIAGNOSTIC ONLY: explicit loader does not satisfy default-interpreter coverage\n"); + const auto compiled = host("gcc -m32 baseline.c -Wl,--dynamic-linker=/usr/lib32/ld-linux.so.2 -o diagnostic32"); + if (expect("diagnostic explicit-loader compile", compiled, 0) && + expect("diagnostic explicit-loader host baseline", host("./diagnostic32"), 42)) + expect("diagnostic explicit-loader sandbox baseline", sandbox("./diagnostic32"), 42); + } + return skip(require, "i386 coverage only: host cannot execute default-interpreter ELF (kernel/loader unavailable):\n" + runtime.output); + } + if (!expect("host i386 baseline", runtime, 42)) return 1; + // After the capability probe, fixture failures are never capability skips. + for (const auto& cmd : std::vector{ + "gcc -m32 -fPIC -shared library.c -o libmultilib.so", + "gcc -m32 dynamic.c -ldl -o dynamic32", + "gcc -m32 restrictions.c -o restrictions32"}) + if (!expect(cmd.c_str(), host(cmd), 0)) return 1; + if (!expect("host i386 dlopen", host("./dynamic32"), 42)) return 1; + ok = expect("sandbox default-interpreter i386 baseline", sandbox("./baseline32"), 42) && ok; + ok = expect("sandbox i386 dlopen shared library", sandbox("./dynamic32"), 42) && ok; + ok = restrictions("32") && ok; + return ok ? 0 : 1; + } catch (const std::exception& e) { + std::fprintf(stderr, "FAIL: %s\n", e.what()); + return 1; + } +#endif +} diff --git a/third_party/claybin b/third_party/claybin index a4f876b3..4b4d2c34 160000 --- a/third_party/claybin +++ b/third_party/claybin @@ -1 +1 @@ -Subproject commit a4f876b3e4fcaa8f99c8f6ecd108634402d8ae38 +Subproject commit 4b4d2c347c45aef994fadb620002ea5036ae1b93