Truly independent web browser
LibSandbox: Broker file access on kernels without Landlock
Andreas Kling93fb09ccfd45
diff --git a/.github/actions/build/action.yml b/.github/actions/build/action.ymlindex 7ec068f40db..e6cf12435e1 100644--- a/.github/actions/build/action.yml+++ b/.github/actions/build/action.yml@@ -35,17 +35,6 @@ inputs:runs:using: 'composite'steps:- # FIXME: The kernel of our Linux runners is built without Landlock, and helpers refuse to run without it. Remove this- # once the runners have Landlock, so that CI tests the sandbox that users get.- - name: Check for Landlock- if: ${{ inputs.os == 'Linux' }}- shell: bash- run: |- if ! python3 -c 'import ctypes, sys; sys.exit(0 if ctypes.CDLL(None, use_errno=True).syscall(444, None, 0, 1) > 0 else 1)'; then- echo "::warning::This kernel has no Landlock, so the helpers run without file system confinement. The rest of the sandbox still applies."- echo "LADYBIRD_UNSAFE_ALLOW_MISSING_LANDLOCK=1" >> "$GITHUB_ENV"- fi-- name: Set Up Environmentuses: ./.github/actions/setupid: 'setup'diff --git a/Documentation/ProcessArchitecture.md b/Documentation/ProcessArchitecture.mdindex c19691d68a7..8551a09151b 100644--- a/Documentation/ProcessArchitecture.md+++ b/Documentation/ProcessArchitecture.md@@ -114,7 +114,7 @@ A renderer that needs a helper it does not have yet asks **Hub** for a connectioEvery process in the table above except **UI** and **Hub** applies a sandbox to itself early in its startup, unless **Hub** was started with `--disable-sandbox`. Each one's sandbox allows only what that process needs, and can be found in the `Sandbox` files in its directory under `Services`. The one of **WebContent** is in `Services/RendererSandbox.h`.-On Linux, sandboxes are built from seccomp and Landlock. On macOS, they use the Seatbelt sandbox. Windows has no sandbox yet.+On Linux, sandboxes are built from seccomp and Landlock. On kernels without Landlock, seccomp traps every system call that takes a path, and a broker process forked from the helper carries out the ones that the helper's path list permits. On macOS, they use the Seatbelt sandbox. Windows has no sandbox yet.## Class overviewdiff --git a/Libraries/LibSandbox/CMakeLists.txt b/Libraries/LibSandbox/CMakeLists.txtindex 5c940a5b80b..71e5859df0d 100644--- a/Libraries/LibSandbox/CMakeLists.txt+++ b/Libraries/LibSandbox/CMakeLists.txt@@ -5,6 +5,7 @@ set(SOURCESif (LINUX)list(APPEND SOURCES+ FileBroker.cppGpuDriverPaths.cppSeccomp.cpp)diff --git a/Libraries/LibSandbox/FileBroker.cpp b/Libraries/LibSandbox/FileBroker.cppnew file mode 100644index 00000000000..bd51355eeae--- /dev/null+++ b/Libraries/LibSandbox/FileBroker.cpp@@ -0,0 +1,790 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/ByteString.h>+#include <AK/Noncopyable.h>+#include <AK/ScopeGuard.h>+#include <AK/StringBuilder.h>+#include <AK/Vector.h>+#include <LibSandbox/FileBroker.h>+#include <LibSandbox/Seccomp.h>+#include <dirent.h>+#include <errno.h>+#include <fcntl.h>+#include <signal.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/prctl.h>+#include <sys/socket.h>+#include <sys/stat.h>+#include <sys/syscall.h>+#include <unistd.h>++namespace Sandbox {++using namespace Detail;++static int s_file_broker_socket = -1;++int Detail::file_broker_socket()+{+ return s_file_broker_socket;+}++bool file_broker_is_active()+{+ return s_file_broker_socket >= 0;+}++static bool is_same_or_beneath(StringView path, StringView ancestor)+{+ if (path == ancestor || ancestor == "/"sv)+ return true;+ return path.length() > ancestor.length() && path.starts_with(ancestor) && path[ancestor.length()] == '/';+}++bool file_broker_allows(ReadonlySpan<ResolvedPathRule> rules, StringView canonical_path, FileBrokerAccess access)+{+ for (auto const& rule : rules) {+ StringView rule_path = rule.resolved_path;++ if (access == FileBrokerAccess::ChangeEntry) {+ if (rule.is_directory && rule.access == PathRule::Access::ReadWrite && canonical_path != rule_path && is_same_or_beneath(canonical_path, rule_path))+ return true;+ continue;+ }++ auto covered = rule.is_directory ? is_same_or_beneath(canonical_path, rule_path) : canonical_path == rule_path;+ if (covered) {+ if (access != FileBrokerAccess::Write || rule.access == PathRule::Access::ReadWrite)+ return true;+ }++ if (access == FileBrokerAccess::Metadata && (is_same_or_beneath(rule_path, canonical_path) || is_same_or_beneath(rule.requested_path, canonical_path)))+ return true;+ }+ return false;+}++namespace {++enum class WalkMode {+ FollowLast,+ StayOnLast,+ StopBeforeLast,+};++// Walks a path one component at a time without ever following a symbolic link inside the kernel. The helper can change+// the files in a directory it may write to, so a path checked first and opened afterwards could lead somewhere else by+// the time it is opened. Here, the descriptor that is checked is the one that gets used.+class PathWalker {+ AK_MAKE_NONCOPYABLE(PathWalker);++public:+ explicit PathWalker(pid_t helper_pid)+ : m_helper_pid(helper_pid)+ {+ }++ ~PathWalker()+ {+ for (auto fd : m_directories)+ close(fd);+ }++ int walk(StringView absolute_path, WalkMode mode)+ {+ // A trailing slash asks for what the link leads to, even from a system call that otherwise stays on the link.+ if (mode == WalkMode::StayOnLast && absolute_path.ends_with('/'))+ mode = WalkMode::FollowLast;++ auto root = open("/", O_PATH | O_DIRECTORY | O_CLOEXEC);+ if (root < 0)+ return errno;+ m_directories.append(root);+ if (fstat(root, &m_stat) < 0)+ return errno;++ Vector<ByteString> pending;+ push_components(pending, absolute_path);++ size_t followed_links = 0;+ while (!pending.is_empty()) {+ auto name = pending.take_last();+ if (name == ".."sv) {+ if (!m_names.is_empty()) {+ close(m_directories.take_last());+ m_names.take_last();+ if (auto error = refresh_stat(); error != 0)+ return error;+ }+ continue;+ }++ auto is_last = pending.is_empty();+ if (is_last && mode == WalkMode::StopBeforeLast) {+ m_last_name = name;+ return 0;+ }++ // The broker is a process of its own, so what the helper calls /proc/self has to be spelled out.+ if (is_directly_in_proc() && name == "self"sv) {+ name = ByteString::number(m_helper_pid);+ m_ended_on_proc_self = is_last;+ } else if (is_directly_in_proc() && name == "thread-self"sv) {+ return fail_at(name, ENOENT);+ }++ auto fd = openat(m_directories.last(), name.characters(), O_PATH | O_NOFOLLOW | O_CLOEXEC);+ if (fd < 0)+ return fail_at(name, errno);++ struct stat statbuf;+ if (fstat(fd, &statbuf) < 0) {+ auto error = errno;+ close(fd);+ return fail_at(name, error);+ }++ if (S_ISLNK(statbuf.st_mode) && !(is_last && mode == WalkMode::StayOnLast)) {+ char target[PATH_MAX];+ auto length = readlinkat(fd, "", target, sizeof(target));+ auto error = errno;+ close(fd);+ if (length < 0)+ return fail_at(name, error);+ if (static_cast<size_t>(length) == sizeof(target))+ return fail_at(name, ENAMETOOLONG);+ if (++followed_links > 40)+ return fail_at(name, ELOOP);++ StringView target_view { target, static_cast<size_t>(length) };+ if (target_view.starts_with('/')) {+ while (!m_names.is_empty()) {+ close(m_directories.take_last());+ m_names.take_last();+ }+ if (auto error = refresh_stat(); error != 0)+ return error;+ }+ push_components(pending, target_view);+ continue;+ }++ m_directories.append(fd);+ m_names.append(move(name));+ m_stat = statbuf;+ }++ // There was nothing before the last component to stop at, as in a request for the root directory itself.+ if (mode == WalkMode::StopBeforeLast)+ return EEXIST;++ // A trailing slash only ever names a directory.+ if (absolute_path.ends_with('/') && !S_ISDIR(m_stat.st_mode)) {+ m_failed_path = canonical_path();+ return ENOTDIR;+ }+ return 0;+ }++ ByteString canonical_path() const+ {+ if (m_names.is_empty())+ return "/"sv;+ StringBuilder builder;+ for (auto const& name : m_names) {+ builder.append('/');+ builder.append(name);+ }+ return builder.to_byte_string();+ }++ ByteString canonical_path_with_last_name() const { return join(canonical_path(), m_last_name); }+ ByteString const& failed_path() const { return m_failed_path; }+ ByteString const& last_name() const { return m_last_name; }+ bool ended_on_proc_self() const { return m_ended_on_proc_self; }+ int fd() const { return m_directories.last(); }+ struct stat const& stat_result() const { return m_stat; }++private:+ static ByteString join(StringView directory, StringView name)+ {+ if (directory == "/"sv)+ return ByteString::formatted("/{}", name);+ return ByteString::formatted("{}/{}", directory, name);+ }++ static void push_components(Vector<ByteString>& pending, StringView path)+ {+ auto parts = path.split_view('/');+ for (auto const& part : parts.in_reverse()) {+ if (part != "."sv)+ pending.append(part);+ }+ }++ bool is_directly_in_proc() const { return m_names.size() == 1 && m_names.first() == "proc"sv; }++ // Leaving a directory by any way other than a new component has to report the directory that we ended up in.+ int refresh_stat()+ {+ return fstat(m_directories.last(), &m_stat) < 0 ? errno : 0;+ }++ int fail_at(StringView name, int error)+ {+ m_failed_path = join(canonical_path(), name);+ return error;+ }++ pid_t m_helper_pid { 0 };+ Vector<int> m_directories;+ Vector<ByteString> m_names;+ ByteString m_last_name;+ ByteString m_failed_path;+ bool m_ended_on_proc_self { false };+ struct stat m_stat {};+};++class FileBrokerServer {+public:+ FileBrokerServer(Vector<ResolvedPathRule> rules, pid_t helper_pid, ByteString current_directory)+ : m_rules(move(rules))+ , m_helper_pid(helper_pid)+ , m_current_directory(move(current_directory))+ {+ }++ void serve(int socket);++private:+ struct Result {+ int error { 0 };+ int fd { -1 };+ };++ bool allows(StringView path, FileBrokerAccess access) const { return file_broker_allows(m_rules, path, access); }++ // A path outside of what the helper can see has to look the same whether or not it exists.+ int failure_for(PathWalker const& walker, int error) const+ {+ return allows(walker.failed_path(), FileBrokerAccess::Metadata) ? error : EACCES;+ }++ ErrorOr<ByteString> absolute_path(StringView path, int directory_fd) const;++ Result open_file(StringView path, int flags, u32 mode);+ Result reopen(PathWalker const&, int flags);+ int access_file(StringView path, int mode, u32 at_flags);+ int stat_file(StringView path, bool follow, struct stat& result);+ int read_link(StringView path, char* buffer, u32& length);+ int make_directory(StringView path, u32 mode);+ int remove(StringView path, bool directory);+ int rename_file(StringView old_path, StringView new_path);+ int bind_socket(int fd, char const* address, u32 length);++ void handle(FileBrokerRequest const&, int directory_fds[2], int reply_fd);++ Vector<ResolvedPathRule> m_rules;+ pid_t m_helper_pid { 0 };+ ByteString m_current_directory;+};++}++// Relative paths start from the directory that the helper named with a descriptor, or else from its working directory.+ErrorOr<ByteString> FileBrokerServer::absolute_path(StringView path, int directory_fd) const+{+ if (path.is_empty())+ return Error::from_errno(ENOENT);+ if (path.starts_with('/'))+ return ByteString { path };+ if (directory_fd < 0) {+ if (m_current_directory.is_empty())+ return Error::from_errno(ENOENT);+ return ByteString::formatted("{}/{}", m_current_directory, path);+ }++ char link[32];+ (void)snprintf(link, sizeof(link), "/proc/self/fd/%d", directory_fd);+ char directory[PATH_MAX];+ auto length = readlink(link, directory, sizeof(directory));+ if (length < 0)+ return Error::from_errno(errno);+ if (static_cast<size_t>(length) == sizeof(directory))+ return Error::from_errno(ENAMETOOLONG);+ // A socket or a pipe has a name too, but no file system path to start from.+ if (length == 0 || directory[0] != '/')+ return Error::from_errno(ENOTDIR);+ return ByteString::formatted("{}/{}", StringView { directory, static_cast<size_t>(length) }, path);+}++// Goes through the descriptor of the file that was checked, so the open cannot land on any other file.+FileBrokerServer::Result FileBrokerServer::reopen(PathWalker const& walker, int flags)+{+ char link[32];+ (void)snprintf(link, sizeof(link), "/proc/self/fd/%d", walker.fd());+ auto fd = open(link, (flags & ~(O_CREAT | O_EXCL | O_NOFOLLOW)) | O_CLOEXEC);+ if (fd < 0)+ return { errno, -1 };+ return { 0, fd };+}++FileBrokerServer::Result FileBrokerServer::open_file(StringView path, int flags, u32 mode)+{+ // A nameless temporary file needs a directory that the rules say nothing about, and callers can do without one.+ if ((flags & O_TMPFILE) == O_TMPFILE)+ return { EOPNOTSUPP, -1 };++ auto access_mode = flags & O_ACCMODE;+ // O_CREAT writes nothing to a file that already exists, and the path that makes a new one has its own check.+ auto wants_write = access_mode != O_RDONLY || (flags & O_TRUNC) != 0;+ auto needed = wants_write ? FileBrokerAccess::Write : FileBrokerAccess::Read;++ auto creates_exclusively = (flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);+ auto stay_on_last = (flags & O_NOFOLLOW) != 0 || creates_exclusively;+ {+ PathWalker walker { m_helper_pid };+ auto error = walker.walk(path, stay_on_last ? WalkMode::StayOnLast : WalkMode::FollowLast);+ if (error == 0) {+ if ((flags & O_PATH) != 0 ? !allows(walker.canonical_path(), FileBrokerAccess::Metadata) : !allows(walker.canonical_path(), needed))+ return { EACCES, -1 };+ if (creates_exclusively)+ return { EEXIST, -1 };+ if (S_ISLNK(walker.stat_result().st_mode) && (flags & O_PATH) == 0)+ return { ELOOP, -1 };+ return reopen(walker, flags);+ }+ if (error != ENOENT || (flags & O_CREAT) == 0)+ return { failure_for(walker, error), -1 };+ }++ if (path.ends_with('/'))+ return { EISDIR, -1 };++ PathWalker walker { m_helper_pid };+ if (auto error = walker.walk(path, WalkMode::StopBeforeLast); error != 0)+ return { failure_for(walker, error), -1 };+ if (!allows(walker.canonical_path_with_last_name(), FileBrokerAccess::ChangeEntry))+ return { EACCES, -1 };++ auto fd = openat(walker.fd(), walker.last_name().characters(), flags | O_NOFOLLOW | O_CLOEXEC, mode);+ if (fd < 0)+ return { errno, -1 };+ return { 0, fd };+}++int FileBrokerServer::access_file(StringView path, int mode, u32 at_flags)+{+ PathWalker walker { m_helper_pid };+ if (auto error = walker.walk(path, (at_flags & AT_SYMLINK_NOFOLLOW) ? WalkMode::StayOnLast : WalkMode::FollowLast); error != 0)+ return failure_for(walker, error);++ auto needed = FileBrokerAccess::Metadata;+ if (mode & W_OK)+ needed = FileBrokerAccess::Write;+ else if (mode & (R_OK | X_OK))+ needed = FileBrokerAccess::Read;+ if (!allows(walker.canonical_path(), needed))+ return EACCES;++ char link[32];+ (void)snprintf(link, sizeof(link), "/proc/self/fd/%d", walker.fd());+ return access(link, mode) < 0 ? errno : 0;+}++int FileBrokerServer::stat_file(StringView path, bool follow, struct stat& result)+{+ PathWalker walker { m_helper_pid };+ if (auto error = walker.walk(path, follow ? WalkMode::FollowLast : WalkMode::StayOnLast); error != 0)+ return failure_for(walker, error);+ if (!allows(walker.canonical_path(), FileBrokerAccess::Metadata))+ return EACCES;+ result = walker.stat_result();+ return 0;+}++int FileBrokerServer::read_link(StringView path, char* buffer, u32& length)+{+ PathWalker walker { m_helper_pid };+ if (auto error = walker.walk(path, WalkMode::StayOnLast); error != 0)+ return failure_for(walker, error);+ if (!allows(walker.canonical_path(), FileBrokerAccess::Metadata))+ return EACCES;++ // The walk replaced this link with the helper's own directory, but the link is what the helper asked about.+ if (walker.ended_on_proc_self()) {+ auto helper_pid = ByteString::number(m_helper_pid);+ memcpy(buffer, helper_pid.characters(), helper_pid.length());+ length = static_cast<u32>(helper_pid.length());+ return 0;+ }++ if (!S_ISLNK(walker.stat_result().st_mode))+ return EINVAL;++ auto result = readlinkat(walker.fd(), "", buffer, PATH_MAX);+ if (result < 0)+ return errno;+ length = static_cast<u32>(result);+ return 0;+}++int FileBrokerServer::make_directory(StringView path, u32 mode)+{+ PathWalker walker { m_helper_pid };+ if (auto error = walker.walk(path, WalkMode::StopBeforeLast); error != 0)+ return failure_for(walker, error);++ // The kernel reports a directory that exists before it asks whether a new one could be made there, and libpulse+ // depends on that for a runtime directory that it may only read.+ auto target = walker.canonical_path_with_last_name();+ if (!allows(target, FileBrokerAccess::ChangeEntry)) {+ struct stat statbuf;+ if (allows(target, FileBrokerAccess::Metadata) && fstatat(walker.fd(), walker.last_name().characters(), &statbuf, AT_SYMLINK_NOFOLLOW) == 0)+ return EEXIST;+ return EACCES;+ }+ return mkdirat(walker.fd(), walker.last_name().characters(), mode) < 0 ? errno : 0;+}++int FileBrokerServer::remove(StringView path, bool directory)+{+ PathWalker walker { m_helper_pid };+ if (auto error = walker.walk(path, WalkMode::StopBeforeLast); error != 0)+ return failure_for(walker, error);+ if (!allows(walker.canonical_path_with_last_name(), FileBrokerAccess::ChangeEntry))+ return EACCES;+ return unlinkat(walker.fd(), walker.last_name().characters(), directory ? AT_REMOVEDIR : 0) < 0 ? errno : 0;+}++int FileBrokerServer::rename_file(StringView old_path, StringView new_path)+{+ PathWalker old_walker { m_helper_pid };+ if (auto error = old_walker.walk(old_path, WalkMode::StopBeforeLast); error != 0)+ return failure_for(old_walker, error);+ PathWalker new_walker { m_helper_pid };+ if (auto error = new_walker.walk(new_path, WalkMode::StopBeforeLast); error != 0)+ return failure_for(new_walker, error);++ if (!allows(old_walker.canonical_path_with_last_name(), FileBrokerAccess::ChangeEntry) || !allows(new_walker.canonical_path_with_last_name(), FileBrokerAccess::ChangeEntry))+ return EACCES;+ return renameat(old_walker.fd(), old_walker.last_name().characters(), new_walker.fd(), new_walker.last_name().characters()) < 0 ? errno : 0;+}++// Binding a UNIX socket to a path creates a file that no path rule covers, so only the families that the network policies+// exist for get through. The kernel refuses an address whose family differs from the socket's own, and the address was+// copied out of the helper before this check, so the helper can't change it afterwards.+int FileBrokerServer::bind_socket(int fd, char const* address, u32 length)+{+ sockaddr_storage storage;+ if (fd < 0 || length < sizeof(sa_family_t) || length > sizeof(storage))+ return EINVAL;+ memcpy(&storage, address, length);+ if (storage.ss_family != AF_INET && storage.ss_family != AF_INET6 && storage.ss_family != AF_NETLINK)+ return EACCES;+ return bind(fd, reinterpret_cast<sockaddr const*>(&storage), length) < 0 ? errno : 0;+}++static void send_response(int reply_fd, FileBrokerResponse const& response, int fd)+{+ iovec io {+ .iov_base = const_cast<FileBrokerResponse*>(&response),+ .iov_len = sizeof(response),+ };++ union {+ cmsghdr header;+ char space[CMSG_SPACE(sizeof(int))];+ } control {};++ msghdr message {+ .msg_name = nullptr,+ .msg_namelen = 0,+ .msg_iov = &io,+ .msg_iovlen = 1,+ .msg_control = nullptr,+ .msg_controllen = 0,+ .msg_flags = 0,+ };++ if (fd >= 0) {+ message.msg_control = &control;+ message.msg_controllen = sizeof(control);+ auto* header = CMSG_FIRSTHDR(&message);+ header->cmsg_level = SOL_SOCKET;+ header->cmsg_type = SCM_RIGHTS;+ header->cmsg_len = CMSG_LEN(sizeof(int));+ memcpy(CMSG_DATA(header), &fd, sizeof(fd));+ }++ // Never wait on a socket that the helper chose. If its buffer is full, the helper did that to itself.+ ssize_t sent = 0;+ do {+ sent = sendmsg(reply_fd, &message, MSG_NOSIGNAL | MSG_DONTWAIT);+ } while (sent < 0 && errno == EINTR);+}++void FileBrokerServer::handle(FileBrokerRequest const& request, int directory_fds[2], int reply_fd)+{+ FileBrokerResponse response;+ memset(&response, 0, sizeof(response));+ response.magic = file_broker_magic;++ int result_fd = -1;+ ScopeGuard send_and_close = [&] {+ send_response(reply_fd, response, result_fd);+ if (result_fd >= 0)+ close(result_fd);+ };++ if (static_cast<FileBrokerOperation>(request.operation) == FileBrokerOperation::BindSocket) {+ response.error = bind_socket(directory_fds[0], request.path, request.path_length);+ return;+ }++ StringView raw_path { request.path, request.path_length };+ StringView raw_second_path { request.second_path, request.second_path_length };+ if (raw_path.contains('\0') || raw_second_path.contains('\0')) {+ response.error = EINVAL;+ return;+ }++ auto path_or_error = absolute_path(raw_path, directory_fds[0]);+ if (path_or_error.is_error()) {+ response.error = path_or_error.error().code();+ return;+ }+ auto path = path_or_error.release_value();++ switch (static_cast<FileBrokerOperation>(request.operation)) {+ case FileBrokerOperation::Open: {+ auto result = open_file(path, request.flags, request.mode);+ response.error = result.error;+ result_fd = result.fd;+ return;+ }+ case FileBrokerOperation::Access:+ response.error = access_file(path, request.flags, request.mode);+ return;+ case FileBrokerOperation::Stat:+ response.error = stat_file(path, true, response.stat_result);+ return;+ case FileBrokerOperation::SymlinkStat:+ response.error = stat_file(path, false, response.stat_result);+ return;+ case FileBrokerOperation::ReadLink:+ response.error = read_link(path, response.link, response.link_length);+ return;+ case FileBrokerOperation::MakeDirectory:+ response.error = make_directory(path, request.mode);+ return;+ case FileBrokerOperation::RemoveFile:+ response.error = remove(path, false);+ return;+ case FileBrokerOperation::RemoveDirectory:+ response.error = remove(path, true);+ return;+ case FileBrokerOperation::BindSocket:+ VERIFY_NOT_REACHED();+ case FileBrokerOperation::Rename: {+ auto second_or_error = absolute_path(raw_second_path, directory_fds[1]);+ if (second_or_error.is_error()) {+ response.error = second_or_error.error().code();+ return;+ }+ response.error = rename_file(path, second_or_error.value());+ return;+ }+ }+ response.error = EINVAL;+}++void FileBrokerServer::serve(int socket)+{+ static FileBrokerRequest request;++ for (;;) {+ iovec io {+ .iov_base = &request,+ .iov_len = sizeof(request),+ };++ // Room for more than a well-behaved helper sends, so that anything extra can be counted and closed.+ union {+ cmsghdr header;+ char space[CMSG_SPACE(4 * sizeof(int))];+ } control {};++ msghdr message {+ .msg_name = nullptr,+ .msg_namelen = 0,+ .msg_iov = &io,+ .msg_iovlen = 1,+ .msg_control = &control,+ .msg_controllen = sizeof(control),+ .msg_flags = 0,+ };++ ssize_t received = 0;+ do {+ received = recvmsg(socket, &message, MSG_CMSG_CLOEXEC);+ } while (received < 0 && errno == EINTR);+ if (received < 0)+ return;++ int fds[8];+ size_t fd_count = 0;+ for (auto* header = CMSG_FIRSTHDR(&message); header; header = CMSG_NXTHDR(&message, header)) {+ if (header->cmsg_level != SOL_SOCKET || header->cmsg_type != SCM_RIGHTS || header->cmsg_len < CMSG_LEN(0))+ continue;+ auto count = (header->cmsg_len - CMSG_LEN(0)) / sizeof(int);+ for (size_t i = 0; i < count && fd_count < 8; ++i)+ memcpy(&fds[fd_count++], CMSG_DATA(header) + i * sizeof(int), sizeof(int));+ }+ ScopeGuard close_fds = [&] {+ for (size_t i = 0; i < fd_count; ++i)+ close(fds[i]);+ };++ if (received == 0 && fd_count == 0)+ return;++ size_t expected_fd_count = 1;+ int directory_fds[2] = { -1, -1 };+ if (static_cast<size_t>(received) != sizeof(request)+ || request.magic != file_broker_magic+ || (message.msg_flags & (MSG_TRUNC | MSG_CTRUNC)) != 0+ || request.path_length >= sizeof(request.path)+ || request.second_path_length >= sizeof(request.second_path)+ || (request.directory_fd_mask & ~3u) != 0) {+ continue;+ }++ if (request.directory_fd_mask & 1)+ ++expected_fd_count;+ if (request.directory_fd_mask & 2)+ ++expected_fd_count;+ if (fd_count != expected_fd_count)+ continue;++ size_t next_fd = 1;+ if (request.directory_fd_mask & 1)+ directory_fds[0] = fds[next_fd++];+ if (request.directory_fd_mask & 2)+ directory_fds[1] = fds[next_fd++];++ handle(request, directory_fds, fds[0]);+ }+}++static void close_all_descriptors_except(int keep)+{+ auto* directory = opendir("/proc/self/fd");+ if (!directory)+ _exit(1);++ Vector<int> to_close;+ while (auto* entry = readdir(directory)) {+ auto fd = atoi(entry->d_name);+ if (entry->d_name[0] != '.' && fd > STDERR_FILENO && fd != keep && fd != dirfd(directory))+ to_close.append(fd);+ }+ closedir(directory);++ for (auto fd : to_close)+ close(fd);+}++static ErrorOr<void> confine_broker()+{+ SeccompPolicy policy;+ policy.allow_filesystem_metadata_queries();+ policy.allow_filesystem_writes();+ policy.allow_file_descriptor_operations();+ policy.allow_ipc();+ policy.allow_binding_sockets();+ policy.allow_memory_without_executable_mappings();+ policy.allow_signals();+ policy.allow_clocks();+ policy.allow_exit();+ return policy.install();+}++ErrorOr<void> start_file_broker(ReadonlySpan<PathRule> rules)+{+ Vector<ResolvedPathRule> resolved_rules;+ for (auto const& rule : rules) {+ char resolved_path[PATH_MAX];+ if (realpath(rule.path.characters(), resolved_path) == nullptr)+ return Error::from_syscall("realpath"sv, errno);+ TRY(resolved_rules.try_append({ rule.path, resolved_path, rule.access, rule.is_directory }));+ }++ // A working directory that was deleted only costs the helper its relative paths, so it must not cost it the sandbox.+ char current_directory[PATH_MAX];+ if (!getcwd(current_directory, sizeof(current_directory)))+ current_directory[0] = '\0';++ int fds[2];+ if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, fds) < 0)+ return Error::from_syscall("socketpair"sv, errno);++ auto helper_pid = getpid();+ auto child = fork();+ if (child < 0) {+ auto error = errno;+ close(fds[0]);+ close(fds[1]);+ return Error::from_syscall("fork"sv, error);+ }++ if (child == 0) {+ close(fds[0]);++ // Everything else the helper has open is more than a broker for its files should ever hold.+ close_all_descriptors_except(fds[1]);++ (void)prctl(PR_SET_NAME, "FileBroker", 0ul, 0ul, 0ul);+ if (prctl(PR_SET_PDEATHSIG, SIGKILL, 0ul, 0ul, 0ul) < 0 || getppid() != helper_pid)+ _exit(1);++ FileBrokerServer server { move(resolved_rules), helper_pid, current_directory };+ if (confine_broker().is_error())+ _exit(1);++ char const ready = 1;+ if (send(fds[1], &ready, 1, MSG_NOSIGNAL) != 1)+ _exit(1);++ server.serve(fds[1]);+ _exit(0);+ }++ close(fds[1]);++ // The helper stays honest about whether it is confined: without this, a broker that failed to start would look like+ // one that refuses every path.+ char ready = 0;+ ssize_t received = 0;+ do {+ received = recv(fds[0], &ready, 1, 0);+ } while (received < 0 && errno == EINTR);+ if (received != 1 || ready != 1) {+ close(fds[0]);+ return Error::from_string_literal("The file broker could not start");+ }++ s_file_broker_socket = fds[0];++ // Landlock confines the helper from here on, while it still sets up drivers and libraries. So must the broker.+ TRY(Detail::install_file_system_filter());+ return {};+}++}diff --git a/Libraries/LibSandbox/FileBroker.h b/Libraries/LibSandbox/FileBroker.hnew file mode 100644index 00000000000..4cd23a143fa--- /dev/null+++ b/Libraries/LibSandbox/FileBroker.h@@ -0,0 +1,97 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/ByteString.h>+#include <AK/Error.h>+#include <AK/Span.h>+#include <AK/StringView.h>+#include <AK/Vector.h>+#include <LibSandbox/Sandbox.h>+#include <limits.h>+#include <sys/stat.h>++namespace Sandbox {++namespace Detail {++static constexpr u32 file_broker_magic = 0x4c424652u;++enum class FileBrokerOperation : u32 {+ Open,+ Access,+ Stat,+ SymlinkStat,+ ReadLink,+ MakeDirectory,+ RemoveFile,+ RemoveDirectory,+ Rename,+ // The address travels in the first path field, and the socket as the first descriptor.+ BindSocket,+};++struct FileBrokerRequest {+ u32 magic;+ u32 operation;+ i32 flags;+ u32 mode;+ u32 path_length;+ u32 second_path_length;+ // Bit 0 says a descriptor for resolving the first path was attached, bit 1 the same for the second path.+ u32 directory_fd_mask;+ char path[PATH_MAX];+ char second_path[PATH_MAX];+};++struct FileBrokerResponse {+ u32 magic;+ i32 error;+ u32 link_length;+ struct stat stat_result;+ char link[PATH_MAX];+};++// The socket that the SIGSYS handler sends its requests to.+int file_broker_socket();++// Sends every system call that takes a path to the broker or refuses it, and allows everything else, so that the helper+// is confined from the moment the broker runs. The helper's own policy stacks on top of this when it installs it.+[[nodiscard]] ErrorOr<void> install_file_system_filter();++}++// A path rule after its symbolic links were followed. The two paths are the same if there were none.+struct ResolvedPathRule {+ ByteString requested_path;+ ByteString resolved_path;+ PathRule::Access access { PathRule::Access::ReadOnly };+ bool is_directory { false };+};++enum class FileBrokerAccess {+ // Knowing that the path exists, which every directory above an allowed path needs for its path to be resolved.+ Metadata,+ Read,+ Write,+ // Making, removing or renaming the entry itself, which only a writable directory above it allows.+ ChangeEntry,+};++// Decides on canonical paths, which contain no symbolic links.+[[nodiscard]] bool file_broker_allows(ReadonlySpan<ResolvedPathRule>, StringView canonical_path, FileBrokerAccess);++// Seccomp can't read the paths that a process passes to the kernel, so it can't tell which files a process opens. On a+// kernel without Landlock, the seccomp policy instead traps every system call that takes a+// path, and a process forked from the helper does the work if the path is one the helper may use. The helper must have+// only one thread, and must not have installed its seccomp policy yet. The broker exits when the helper does.+[[nodiscard]] ErrorOr<void> start_file_broker(ReadonlySpan<PathRule>);++// Tells the seccomp policy to trap system calls that take a path, in place of allowing them.+[[nodiscard]] bool file_broker_is_active();++}diff --git a/Libraries/LibSandbox/Sandbox.cpp b/Libraries/LibSandbox/Sandbox.cppindex 5659c1adde5..60d6f91b707 100644--- a/Libraries/LibSandbox/Sandbox.cpp+++ b/Libraries/LibSandbox/Sandbox.cpp@@ -10,6 +10,7 @@# include <AK/LexicalPath.h># include <AK/ScopeGuard.h># include <AK/Vector.h>+# include <LibSandbox/FileBroker.h># include <dirent.h># include <errno.h># include <fcntl.h>@@ -795,28 +796,15 @@ static ErrorOr<size_t> count_threads()return thread_count;}-ErrorOr<void> restrict_filesystem(ReadonlySpan<PathRule> paths)-{- // Landlock confines only the calling thread and the threads that it starts later. A thread that already runs would- // keep full access to the file system.- if (TRY(count_threads()) != 1)- return Error::from_string_literal("Landlock must be applied before the process starts a second thread");+static bool s_signals_stay_within_the_process_tree = false;- // Without Landlock, nothing limits the files a helper can open, so we refuse to go on. Running without it has to- // be a choice that the user makes with --disable-sandbox.- auto landlock_abi = syscall(__NR_landlock_create_ruleset, nullptr, 0, LANDLOCK_CREATE_RULESET_VERSION);- if (landlock_abi < 0 && errno != ENOSYS && errno != EOPNOTSUPP)- return Error::from_syscall("landlock_create_ruleset(LANDLOCK_CREATE_RULESET_VERSION)"sv, errno);- if (landlock_abi <= 0) {- // NB: Only for machines that cannot run Landlock at all, such as our CI runners. The rest of the sandbox still- // applies. On a kernel that has Landlock, this changes nothing.- if (auto const* allow = getenv("LADYBIRD_UNSAFE_ALLOW_MISSING_LANDLOCK"); allow && StringView { allow, strlen(allow) } == "1"sv) {- warnln("Landlock is not available in this kernel. This helper runs without file system confinement, because LADYBIRD_UNSAFE_ALLOW_MISSING_LANDLOCK is set.");- return {};- }- return Error::from_string_literal("Landlock is not available in this kernel, so the helper cannot be sandboxed (--disable-sandbox runs helpers without a sandbox)");- }+bool signals_stay_within_the_process_tree()+{+ return s_signals_stay_within_the_process_tree;+}+static ErrorOr<void> restrict_filesystem_with_landlock(ReadonlySpan<PathRule> paths, long landlock_abi)+{// Before ABI 3, Landlock does not handle truncation, so a helper can truncate any file that it can open.static bool s_warned_about_truncation = false;if (landlock_abi < 3 && !s_warned_about_truncation) {@@ -926,9 +914,28 @@ ErrorOr<void> restrict_filesystem(ReadonlySpan<PathRule> paths)if (syscall(__NR_landlock_restrict_self, ruleset_fd, 0) < 0)return Error::from_syscall("landlock_restrict_self"sv, errno);+# if defined(LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET) && defined(LANDLOCK_SCOPE_SIGNAL)+ s_signals_stay_within_the_process_tree = landlock_abi >= 6;+# endifreturn {};}++ErrorOr<void> restrict_filesystem(ReadonlySpan<PathRule> paths)+{+ // Landlock confines only the calling thread and the threads that it starts later, and forking the broker is only+ // safe with one thread. A thread that already runs would keep full access to the file system.+ if (TRY(count_threads()) != 1)+ return Error::from_string_literal("The file system must be restricted before the process starts a second thread");++ // Any failure means we can't have Landlock here: a kernel without it says ENOSYS or EOPNOTSUPP, and a container's+ // own seccomp filter can say anything.+ auto landlock_abi = syscall(__NR_landlock_create_ruleset, nullptr, 0, LANDLOCK_CREATE_RULESET_VERSION);+ if (landlock_abi > 0)+ return restrict_filesystem_with_landlock(paths, landlock_abi);++ return start_file_broker(paths);+}#endif}diff --git a/Libraries/LibSandbox/Sandbox.h b/Libraries/LibSandbox/Sandbox.hindex 1b4b01b0f91..1079746eea7 100644--- a/Libraries/LibSandbox/Sandbox.h+++ b/Libraries/LibSandbox/Sandbox.h@@ -87,6 +87,8 @@ struct SeatbeltProfile {[[nodiscard]] ErrorOr<void> add_path_if_exists(Vector<PathRule>& paths, StringView path, PathRule::Access);[[nodiscard]] ErrorOr<void> add_loaded_library_directories(Vector<PathRule>& paths, Optional<StringView> root = {});[[nodiscard]] ErrorOr<void> restrict_filesystem(ReadonlySpan<PathRule> = {});+// Whether restrict_filesystem() also kept this process from signalling any process outside its own tree.+[[nodiscard]] bool signals_stay_within_the_process_tree();[[nodiscard]] ErrorOr<void> add_gpu_driver_paths(Vector<PathRule>& paths);#endifdiff --git a/Libraries/LibSandbox/Seccomp.cpp b/Libraries/LibSandbox/Seccomp.cppindex 9443001bc9e..5088e6b461b 100644--- a/Libraries/LibSandbox/Seccomp.cpp+++ b/Libraries/LibSandbox/Seccomp.cpp@@ -7,6 +7,7 @@#include <AK/Array.h>#include <LibCore/CrashHandler.h>#include <LibSandbox/ConnectBroker.h>+#include <LibSandbox/FileBroker.h>#include <LibSandbox/Seccomp.h>#include <asm/termbits.h>#include <errno.h>@@ -51,6 +52,11 @@ static constexpr u32 audit_architecture = AUDIT_ARCH_RISCV64;static constexpr u16 emulate_fstatat_trap = 1;static constexpr u16 broker_socket_trap = 2;static constexpr u16 broker_connect_trap = 3;+static constexpr u16 file_broker_trap = 4;+static constexpr u16 signal_mask_trap = 5;+// A refusal for a system call that the file system filter sends to the broker. The policy can't refuse it with an errno,+// because the kernel takes the filter's trap over that, so it traps too, with the errno added to this.+static constexpr u16 refused_path_syscall_trap = 0x1000;static constexpr u32 thread_clone_required_flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD;static constexpr u32 thread_clone_allowed_flags = thread_clone_required_flags@@ -85,6 +91,13 @@ static constexpr unsigned read_only_open_flags = [] {#define SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(policy, name) \IF_DEFINED_##name(SECCOMP_APPEND_ALLOW_SYSCALL(policy, name), (policy).append(SECCOMP_ALLOW_NOTHING))+// A system call that takes a path is allowed when Landlock decides which paths work. Without Landlock, the file system+// filter beneath every policy sends it to the broker or refuses it, which wins over the allow here.+#define SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(policy, name) \+ IF_DEFINED_##name(do { \+ (policy).append(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_##name, 0, 1)); \+ (policy).append((policy).path_syscall_action()); } while (0), (policy).append(SECCOMP_ALLOW_NOTHING))+#define IF_DEFINED_access(if_defined, if_not_defined) if_defined#define IF_DEFINED_bind(if_defined, if_not_defined) if_defined#define IF_DEFINED_brk(if_defined, if_not_defined) if_defined@@ -196,6 +209,7 @@ static constexpr unsigned read_only_open_flags = [] {#define IF_DEFINED_statfs(if_defined, if_not_defined) if_defined#define IF_DEFINED_statx(if_defined, if_not_defined) if_defined#define IF_DEFINED_symlink(if_defined, if_not_defined) if_defined+#define IF_DEFINED_symlinkat(if_defined, if_not_defined) if_defined#define IF_DEFINED_sysinfo(if_defined, if_not_defined) if_defined#define IF_DEFINED_tgkill(if_defined, if_not_defined) if_defined#define IF_DEFINED_unlink(if_defined, if_not_defined) if_defined@@ -467,6 +481,10 @@ static constexpr unsigned read_only_open_flags = [] {# undef IF_DEFINED_symlink# define IF_DEFINED_symlink(if_defined, if_not_defined) if_not_defined#endif+#ifndef __NR_symlinkat+# undef IF_DEFINED_symlinkat+# define IF_DEFINED_symlinkat(if_defined, if_not_defined) if_not_defined+#endif#ifndef __NR_unlink# undef IF_DEFINED_unlink# define IF_DEFINED_unlink(if_defined, if_not_defined) if_not_defined@@ -697,6 +715,9 @@ static char const* syscall_name(long syscall_number)#ifdef __NR_symlinkCASE_SYSCALL_NAME(symlink);#endif+#ifdef __NR_symlinkat+ CASE_SYSCALL_NAME(symlinkat);+#endif#ifdef __NR_unlinkCASE_SYSCALL_NAME(unlink);#endif@@ -718,7 +739,7 @@ static char s_process_name[16] = "unknown";// The arguments are copied out before anything is written back, because the result register and the// first argument register are the same one on some architectures.struct SyscallRegisters {- FlatPtr arguments[4];+ FlatPtr arguments[5];FlatPtr* result;};@@ -733,6 +754,7 @@ static SyscallRegisters syscall_registers(void* context)static_cast<FlatPtr>(machine_context.gregs[REG_RSI]),static_cast<FlatPtr>(machine_context.gregs[REG_RDX]),static_cast<FlatPtr>(machine_context.gregs[REG_R10]),+ static_cast<FlatPtr>(machine_context.gregs[REG_R8]),},reinterpret_cast<FlatPtr*>(&machine_context.gregs[REG_RAX]),};@@ -744,6 +766,7 @@ static SyscallRegisters syscall_registers(void* context)static_cast<FlatPtr>(machine_context.regs[1]),static_cast<FlatPtr>(machine_context.regs[2]),static_cast<FlatPtr>(machine_context.regs[3]),+ static_cast<FlatPtr>(machine_context.regs[4]),},reinterpret_cast<FlatPtr*>(&machine_context.regs[0]),};@@ -755,6 +778,7 @@ static SyscallRegisters syscall_registers(void* context)static_cast<FlatPtr>(machine_context.__gregs[REG_A0 + 1]),static_cast<FlatPtr>(machine_context.__gregs[REG_A0 + 2]),static_cast<FlatPtr>(machine_context.__gregs[REG_A0 + 3]),+ static_cast<FlatPtr>(machine_context.__gregs[REG_A0 + 4]),},reinterpret_cast<FlatPtr*>(&machine_context.__gregs[REG_A0]),};@@ -797,27 +821,29 @@ static int s_connect_broker_fd = -1;// Runs inside the SIGSYS handler, so it may only touch descriptors and syscalls. Each call carries// its own reply socket, which is what keeps it safe to run on several threads at once. Returns the-// descriptor the answer carried, zero when it carried none, or a negative errno.-static i64 ask_broker(Detail::ConnectBrokerRequest const& request, int socket_fd, bool expect_descriptor)+// size of the answer or a negative errno, and stores the descriptor the answer carried, if any.+static i64 exchange_with_broker(int broker_fd, void const* request, size_t request_size, int const* extra_fds, size_t extra_fd_count, void* response, size_t response_size, int& answered_fd){- if (s_connect_broker_fd < 0)- return -EACCES;+ answered_fd = -1;+ VERIFY(extra_fd_count <= 2);int reply_fds[2];if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, reply_fds) < 0)return -errno;- int passed_fds[2] = { reply_fds[1], socket_fd };- size_t passed_fd_count = socket_fd >= 0 ? 2 : 1;+ int passed_fds[3] = { reply_fds[1], -1, -1 };+ for (size_t i = 0; i < extra_fd_count; ++i)+ passed_fds[i + 1] = extra_fds[i];+ size_t passed_fd_count = 1 + extra_fd_count;iovec request_io {- .iov_base = const_cast<Detail::ConnectBrokerRequest*>(&request),- .iov_len = sizeof(request),+ .iov_base = const_cast<void*>(request),+ .iov_len = request_size,};union {cmsghdr header;- char space[CMSG_SPACE(2 * sizeof(int))];+ char space[CMSG_SPACE(3 * sizeof(int))];} request_control {};msghdr request_message {@@ -838,7 +864,7 @@ static i64 ask_broker(Detail::ConnectBrokerRequest const& request, int socket_fdssize_t sent = 0;do {- sent = sendmsg(s_connect_broker_fd, &request_message, MSG_NOSIGNAL);+ sent = sendmsg(broker_fd, &request_message, MSG_NOSIGNAL);} while (sent < 0 && errno == EINTR);close(reply_fds[1]);@@ -849,10 +875,9 @@ static i64 ask_broker(Detail::ConnectBrokerRequest const& request, int socket_fdreturn -saved_errno;}- Detail::ConnectBrokerResponse response {};iovec response_io {- .iov_base = &response,- .iov_len = sizeof(response),+ .iov_base = response,+ .iov_len = response_size,};union {@@ -881,7 +906,6 @@ static i64 ask_broker(Detail::ConnectBrokerRequest const& request, int socket_fdif (received < 0)return -saved_errno;- int answered_fd = -1;for (auto* header = CMSG_FIRSTHDR(&response_message); header; header = CMSG_NXTHDR(&response_message, header)) {if (header->cmsg_level != SOL_SOCKET || header->cmsg_type != SCM_RIGHTS)continue;@@ -898,6 +922,21 @@ static i64 ask_broker(Detail::ConnectBrokerRequest const& request, int socket_fd}}+ return received;+}++// Returns the descriptor the answer carried, zero when it carried none, or a negative errno.+static i64 ask_broker(Detail::ConnectBrokerRequest const& request, int socket_fd, bool expect_descriptor)+{+ if (s_connect_broker_fd < 0)+ return -EACCES;++ Detail::ConnectBrokerResponse response {};+ int answered_fd = -1;+ auto received = exchange_with_broker(s_connect_broker_fd, &request, sizeof(request), &socket_fd, socket_fd >= 0 ? 1 : 0, &response, sizeof(response), answered_fd);+ if (received < 0)+ return received;+auto fail = [&](i64 error) {if (answered_fd >= 0)close(answered_fd);@@ -928,7 +967,10 @@ static i64 copy_from_caller(void* destination, void const* source, size_t lengthi64 result = 0;ssize_t written = 0;do {- written = write(fds[1], source, length);+ // A path is read up to the end of its page, past the memory that holds it. AddressSanitizer checks the bytes+ // that write() sends, and its report would make system calls that trap again inside this handler, where the+ // kernel kills the process for it. The kernel checks the bytes anyway, so this goes to it directly.+ written = syscall(__NR_write, fds[1], source, length);} while (written < 0 && errno == EINTR);if (written < 0)@@ -1040,6 +1082,311 @@ static void emulate_connect(void* context)errno = saved_errno;}+// Reads the string one page at a time, because a string can end right before a page that can't be read.+static i64 copy_path_from_caller(char* destination, char const* source, u32& length)+{+ static constexpr size_t smallest_page_size = 4096;++ size_t copied = 0;+ while (copied < PATH_MAX) {+ auto address = reinterpret_cast<FlatPtr>(source) + copied;+ auto chunk = min(smallest_page_size - address % smallest_page_size, PATH_MAX - copied);+ if (auto result = copy_from_caller(destination + copied, source + copied, chunk); result < 0)+ return result;+ for (size_t i = 0; i < chunk; ++i) {+ if (destination[copied + i] == '\0') {+ length = static_cast<u32>(copied + i);+ return 0;+ }+ }+ copied += chunk;+ }+ return -ENAMETOOLONG;+}++struct FileBrokerPath {+ int directory_fd { AT_FDCWD };+ char const* path { nullptr };+};++static i64 exchange_with_file_broker(Detail::FileBrokerRequest const& request, int const* fds, size_t fd_count, Detail::FileBrokerResponse& response)+{+ int answered_fd = -1;+ auto received = exchange_with_broker(Detail::file_broker_socket(), &request, sizeof(request), fds, fd_count, &response, sizeof(response), answered_fd);+ if (received < 0)+ return received == -EPIPE ? -EACCES : received;++ auto is_valid = static_cast<size_t>(received) == sizeof(response) && response.magic == Detail::file_broker_magic;+ if (!is_valid || response.error != 0) {+ if (answered_fd >= 0)+ close(answered_fd);+ return is_valid ? -response.error : -EACCES;+ }++ // The kernel drops a descriptor that doesn't fit in our table. Zero would read as a successful open of stdin.+ if (request.operation == static_cast<u32>(Detail::FileBrokerOperation::Open) && answered_fd < 0)+ return -EMFILE;+ return answered_fd >= 0 ? answered_fd : 0;+}++static i64 ask_file_broker(Detail::FileBrokerOperation operation, FileBrokerPath first, FileBrokerPath second, int flags, u32 mode, Detail::FileBrokerResponse& response)+{+ Detail::FileBrokerRequest request;+ __builtin_memset(&request, 0, sizeof(request));+ request.magic = Detail::file_broker_magic;+ request.operation = static_cast<u32>(operation);+ request.flags = flags;+ request.mode = mode;++ if (auto result = copy_path_from_caller(request.path, first.path, request.path_length); result < 0)+ return result;+ if (second.path) {+ if (auto result = copy_path_from_caller(request.second_path, second.path, request.second_path_length); result < 0)+ return result;+ }++ int directory_fds[2];+ size_t directory_fd_count = 0;+ if (first.directory_fd != AT_FDCWD && request.path[0] != '/') {+ request.directory_fd_mask |= 1;+ directory_fds[directory_fd_count++] = first.directory_fd;+ }+ if (second.path && second.directory_fd != AT_FDCWD && request.second_path[0] != '/') {+ request.directory_fd_mask |= 2;+ directory_fds[directory_fd_count++] = second.directory_fd;+ }++ return exchange_with_file_broker(request, directory_fds, directory_fd_count, response);+}++static i64 bind_through_broker(int fd, void const* address, socklen_t length)+{+ Detail::FileBrokerRequest request;+ __builtin_memset(&request, 0, sizeof(request));+ request.magic = Detail::file_broker_magic;+ request.operation = static_cast<u32>(Detail::FileBrokerOperation::BindSocket);+ request.directory_fd_mask = 1;++ if (length < sizeof(sa_family_t) || length > sizeof(sockaddr_storage))+ return -EINVAL;+ request.path_length = length;+ if (auto result = copy_from_caller(request.path, address, length); result < 0)+ return result;++ Detail::FileBrokerResponse response;+ return exchange_with_file_broker(request, &fd, 1, response);+}++static i64 open_through_broker(int directory_fd, char const* path, int flags, u32 mode)+{+ Detail::FileBrokerResponse response;+ auto result = ask_file_broker(Detail::FileBrokerOperation::Open, { directory_fd, path }, {}, flags, mode, response);++ // The descriptor arrives close-on-exec, because that is how it travels safely.+ if (result >= 0 && (flags & O_CLOEXEC) == 0 && fcntl(static_cast<int>(result), F_SETFD, 0) < 0) {+ auto failure = -errno;+ close(static_cast<int>(result));+ return failure;+ }+ return result;+}++static i64 stat_through_broker(int directory_fd, char const* path, void* buffer, bool follow_symlinks)+{+ Detail::FileBrokerResponse response;+ auto operation = follow_symlinks ? Detail::FileBrokerOperation::Stat : Detail::FileBrokerOperation::SymlinkStat;+ auto result = ask_file_broker(operation, { directory_fd, path }, {}, 0, 0, response);+ if (result < 0)+ return result;+ return copy_from_caller(buffer, &response.stat_result, sizeof(response.stat_result));+}++static i64 read_link_through_broker(int directory_fd, char const* path, char* buffer, size_t buffer_size)+{+ Detail::FileBrokerResponse response;+ auto result = ask_file_broker(Detail::FileBrokerOperation::ReadLink, { directory_fd, path }, {}, 0, 0, response);+ if (result < 0)+ return result;+ auto length = min<size_t>(response.link_length, buffer_size);+ if (auto copied = copy_from_caller(buffer, response.link, length); copied < 0)+ return copied;+ return static_cast<i64>(length);+}++static i64 simple_broker_call(Detail::FileBrokerOperation operation, int directory_fd, char const* path, int flags, u32 mode)+{+ Detail::FileBrokerResponse response;+ return ask_file_broker(operation, { directory_fd, path }, {}, flags, mode, response);+}++static i64 rename_through_broker(int old_directory_fd, char const* old_path, int new_directory_fd, char const* new_path)+{+ Detail::FileBrokerResponse response;+ return ask_file_broker(Detail::FileBrokerOperation::Rename, { old_directory_fd, old_path }, { new_directory_fd, new_path }, 0, 0, response);+}++static i64 perform_file_syscall(int syscall_number, SyscallRegisters const& registers)+{+ using Operation = Detail::FileBrokerOperation;+ auto number = [&](size_t index) { return static_cast<int>(registers.arguments[index]); };+ auto path = [&](size_t index) { return reinterpret_cast<char const*>(registers.arguments[index]); };++ switch (syscall_number) {+#ifdef __NR_bind+ case __NR_bind:+ return bind_through_broker(number(0), reinterpret_cast<void const*>(registers.arguments[1]), static_cast<socklen_t>(number(2)));+#endif+#ifdef __NR_open+ case __NR_open:+ return open_through_broker(AT_FDCWD, path(0), number(1), static_cast<u32>(number(2)));+#endif+#ifdef __NR_openat+ case __NR_openat:+ return open_through_broker(number(0), path(1), number(2), static_cast<u32>(number(3)));+#endif+#ifdef __NR_access+ case __NR_access:+ return simple_broker_call(Operation::Access, AT_FDCWD, path(0), number(1), 0);+#endif+#ifdef __NR_faccessat+ case __NR_faccessat:+ return simple_broker_call(Operation::Access, number(0), path(1), number(2), 0);+#endif+#ifdef __NR_faccessat2+ case __NR_faccessat2:+ return simple_broker_call(Operation::Access, number(0), path(1), number(2), static_cast<u32>(number(3)));+#endif+#ifdef __NR_stat+ case __NR_stat:+ return stat_through_broker(AT_FDCWD, path(0), reinterpret_cast<void*>(registers.arguments[1]), true);+#endif+#ifdef __NR_newfstatat+ case __NR_newfstatat: {+ auto flags = number(3);+ if (flags & AT_EMPTY_PATH) {+ // Since Linux 6.11, AT_EMPTY_PATH accepts a null path as well.+ char first_byte = '\0';+ if (path(1)) {+ if (auto result = copy_from_caller(&first_byte, path(1), 1); result < 0)+ return result;+ }+# ifdef __NR_fstat+ if (first_byte == '\0') {+ auto result = syscall(__NR_fstat, number(0), registers.arguments[2]);+ return result < 0 ? -errno : result;+ }+# endif+ }+ return stat_through_broker(number(0), path(1), reinterpret_cast<void*>(registers.arguments[2]), (flags & AT_SYMLINK_NOFOLLOW) == 0);+ }+#endif+#ifdef __NR_readlink+ case __NR_readlink:+ return read_link_through_broker(AT_FDCWD, path(0), reinterpret_cast<char*>(registers.arguments[1]), registers.arguments[2]);+#endif+#ifdef __NR_readlinkat+ case __NR_readlinkat:+ return read_link_through_broker(number(0), path(1), reinterpret_cast<char*>(registers.arguments[2]), registers.arguments[3]);+#endif+#ifdef __NR_mkdir+ case __NR_mkdir:+ return simple_broker_call(Operation::MakeDirectory, AT_FDCWD, path(0), 0, static_cast<u32>(number(1)));+#endif+#ifdef __NR_mkdirat+ case __NR_mkdirat:+ return simple_broker_call(Operation::MakeDirectory, number(0), path(1), 0, static_cast<u32>(number(2)));+#endif+#ifdef __NR_unlink+ case __NR_unlink:+ return simple_broker_call(Operation::RemoveFile, AT_FDCWD, path(0), 0, 0);+#endif+#ifdef __NR_rmdir+ case __NR_rmdir:+ return simple_broker_call(Operation::RemoveDirectory, AT_FDCWD, path(0), 0, 0);+#endif+#ifdef __NR_unlinkat+ case __NR_unlinkat:+ return simple_broker_call((number(2) & AT_REMOVEDIR) ? Operation::RemoveDirectory : Operation::RemoveFile, number(0), path(1), 0, 0);+#endif+#ifdef __NR_rename+ case __NR_rename:+ return rename_through_broker(AT_FDCWD, path(0), AT_FDCWD, path(1));+#endif+#ifdef __NR_renameat+ case __NR_renameat:+ return rename_through_broker(number(0), path(1), number(2), path(3));+#endif+#ifdef __NR_renameat2+ case __NR_renameat2:+ // The broker only replaces, so anything else has to fall back to doing without, as on a kernel without flags.+ if (registers.arguments[4] != 0)+ return -ENOSYS;+ return rename_through_broker(number(0), path(1), number(2), path(3));+#endif+ default:+ return -ENOSYS;+ }+}++static void emulate_file_syscall(int syscall_number, void* context)+{+ auto registers = syscall_registers(context);+ auto saved_errno = errno;+ set_syscall_result(registers, perform_file_syscall(syscall_number, registers));+ errno = saved_errno;+}++// The kernel kills a process outright for a trap that arrives while SIGSYS is blocked, so a path that a thread looks up+// then would end the helper instead of reaching the broker. glibc blocks every signal while a thread exits, and freeing+// that thread's memory can read /proc/sys/vm/overcommit_memory. This keeps SIGSYS out of every mask that the helper+// asks for. The handler's context holds the mask that the thread gets back when the handler returns.+static i64 change_signal_mask(SyscallRegisters const& registers, void* context)+{+ static constexpr u64 unblockable = (1ull << (SIGKILL - 1)) | (1ull << (SIGSTOP - 1)) | (1ull << (SIGSYS - 1));++ auto how = static_cast<int>(registers.arguments[0]);+ auto const* new_mask = reinterpret_cast<u64 const*>(registers.arguments[1]);+ auto* old_mask = reinterpret_cast<u64*>(registers.arguments[2]);+ if (registers.arguments[3] != sizeof(u64))+ return -EINVAL;++ auto& thread_mask = static_cast<ucontext_t*>(context)->uc_sigmask;+ u64 current = 0;+ __builtin_memcpy(¤t, &thread_mask, sizeof(current));++ auto updated = current;+ if (new_mask) {+ u64 requested = 0;+ __builtin_memcpy(&requested, new_mask, sizeof(requested));+ switch (how) {+ case SIG_BLOCK:+ updated |= requested;+ break;+ case SIG_UNBLOCK:+ updated &= ~requested;+ break;+ case SIG_SETMASK:+ updated = requested;+ break;+ default:+ return -EINVAL;+ }+ }++ if (old_mask)+ __builtin_memcpy(old_mask, ¤t, sizeof(current));++ updated &= ~unblockable;+ __builtin_memcpy(&thread_mask, &updated, sizeof(updated));+ return 0;+}++static void emulate_signal_mask_change(void* context)+{+ auto registers = syscall_registers(context);+ set_syscall_result(registers, change_signal_mask(registers, context));+}+static void handle_sigsys(int, siginfo_t* info, void* context){if (info->si_code == SYS_SECCOMP && info->si_arch == audit_architecture) {@@ -1057,6 +1404,20 @@ static void handle_sigsys(int, siginfo_t* info, void* context)emulate_connect(context);return;}+ if (info->si_errno == file_broker_trap) {+ emulate_file_syscall(info->si_syscall, context);+ return;+ }+#ifdef __NR_rt_sigprocmask+ if (info->si_syscall == __NR_rt_sigprocmask && info->si_errno == signal_mask_trap) {+ emulate_signal_mask_change(context);+ return;+ }+#endif+ if (info->si_errno > refused_path_syscall_trap && info->si_errno < refused_path_syscall_trap + 0x1000) {+ set_syscall_result(syscall_registers(context), -(info->si_errno - refused_path_syscall_trap));+ return;+ }}write_string("Sandbox violation in ");@@ -1117,6 +1478,20 @@ static ErrorOr<void> install_sigsys_handler()}+sock_filter SeccompPolicy::path_syscall_action()+{+ if (file_broker_is_active())+ m_sends_paths_to_file_broker = true;+ return SECCOMP_ALLOW;+}++static sock_filter refused_path_syscall_action(int error)+{+ if (file_broker_is_active())+ return BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_TRAP | (refused_path_syscall_trap + error));+ return SECCOMP_ERRNO(error);+}+SeccompPolicy::SeccompPolicy(){append_architecture_check();@@ -1152,7 +1527,7 @@ void SeccompPolicy::deny_readonly_filesystem_probes()append(SECCOMP_LOAD_ARGUMENT(1));append(BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~read_only_open_flags));append(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1));- append(SECCOMP_ERRNO(EACCES));+ append(refused_path_syscall_action(EACCES));append(SECCOMP_LOAD_SYSCALL_NR);#endif#ifdef __NR_openat@@ -1160,20 +1535,20 @@ void SeccompPolicy::deny_readonly_filesystem_probes()append(SECCOMP_LOAD_ARGUMENT(2));append(BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~read_only_open_flags));append(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1));- append(SECCOMP_ERRNO(EACCES));+ append(refused_path_syscall_action(EACCES));append(SECCOMP_LOAD_SYSCALL_NR);#endif#ifdef __NR_accessappend(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_access, 0, 1));- append(SECCOMP_ERRNO(EACCES));+ append(refused_path_syscall_action(EACCES));#endif#ifdef __NR_faccessatappend(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_faccessat, 0, 1));- append(SECCOMP_ERRNO(EACCES));+ append(refused_path_syscall_action(EACCES));#endif#ifdef __NR_faccessat2append(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_faccessat2, 0, 1));- append(SECCOMP_ERRNO(EACCES));+ append(refused_path_syscall_action(EACCES));#endif}@@ -1184,7 +1559,7 @@ void SeccompPolicy::allow_readonly_file_opens()append(SECCOMP_LOAD_ARGUMENT(1));append(BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~read_only_open_flags));append(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1));- append(SECCOMP_ALLOW);+ append(path_syscall_action());append(SECCOMP_LOAD_SYSCALL_NR);#endif#ifdef __NR_openat@@ -1192,41 +1567,42 @@ void SeccompPolicy::allow_readonly_file_opens()append(SECCOMP_LOAD_ARGUMENT(2));append(BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~read_only_open_flags));append(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1));- append(SECCOMP_ALLOW);+ append(path_syscall_action());append(SECCOMP_LOAD_SYSCALL_NR);#endif}void SeccompPolicy::allow_filesystem_metadata_queries(){- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, access);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, faccessat);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, faccessat2);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, access);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, faccessat);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, faccessat2);SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, fstatfs);SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, getdents64);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, newfstatat);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, readlink);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, readlinkat);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, stat);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, newfstatat);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, readlink);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, readlinkat);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, stat);SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, statfs);SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, statx);}void SeccompPolicy::allow_filesystem_writes(){- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, open);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, openat);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, unlink);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, unlinkat);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, open);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, openat);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, unlink);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, unlinkat);SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, link);SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, linkat);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, rename);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, renameat);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, renameat2);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, mkdir);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, mkdirat);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, rename);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, renameat);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, renameat2);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, mkdir);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, mkdirat);SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, symlink);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, rmdir);+ SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, symlinkat);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, rmdir);SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, fsync);SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, fdatasync);SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, fallocate);@@ -1381,9 +1757,21 @@ void SeccompPolicy::allow_file_descriptor_operations()void SeccompPolicy::allow_process_creation(){- // Compiler children inherit this filter but have different thread group IDs. Landlock- // signal scoping confines their signals to the sandbox's process tree on ABI 6 and newer.- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, tgkill);+ // Compiler children inherit this filter but have different thread group IDs. Landlock's signal scope confines their+ // signals to the sandbox's process tree. Without it, any thread group could be signalled, including the Browser's,+ // so only this process may be, and a child can't signal at all. It can't exec anything there either, so it can only+ // be a fork that ends with its parent.+ if (signals_stay_within_the_process_tree()) {+ SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, tgkill);+ } else {+#ifdef __NR_tgkill+ append(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_tgkill, 0, 4));+ append(SECCOMP_LOAD_ARGUMENT(0));+ append(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, static_cast<u32>(getpid()), 0, 1));+ append(SECCOMP_ALLOW);+ append(SECCOMP_LOAD_SYSCALL_NR);+#endif+ }// Core::Process::spawn() asks for compiler children to die with their parent.append(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_prctl, 0, 6));append(SECCOMP_LOAD_ARGUMENT(0));@@ -1565,14 +1953,14 @@ void SeccompPolicy::allow_pulseaudio_client_file_operations(){// libpulse re-creates its runtime directory before it looks for a socket there, and removes a directory it made// again when it can't use it; Landlock decides where that succeeds.- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, mkdir);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, mkdirat);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, rmdir);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, mkdir);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, mkdirat);+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, rmdir);#ifdef __NR_unlinkatappend(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_unlinkat, 0, 4));append(SECCOMP_LOAD_ARGUMENT(2));append(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AT_REMOVEDIR, 0, 1));- append(SECCOMP_ALLOW);+ append(path_syscall_action());append(SECCOMP_LOAD_SYSCALL_NR);#endif@@ -1584,7 +1972,7 @@ void SeccompPolicy::allow_pulseaudio_client_file_operations()append(SECCOMP_LOAD_ARGUMENT(1));append(BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~read_only_open_flags));append(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 1, 0));- append(SECCOMP_ERRNO(EACCES));+ append(refused_path_syscall_action(EACCES));append(SECCOMP_LOAD_SYSCALL_NR);#endif#ifdef __NR_openat@@ -1592,7 +1980,7 @@ void SeccompPolicy::allow_pulseaudio_client_file_operations()append(SECCOMP_LOAD_ARGUMENT(2));append(BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~read_only_open_flags));append(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 1, 0));- append(SECCOMP_ERRNO(EACCES));+ append(refused_path_syscall_action(EACCES));append(SECCOMP_LOAD_SYSCALL_NR);#endif@@ -1666,7 +2054,8 @@ void SeccompPolicy::allow_network()SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, sendto);SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, connect);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, bind);+ // Binding a UNIX socket creates a file, which is for Landlock or the file broker to decide on.+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, bind);SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, shutdown);#ifdef __NR_setsockopt@@ -1691,6 +2080,13 @@ void SeccompPolicy::allow_network()append(BPF_STMT(BPF_ALU | BPF_ADD | BPF_K, 0));}+// For the file broker's own policy. The broker runs without the file system filter, so it may bind outright, while+// the helpers' policies send bind through the broker.+void SeccompPolicy::allow_binding_sockets()+{+ SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, bind);+}+// ICE only exchanges UDP datagrams, so unlike allow_network() this leaves out streams. Its mDNS responder shares the// mDNS port with the system's and joins the mDNS multicast group.void SeccompPolicy::allow_datagram_network()@@ -1717,7 +2113,8 @@ void SeccompPolicy::allow_datagram_network()SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, sendto);SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, connect);- SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, bind);+ // Binding a UNIX socket creates a file, which is for Landlock or the file broker to decide on.+ SECCOMP_APPEND_PATH_SYSCALL_IF_DEFINED(*this, bind);#ifdef __NR_setsockoptstatic constexpr Array<u32, 3> socket_options { SO_REUSEADDR, SO_REUSEPORT, SO_BROADCAST };@@ -2066,6 +2463,18 @@ ErrorOr<void> SeccompPolicy::install(){TRY(install_sigsys_handler());+ // The trap handler can't make a system call that traps again, so what it needs to reach the broker has to be allowed+ // outright. A policy that sends nothing there keeps these closed, so that one that pairs no sockets still can't.+ if (m_sends_paths_to_file_broker) {+ SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, sendmsg);+ SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, recvmsg);+ SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, pipe2);+ SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, read);+ SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, write);+ SECCOMP_APPEND_ALLOW_SYSCALL_IF_DEFINED(*this, close);+ allow_socket_pairs();+ }+// A socket domain that no group asked for is refused rather than fatal. Libraries probe// transports they can live without; glibc, for one, tries an nscd socket before it falls back// to reading files, and killing the process over that would be a stability bug, not security.@@ -2117,4 +2526,286 @@ ErrorOr<void> SeccompPolicy::install()return {};}+namespace Detail {++// Every architecture numbers the system calls from 424 on alike, so these hold even where the headers predate them.+// A number past the newest one that was checked here could be a new way to reach a path, so it gets ENOSYS. That+// includes the x32 system calls on x86_64.+static constexpr u32 first_unchecked_syscall_number = 472;++ErrorOr<void> install_file_system_filter()+{+ TRY(install_sigsys_handler());+ TRY(install_no_new_privileges());++ // From here on, the filter keeps SIGSYS out of every mask. One that is blocked already has to be let through too.+ sigset_t trap_signal;+ sigemptyset(&trap_signal);+ sigaddset(&trap_signal, SIGSYS);+ if (auto error = pthread_sigmask(SIG_UNBLOCK, &trap_signal, nullptr); error != 0)+ return Error::from_syscall("pthread_sigmask"sv, error);++ struct Answer {+ u32 syscall_number;+ u32 action;+ };+ static constexpr u32 brokered = SECCOMP_RET_TRAP | file_broker_trap;+ static constexpr auto refused = [](int error) { return SECCOMP_RET_ERRNO | static_cast<u32>(error); };++ // System calls that take a path go to the broker. The others are refused: the broker has nothing like them, or they+ // reach files without a path, or into the broker itself.+ static constexpr Answer answers[] = {+#ifdef __NR_open+ { __NR_open, brokered },+#endif+#ifdef __NR_openat+ { __NR_openat, brokered },+#endif+#ifdef __NR_access+ { __NR_access, brokered },+#endif+#ifdef __NR_faccessat+ { __NR_faccessat, brokered },+#endif+#ifdef __NR_faccessat2+ { __NR_faccessat2, brokered },+#endif+#ifdef __NR_stat+ { __NR_stat, brokered },+#endif+#ifdef __NR_newfstatat+ { __NR_newfstatat, brokered },+#endif+#ifdef __NR_readlink+ { __NR_readlink, brokered },+#endif+#ifdef __NR_readlinkat+ { __NR_readlinkat, brokered },+#endif+#ifdef __NR_mkdir+ { __NR_mkdir, brokered },+#endif+#ifdef __NR_mkdirat+ { __NR_mkdirat, brokered },+#endif+#ifdef __NR_unlink+ { __NR_unlink, brokered },+#endif+#ifdef __NR_rmdir+ { __NR_rmdir, brokered },+#endif+#ifdef __NR_unlinkat+ { __NR_unlinkat, brokered },+#endif+#ifdef __NR_rename+ { __NR_rename, brokered },+#endif+#ifdef __NR_renameat+ { __NR_renameat, brokered },+#endif+#ifdef __NR_renameat2+ { __NR_renameat2, brokered },+#endif+#ifdef __NR_bind+ { __NR_bind, brokered },+#endif+#ifdef __NR_lstat+ { __NR_lstat, refused(ENOSYS) },+#endif+#ifdef __NR_statx+ { __NR_statx, refused(ENOSYS) },+#endif+#ifdef __NR_statfs+ { __NR_statfs, refused(ENOSYS) },+#endif+#ifdef __NR_link+ { __NR_link, refused(EPERM) },+#endif+#ifdef __NR_linkat+ { __NR_linkat, refused(EPERM) },+#endif+#ifdef __NR_symlink+ { __NR_symlink, refused(EPERM) },+#endif+#ifdef __NR_symlinkat+ { __NR_symlinkat, refused(EPERM) },+#endif+#ifdef __NR_execve+ { __NR_execve, refused(EACCES) },+#endif+#ifdef __NR_execveat+ { __NR_execveat, refused(EACCES) },+#endif+#ifdef __NR_creat+ { __NR_creat, refused(EACCES) },+#endif+#ifdef __NR_truncate+ { __NR_truncate, refused(EACCES) },+#endif+#ifdef __NR_inotify_add_watch+ { __NR_inotify_add_watch, refused(EACCES) },+#endif+#ifdef __NR_chmod+ { __NR_chmod, refused(EPERM) },+#endif+#ifdef __NR_fchmodat+ { __NR_fchmodat, refused(EPERM) },+#endif+#ifdef __NR_chown+ { __NR_chown, refused(EPERM) },+#endif+#ifdef __NR_lchown+ { __NR_lchown, refused(EPERM) },+#endif+#ifdef __NR_fchownat+ { __NR_fchownat, refused(EPERM) },+#endif+#ifdef __NR_mknod+ { __NR_mknod, refused(EPERM) },+#endif+#ifdef __NR_mknodat+ { __NR_mknodat, refused(EPERM) },+#endif+#ifdef __NR_utime+ { __NR_utime, refused(EPERM) },+#endif+#ifdef __NR_utimes+ { __NR_utimes, refused(EPERM) },+#endif+#ifdef __NR_futimesat+ { __NR_futimesat, refused(EPERM) },+#endif+#ifdef __NR_utimensat+ { __NR_utimensat, refused(EPERM) },+#endif+#ifdef __NR_chdir+ { __NR_chdir, refused(EPERM) },+#endif+#ifdef __NR_fchdir+ { __NR_fchdir, refused(EPERM) },+#endif+#ifdef __NR_chroot+ { __NR_chroot, refused(EPERM) },+#endif+#ifdef __NR_pivot_root+ { __NR_pivot_root, refused(EPERM) },+#endif+#ifdef __NR_mount+ { __NR_mount, refused(EPERM) },+#endif+#ifdef __NR_umount2+ { __NR_umount2, refused(EPERM) },+#endif+#ifdef __NR_swapon+ { __NR_swapon, refused(EPERM) },+#endif+#ifdef __NR_swapoff+ { __NR_swapoff, refused(EPERM) },+#endif+#ifdef __NR_acct+ { __NR_acct, refused(EPERM) },+#endif+#ifdef __NR_quotactl+ { __NR_quotactl, refused(EPERM) },+#endif+#ifdef __NR_uselib+ { __NR_uselib, refused(EPERM) },+#endif+#ifdef __NR_name_to_handle_at+ { __NR_name_to_handle_at, refused(EPERM) },+#endif+#ifdef __NR_open_by_handle_at+ { __NR_open_by_handle_at, refused(EPERM) },+#endif+#ifdef __NR_fanotify_mark+ { __NR_fanotify_mark, refused(EPERM) },+#endif+#ifdef __NR_ptrace+ { __NR_ptrace, refused(EPERM) },+#endif+#ifdef __NR_process_vm_readv+ { __NR_process_vm_readv, refused(EPERM) },+#endif+#ifdef __NR_process_vm_writev+ { __NR_process_vm_writev, refused(EPERM) },+#endif+#ifdef __NR_setxattr+ { __NR_setxattr, refused(EOPNOTSUPP) },+#endif+#ifdef __NR_lsetxattr+ { __NR_lsetxattr, refused(EOPNOTSUPP) },+#endif+#ifdef __NR_getxattr+ { __NR_getxattr, refused(EOPNOTSUPP) },+#endif+#ifdef __NR_lgetxattr+ { __NR_lgetxattr, refused(EOPNOTSUPP) },+#endif+#ifdef __NR_listxattr+ { __NR_listxattr, refused(EOPNOTSUPP) },+#endif+#ifdef __NR_llistxattr+ { __NR_llistxattr, refused(EOPNOTSUPP) },+#endif+#ifdef __NR_removexattr+ { __NR_removexattr, refused(EOPNOTSUPP) },+#endif+#ifdef __NR_lremovexattr+ { __NR_lremovexattr, refused(EOPNOTSUPP) },+#endif+ { 425, refused(ENOSYS) }, // io_uring_setup+ { 426, refused(ENOSYS) }, // io_uring_enter+ { 427, refused(ENOSYS) }, // io_uring_register+ { 428, refused(EPERM) }, // open_tree+ { 429, refused(EPERM) }, // move_mount+ { 430, refused(EPERM) }, // fsopen+ { 431, refused(EPERM) }, // fsconfig+ { 432, refused(EPERM) }, // fsmount+ { 433, refused(EPERM) }, // fspick+ { 437, refused(ENOSYS) }, // openat2+ { 438, refused(EPERM) }, // pidfd_getfd+ { 442, refused(EPERM) }, // mount_setattr+ { 443, refused(EPERM) }, // quotactl_fd+ { 452, refused(EPERM) }, // fchmodat2+ { 463, refused(EOPNOTSUPP) }, // setxattrat+ { 464, refused(EOPNOTSUPP) }, // getxattrat+ { 465, refused(EOPNOTSUPP) }, // listxattrat+ { 466, refused(EOPNOTSUPP) }, // removexattrat+ { 467, refused(EPERM) }, // open_tree_attr+ { 468, refused(EACCES) }, // file_getattr+ { 469, refused(EPERM) }, // file_setattr+ };++ Vector<sock_filter> filter;+ TRY(filter.try_append(SECCOMP_LOAD_ARCHITECTURE));+ TRY(filter.try_append(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, audit_architecture, 1, 0)));+ TRY(filter.try_append(SECCOMP_TRAP));+ TRY(filter.try_append(SECCOMP_LOAD_SYSCALL_NR));+ TRY(filter.try_append(BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, first_unchecked_syscall_number, 0, 1)));+ TRY(filter.try_append(SECCOMP_ERRNO(ENOSYS)));+#ifdef __NR_rt_sigprocmask+ // Only a mask that could block SIGSYS needs a look.+ TRY(filter.try_append(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_rt_sigprocmask, 0, 4)));+ TRY(filter.try_append(SECCOMP_LOAD_ARGUMENT(0)));+ TRY(filter.try_append(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SIG_UNBLOCK, 0, 1)));+ TRY(filter.try_append(SECCOMP_ALLOW));+ TRY(filter.try_append(BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_TRAP | signal_mask_trap)));+#endif+ for (auto const& answer : answers) {+ TRY(filter.try_append(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, answer.syscall_number, 0, 1)));+ TRY(filter.try_append(BPF_STMT(BPF_RET | BPF_K, answer.action)));+ }+ TRY(filter.try_append(SECCOMP_ALLOW));++ sock_fprog program {+ .len = static_cast<unsigned short>(filter.size()),+ .filter = filter.data(),+ };+ if (syscall(__NR_seccomp, SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC, &program) < 0)+ return Error::from_syscall("seccomp(SECCOMP_SET_MODE_FILTER)"sv, errno);+ return {};+}++}+}diff --git a/Libraries/LibSandbox/Seccomp.h b/Libraries/LibSandbox/Seccomp.hindex e4bee6c6a79..93c76d9d4ef 100644--- a/Libraries/LibSandbox/Seccomp.h+++ b/Libraries/LibSandbox/Seccomp.h@@ -31,6 +31,7 @@ public:void allow_pulseaudio_client_file_operations();void allow_network();void allow_datagram_network();+ void allow_binding_sockets();void allow_memory_without_executable_mappings();void allow_executable_memory_mappings();void allow_writable_executable_memory_mappings();@@ -53,8 +54,10 @@ private:void append_architecture_check();void append_load_syscall_number();void append_kill();+ sock_filter path_syscall_action();Vector<sock_filter> m_filter;+ bool m_sends_paths_to_file_broker { false };};}diff --git a/Tests/LibSandbox/CMakeLists.txt b/Tests/LibSandbox/CMakeLists.txtindex 90d4a655fe2..a7b16285f92 100644--- a/Tests/LibSandbox/CMakeLists.txt+++ b/Tests/LibSandbox/CMakeLists.txt@@ -4,6 +4,7 @@ target_link_libraries(TestLibSandbox PRIVATE LibSandbox)if (LINUX)# Applies the real sandbox of the image decoder, so it builds its sandbox source.target_sources(TestLibSandbox PRIVATE+ TestFileBroker.cppTestImageDecoderSandbox.cppTestLandlock.cppTestSeccomp.cppdiff --git a/Tests/LibSandbox/TestFileBroker.cpp b/Tests/LibSandbox/TestFileBroker.cppnew file mode 100644index 00000000000..7c5fd28b5b7--- /dev/null+++ b/Tests/LibSandbox/TestFileBroker.cpp@@ -0,0 +1,738 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Platform.h>+#include <LibSandbox/FileBroker.h>+#include <LibSandbox/Sandbox.h>+#include <LibSandbox/Seccomp.h>+#include <LibTest/TestCase.h>+#include <arpa/inet.h>+#include <errno.h>+#include <fcntl.h>+#include <linux/filter.h>+#include <linux/netlink.h>+#include <linux/seccomp.h>+#include <netinet/in.h>+#include <signal.h>+#include <stddef.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/inotify.h>+#include <sys/prctl.h>+#include <sys/ptrace.h>+#include <sys/resource.h>+#include <sys/socket.h>+#include <sys/stat.h>+#include <sys/syscall.h>+#include <sys/un.h>+#include <sys/wait.h>+#include <sys/xattr.h>+#include <unistd.h>++using Sandbox::file_broker_allows;+using Sandbox::FileBrokerAccess;+using Sandbox::PathRule;+using Sandbox::ResolvedPathRule;++static ResolvedPathRule rule(StringView path, PathRule::Access access, bool is_directory)+{+ return { path, path, access, is_directory };+}++TEST_CASE(a_directory_rule_covers_what_is_inside_it)+{+ Vector<ResolvedPathRule> rules { rule("/a/b"sv, PathRule::Access::ReadOnly, true) };+ EXPECT(file_broker_allows(rules, "/a/b"sv, FileBrokerAccess::Read));+ EXPECT(file_broker_allows(rules, "/a/b/c/d"sv, FileBrokerAccess::Read));+ EXPECT(!file_broker_allows(rules, "/a/bc"sv, FileBrokerAccess::Read));+ EXPECT(!file_broker_allows(rules, "/a/b/c"sv, FileBrokerAccess::Write));+}++TEST_CASE(a_file_rule_covers_only_that_file)+{+ Vector<ResolvedPathRule> rules { rule("/a/file"sv, PathRule::Access::ReadWrite, false) };+ EXPECT(file_broker_allows(rules, "/a/file"sv, FileBrokerAccess::Write));+ EXPECT(!file_broker_allows(rules, "/a/file/x"sv, FileBrokerAccess::Read));+ EXPECT(!file_broker_allows(rules, "/a/other"sv, FileBrokerAccess::Read));+}++TEST_CASE(directories_above_a_rule_expose_their_metadata_and_nothing_else)+{+ Vector<ResolvedPathRule> rules { rule("/a/b"sv, PathRule::Access::ReadOnly, true) };+ EXPECT(file_broker_allows(rules, "/"sv, FileBrokerAccess::Metadata));+ EXPECT(file_broker_allows(rules, "/a"sv, FileBrokerAccess::Metadata));+ EXPECT(!file_broker_allows(rules, "/a"sv, FileBrokerAccess::Read));+ EXPECT(!file_broker_allows(rules, "/a/other"sv, FileBrokerAccess::Metadata));+}++TEST_CASE(rules_add_up_along_a_path)+{+ Vector<ResolvedPathRule> rules { rule("/a"sv, PathRule::Access::ReadWrite, true), rule("/a/b"sv, PathRule::Access::ReadOnly, true) };+ EXPECT(file_broker_allows(rules, "/a/b/c"sv, FileBrokerAccess::Write));+}++TEST_CASE(a_link_named_by_a_rule_exposes_its_metadata)+{+ Vector<ResolvedPathRule> rules { { "/a/link"sv, "/b/target"sv, PathRule::Access::ReadOnly, false } };+ EXPECT(file_broker_allows(rules, "/a/link"sv, FileBrokerAccess::Metadata));+ EXPECT(file_broker_allows(rules, "/a"sv, FileBrokerAccess::Metadata));+ EXPECT(!file_broker_allows(rules, "/a/link"sv, FileBrokerAccess::Read));+ EXPECT(file_broker_allows(rules, "/b/target"sv, FileBrokerAccess::Read));+}++TEST_CASE(only_a_writable_directory_lets_its_entries_change)+{+ Vector<ResolvedPathRule> rules { rule("/a/file"sv, PathRule::Access::ReadWrite, false), rule("/b"sv, PathRule::Access::ReadWrite, true), rule("/c"sv, PathRule::Access::ReadOnly, true) };+ EXPECT(!file_broker_allows(rules, "/a/file"sv, FileBrokerAccess::ChangeEntry));+ EXPECT(!file_broker_allows(rules, "/b"sv, FileBrokerAccess::ChangeEntry));+ EXPECT(file_broker_allows(rules, "/b/entry"sv, FileBrokerAccess::ChangeEntry));+ EXPECT(!file_broker_allows(rules, "/c/entry"sv, FileBrokerAccess::ChangeEntry));+}++// Hides Landlock, which is what a kernel without it looks like from here.+static void leave_only_the_broker_available()+{+ sock_filter filter[] = {+ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(seccomp_data, nr)),+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_landlock_create_ruleset, 0, 1),+ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | ENOSYS),+ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),+ };+ sock_fprog program {+ .len = sizeof(filter) / sizeof(filter[0]),+ .filter = filter,+ };+ if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0 || prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &program) < 0)+ _exit(100);+}++static void make_file(ByteString const& path)+{+ auto fd = open(path.characters(), O_CREAT | O_WRONLY | O_CLOEXEC, 0600);+ VERIFY(fd >= 0);+ VERIFY(write(fd, "k", 1) == 1);+ close(fd);+}++// Each check has its own exit code, so that a failure says which one it was.+static void check(int code, bool condition)+{+ if (!condition)+ _exit(code);+}++static int error_opening(ByteString const& path, int flags)+{+ auto fd = open(path.characters(), flags | O_CLOEXEC, 0600);+ if (fd < 0)+ return errno;+ close(fd);+ return 0;+}++static void confine(ReadonlySpan<PathRule> rules)+{+ leave_only_the_broker_available();+ check(50, !Sandbox::restrict_filesystem(rules).is_error());+ check(51, Sandbox::file_broker_is_active());++ Sandbox::SeccompPolicy policy;+ policy.allow_readonly_file_opens();+ policy.allow_filesystem_metadata_queries();+ policy.allow_filesystem_writes();+ policy.allow_file_descriptor_operations();+ policy.allow_ipc();+ policy.allow_socket_pairs();+ policy.allow_common_runtime();+ check(52, !policy.install().is_error());+}++TEST_CASE(the_broker_enforces_the_path_rules)+{+ char base_template[] = "/tmp/lb-file-broker-XXXXXX";+ VERIFY(mkdtemp(base_template));+ ByteString base { base_template };+ auto read_only = ByteString::formatted("{}/read-only", base);+ auto writable = ByteString::formatted("{}/writable", base);+ auto hidden = ByteString::formatted("{}/hidden", base);+ auto read_only_file = ByteString::formatted("{}/file", read_only);+ auto hidden_file = ByteString::formatted("{}/file", hidden);++ VERIFY(mkdir(read_only.characters(), 0700) == 0);+ VERIFY(mkdir(writable.characters(), 0700) == 0);+ VERIFY(mkdir(hidden.characters(), 0700) == 0);+ make_file(read_only_file);+ make_file(hidden_file);+ auto subdirectory = ByteString::formatted("{}/subdirectory", read_only);+ VERIFY(mkdir(subdirectory.characters(), 0700) == 0);++ auto child = fork();+ VERIFY(child >= 0);+ if (child == 0) {+ Vector<PathRule> rules;+ MUST(Sandbox::add_path_if_exists(rules, read_only, PathRule::Access::ReadOnly));+ MUST(Sandbox::add_path_if_exists(rules, writable, PathRule::Access::ReadWrite));+ MUST(Sandbox::add_path_if_exists(rules, "/proc/self"sv, PathRule::Access::ReadOnly));+ confine(rules);++ // Reading.+ auto fd = open(read_only_file.characters(), O_RDONLY | O_CLOEXEC);+ check(1, fd >= 0);+ char byte = 0;+ check(2, read(fd, &byte, 1) == 1 && byte == 'k');+ close(fd);++ // What the rules leave out.+ check(3, error_opening(hidden_file, O_RDONLY) == EACCES);+ check(4, error_opening("/etc/passwd"sv, O_RDONLY) == EACCES);+ check(5, error_opening(ByteString::formatted("{}/does-not-exist", hidden), O_RDONLY) == EACCES);++ // Writing.+ check(6, error_opening(read_only_file, O_WRONLY) == EACCES);+ check(7, error_opening(ByteString::formatted("{}/new", read_only), O_CREAT | O_WRONLY) == EACCES);+ auto created = ByteString::formatted("{}/created", writable);+ check(8, error_opening(created, O_CREAT | O_WRONLY) == 0);+ check(9, error_opening(created, O_CREAT | O_EXCL | O_WRONLY) == EEXIST);++ // Metadata.+ struct stat statbuf;+ check(10, stat(created.characters(), &statbuf) == 0 && S_ISREG(statbuf.st_mode));+ check(11, stat(hidden_file.characters(), &statbuf) < 0 && errno == EACCES);+ check(12, stat(base.characters(), &statbuf) == 0 && S_ISDIR(statbuf.st_mode));+ check(13, access(read_only_file.characters(), R_OK) == 0);+ check(14, access(read_only_file.characters(), W_OK) < 0 && errno == EACCES);++ // Making a link is refused rather than fatal, so a library that tries one can carry on.+ check(15, symlink(hidden_file.characters(), ByteString::formatted("{}/link", writable).characters()) < 0 && errno == EPERM);+ check(16, syscall(__NR_symlinkat, hidden_file.characters(), AT_FDCWD, ByteString::formatted("{}/link", writable).characters()) < 0 && errno == EPERM);++ // Changing the contents of a writable directory.+ auto directory = ByteString::formatted("{}/directory", writable);+ check(20, mkdir(directory.characters(), 0700) == 0);+ check(21, mkdir(ByteString::formatted("{}/nope", read_only).characters(), 0700) < 0 && errno == EACCES);+ check(28, mkdir(read_only.characters(), 0700) < 0 && errno == EEXIST);+ auto renamed = ByteString::formatted("{}/renamed", writable);+ check(22, rename(created.characters(), renamed.characters()) == 0);+ check(23, rename(renamed.characters(), ByteString::formatted("{}/stolen", hidden).characters()) < 0 && errno == EACCES);+ check(24, rename(read_only_file.characters(), ByteString::formatted("{}/stolen", writable).characters()) < 0 && errno == EACCES);+ check(25, unlink(renamed.characters()) == 0);+ check(26, unlink(read_only_file.characters()) < 0 && errno == EACCES);+ check(27, rmdir(directory.characters()) == 0);++ // Relative to a directory the process has open.+ auto directory_fd = open(read_only.characters(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);+ check(30, directory_fd >= 0);+ fd = openat(directory_fd, "file", O_RDONLY | O_CLOEXEC);+ check(31, fd >= 0);+ close(fd);+ check(32, openat(directory_fd, "../hidden/file", O_RDONLY | O_CLOEXEC) < 0 && errno == EACCES);++ // Going back up reports the directory that the path ends in.+ struct stat through_parent;+ check(36, stat(read_only.characters(), &statbuf) == 0);+ check(37, stat(ByteString::formatted("{}/subdirectory/..", read_only).characters(), &through_parent) == 0);+ check(38, statbuf.st_ino == through_parent.st_ino);++ // /proc/self has to mean this process, not the broker.+ fd = open("/proc/self/stat", O_RDONLY | O_CLOEXEC);+ check(33, fd >= 0);+ char status[32] {};+ check(34, read(fd, status, sizeof(status) - 1) > 0);+ close(fd);+ check(35, atoi(status) == getpid());+ char own_pid[32] {};+ check(39, readlink("/proc/self", own_pid, sizeof(own_pid) - 1) > 0 && atoi(own_pid) == getpid());+ memset(own_pid, 0, sizeof(own_pid));+ check(40, readlink("/proc/./self", own_pid, sizeof(own_pid) - 1) > 0 && atoi(own_pid) == getpid());++ // A trailing slash only ever names a directory.+ check(41, stat(ByteString::formatted("{}/", read_only_file).characters(), &statbuf) < 0 && errno == ENOTDIR);+ check(42, stat(ByteString::formatted("{}/", read_only).characters(), &statbuf) == 0);++ // A descriptor can be queried with no path at all.+ check(43, syscall(__NR_newfstatat, directory_fd, nullptr, &statbuf, AT_EMPTY_PATH) == 0 && S_ISDIR(statbuf.st_mode));++ _exit(0);+ }++ int status = 0;+ VERIFY(waitpid(child, &status, 0) == child);+ EXPECT(WIFEXITED(status));+ if (WIFEXITED(status))+ EXPECT_EQ(WEXITSTATUS(status), 0);++ EXPECT_EQ(error_opening(read_only_file, O_RDONLY), 0);+ EXPECT_EQ(error_opening(hidden_file, O_RDONLY), 0);++ (void)unlink(hidden_file.characters());+ (void)unlink(read_only_file.characters());+ (void)rmdir(subdirectory.characters());+ (void)rmdir(hidden.characters());+ (void)rmdir(writable.characters());+ (void)rmdir(read_only.characters());+ (void)rmdir(base.characters());+}++TEST_CASE(the_broker_does_not_follow_a_link_out_of_a_writable_directory)+{+ char base_template[] = "/tmp/lb-file-broker-XXXXXX";+ VERIFY(mkdtemp(base_template));+ ByteString base { base_template };+ auto writable = ByteString::formatted("{}/writable", base);+ auto hidden = ByteString::formatted("{}/hidden", base);+ auto hidden_file = ByteString::formatted("{}/file", hidden);+ auto link_to_file = ByteString::formatted("{}/link-to-file", writable);+ auto link_to_directory = ByteString::formatted("{}/link-to-directory", writable);++ VERIFY(mkdir(writable.characters(), 0700) == 0);+ VERIFY(mkdir(hidden.characters(), 0700) == 0);+ make_file(hidden_file);+ // The sandbox can't make these itself. A helper that found one, or was handed a directory with one, is the concern.+ VERIFY(symlink(hidden_file.characters(), link_to_file.characters()) == 0);+ VERIFY(symlink(hidden.characters(), link_to_directory.characters()) == 0);++ auto child = fork();+ VERIFY(child >= 0);+ if (child == 0) {+ Vector<PathRule> rules;+ MUST(Sandbox::add_path_if_exists(rules, writable, PathRule::Access::ReadWrite));+ confine(rules);++ check(1, error_opening(link_to_file, O_RDONLY) == EACCES);+ check(2, error_opening(link_to_file, O_WRONLY) == EACCES);+ check(3, error_opening(ByteString::formatted("{}/file", link_to_directory), O_RDONLY) == EACCES);+ check(4, error_opening(ByteString::formatted("{}/new", link_to_directory), O_CREAT | O_WRONLY) == EACCES);+ check(5, error_opening(link_to_file, O_RDONLY | O_NOFOLLOW) == ELOOP);++ // A link's own text is part of the directory the helper may read.+ char target[PATH_MAX];+ auto length = readlink(link_to_file.characters(), target, sizeof(target));+ check(6, length == static_cast<ssize_t>(hidden_file.length()));++ // Not following the link means that where it leads doesn't matter.+ check(8, syscall(__NR_faccessat2, AT_FDCWD, link_to_file.characters(), F_OK, AT_SYMLINK_NOFOLLOW) == 0);+ check(9, syscall(__NR_faccessat2, AT_FDCWD, link_to_file.characters(), F_OK, 0) < 0 && errno == EACCES);++ // Going up from an allowed directory is not a way out.+ check(7, error_opening(ByteString::formatted("{}/../hidden/file", writable), O_RDONLY) == EACCES);+ _exit(0);+ }++ int status = 0;+ VERIFY(waitpid(child, &status, 0) == child);+ EXPECT(WIFEXITED(status));+ if (WIFEXITED(status))+ EXPECT_EQ(WEXITSTATUS(status), 0);++ (void)unlink(link_to_directory.characters());+ (void)unlink(link_to_file.characters());+ (void)unlink(hidden_file.characters());+ (void)rmdir(hidden.characters());+ (void)rmdir(writable.characters());+ (void)rmdir(base.characters());+}++TEST_CASE(a_socket_cannot_create_a_file_outside_the_path_rules)+{+ char base_template[] = "/tmp/lb-file-broker-XXXXXX";+ VERIFY(mkdtemp(base_template));+ ByteString base { base_template };+ auto hidden = ByteString::formatted("{}/hidden", base);+ auto writable = ByteString::formatted("{}/writable", base);+ auto planted = ByteString::formatted("{}/planted", hidden);+ VERIFY(mkdir(hidden.characters(), 0700) == 0);+ VERIFY(mkdir(writable.characters(), 0700) == 0);++ auto child = fork();+ VERIFY(child >= 0);+ if (child == 0) {+ Vector<PathRule> rules;+ MUST(Sandbox::add_path_if_exists(rules, writable, PathRule::Access::ReadWrite));+ leave_only_the_broker_available();+ check(50, !Sandbox::restrict_filesystem(rules).is_error());++ Sandbox::SeccompPolicy policy;+ policy.allow_file_descriptor_operations();+ policy.allow_ipc();+ policy.allow_socket_pairs();+ policy.allow_common_runtime();+ policy.allow_network();+ check(52, !policy.install().is_error());++ int pair[2];+ check(1, socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, pair) == 0);++ sockaddr_un address {};+ address.sun_family = AF_UNIX;+ memcpy(address.sun_path, planted.characters(), planted.length());+ check(2, bind(pair[0], reinterpret_cast<sockaddr*>(&address), sizeof(address)) < 0 && errno == EACCES);++ // Internet sockets still bind, because the network policies are there for them.+ auto udp = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);+ check(3, udp >= 0);+ sockaddr_in loopback {};+ loopback.sin_family = AF_INET;+ loopback.sin_addr.s_addr = htonl(INADDR_LOOPBACK);+ check(4, bind(udp, reinterpret_cast<sockaddr*>(&loopback), sizeof(loopback)) == 0);+ socklen_t length = sizeof(loopback);+ check(5, getsockname(udp, reinterpret_cast<sockaddr*>(&loopback), &length) == 0 && loopback.sin_port != 0);++ // glibc binds one of these to ask the kernel about the network interfaces.+ auto netlink = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);+ check(6, netlink >= 0);+ sockaddr_nl netlink_address {};+ netlink_address.nl_family = AF_NETLINK;+ check(7, bind(netlink, reinterpret_cast<sockaddr*>(&netlink_address), sizeof(netlink_address)) == 0);+ _exit(0);+ }++ int status = 0;+ VERIFY(waitpid(child, &status, 0) == child);+ EXPECT(WIFEXITED(status));+ if (WIFEXITED(status))+ EXPECT_EQ(WEXITSTATUS(status), 0);++ struct stat statbuf;+ EXPECT(lstat(planted.characters(), &statbuf) < 0);++ (void)unlink(planted.characters());+ (void)rmdir(hidden.characters());+ (void)rmdir(writable.characters());+ (void)rmdir(base.characters());+}++TEST_CASE(a_helper_cannot_reach_a_unix_socket_outside_the_path_rules)+{+ char base_template[] = "/tmp/lb-file-broker-XXXXXX";+ VERIFY(mkdtemp(base_template));+ ByteString base { base_template };+ auto stream_path = ByteString::formatted("{}/stream", base);+ auto datagram_path = ByteString::formatted("{}/datagram", base);++ auto address_of = [](ByteString const& path) {+ sockaddr_un address {};+ address.sun_family = AF_UNIX;+ memcpy(address.sun_path, path.characters(), path.length());+ return address;+ };++ auto stream_address = address_of(stream_path);+ auto datagram_address = address_of(datagram_path);+ auto listener = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);+ auto receiver = socket(AF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);+ VERIFY(listener >= 0 && receiver >= 0);+ VERIFY(bind(listener, reinterpret_cast<sockaddr*>(&stream_address), sizeof(stream_address)) == 0);+ VERIFY(listen(listener, 4) == 0);+ VERIFY(bind(receiver, reinterpret_cast<sockaddr*>(&datagram_address), sizeof(datagram_address)) == 0);++ auto child = fork();+ VERIFY(child >= 0);+ if (child == 0) {+ Vector<PathRule> rules;+ leave_only_the_broker_available();+ check(50, !Sandbox::restrict_filesystem(rules).is_error());++ Sandbox::SeccompPolicy policy;+ policy.allow_file_descriptor_operations();+ policy.allow_ipc();+ policy.allow_socket_pairs();+ policy.allow_common_runtime();+ policy.allow_network();+ check(52, !policy.install().is_error());++ int unusable[2];+ check(1, socketpair(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0, unusable) < 0);+ check(5, socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0) < 0);+ check(6, socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0) < 0);++ for (int type : { SOCK_STREAM, SOCK_SEQPACKET }) {+ int pair[2];+ check(2, socketpair(AF_UNIX, type | SOCK_CLOEXEC, 0, pair) == 0);++ auto cannot_leave_its_pair = [&](int code) {+ check(code, connect(pair[0], reinterpret_cast<sockaddr*>(&stream_address), sizeof(stream_address)) < 0);+ check(code + 1, connect(pair[0], reinterpret_cast<sockaddr*>(&datagram_address), sizeof(datagram_address)) < 0);+ (void)sendto(pair[0], "x", 1, MSG_NOSIGNAL | MSG_DONTWAIT, reinterpret_cast<sockaddr*>(&datagram_address), sizeof(datagram_address));+ };++ cannot_leave_its_pair(10);+ check(3, shutdown(pair[0], SHUT_RDWR) == 0);+ cannot_leave_its_pair(20);+ check(4, close(pair[1]) == 0);+ cannot_leave_its_pair(30);+ }+ _exit(0);+ }++ int status = 0;+ VERIFY(waitpid(child, &status, 0) == child);+ EXPECT(WIFEXITED(status));+ if (WIFEXITED(status))+ EXPECT_EQ(WEXITSTATUS(status), 0);++ char byte = 0;+ EXPECT(accept(listener, nullptr, nullptr) < 0 && errno == EAGAIN);+ EXPECT(recv(receiver, &byte, 1, 0) < 0 && errno == EAGAIN);++ close(listener);+ close(receiver);+ (void)unlink(stream_path.characters());+ (void)unlink(datagram_path.characters());+ (void)rmdir(base.characters());+}++TEST_CASE(files_are_refused_as_soon_as_the_broker_runs)+{+ char base_template[] = "/tmp/lb-file-broker-XXXXXX";+ VERIFY(mkdtemp(base_template));+ ByteString base { base_template };+ auto allowed = ByteString::formatted("{}/allowed", base);+ auto hidden = ByteString::formatted("{}/hidden", base);+ auto allowed_file = ByteString::formatted("{}/file", allowed);+ auto hidden_file = ByteString::formatted("{}/file", hidden);+ auto linked_file = ByteString::formatted("{}/linked", allowed);+ VERIFY(mkdir(allowed.characters(), 0700) == 0);+ VERIFY(mkdir(hidden.characters(), 0700) == 0);+ make_file(allowed_file);+ make_file(hidden_file);++ auto child = fork();+ VERIFY(child >= 0);+ if (child == 0) {+ Vector<PathRule> rules;+ MUST(Sandbox::add_path_if_exists(rules, allowed, PathRule::Access::ReadOnly));+ leave_only_the_broker_available();+ check(50, !Sandbox::restrict_filesystem(rules).is_error());++ // No policy yet, as while a helper sets up its GPU driver.+ check(1, error_opening(hidden_file, O_RDONLY) == EACCES);+ check(2, error_opening(allowed_file, O_RDONLY) == 0);+ struct stat statbuf;+ check(3, stat(hidden_file.characters(), &statbuf) < 0 && errno == EACCES);+ check(4, truncate(hidden_file.characters(), 0) < 0 && errno == EACCES);+ check(5, chmod(hidden_file.characters(), 0777) < 0 && errno == EPERM);+ char value[8];+ check(6, lgetxattr(hidden_file.characters(), "user.test", value, sizeof(value)) < 0 && errno == EOPNOTSUPP);+ check(7, link(hidden_file.characters(), linked_file.characters()) < 0 && errno == EPERM);+ auto inotify = inotify_init1(IN_CLOEXEC);+ check(8, inotify >= 0 && inotify_add_watch(inotify, hidden_file.characters(), IN_ALL_EVENTS) < 0 && errno == EACCES);+ char* arguments[] = { const_cast<char*>("true"), nullptr };+ check(9, execve("/bin/true", arguments, nullptr) < 0 && errno == EACCES);+ check(10, ptrace(PTRACE_ATTACH, getppid(), nullptr, nullptr) < 0 && errno == EPERM);++ // open_tree(), openat2() and io_uring_setup(), by the numbers that every architecture shares.+ check(11, syscall(428, AT_FDCWD, hidden_file.characters(), 0) < 0 && errno == EPERM);+ check(12, syscall(437, AT_FDCWD, hidden_file.characters(), nullptr, 0) < 0 && errno == ENOSYS);+ check(13, syscall(425, 1, nullptr) < 0 && errno == ENOSYS);+ check(14, syscall(472) < 0 && errno == ENOSYS);+#if ARCH(X86_64)+ check(15, syscall(0x40000000 | __NR_openat, AT_FDCWD, hidden_file.characters(), O_RDONLY) < 0 && errno == ENOSYS);+#endif+ _exit(0);+ }++ int status = 0;+ VERIFY(waitpid(child, &status, 0) == child);+ EXPECT(WIFEXITED(status));+ if (WIFEXITED(status))+ EXPECT_EQ(WEXITSTATUS(status), 0);++ struct stat statbuf;+ EXPECT(stat(hidden_file.characters(), &statbuf) == 0 && statbuf.st_size == 1 && (statbuf.st_mode & 0777) == 0600);+ EXPECT(lstat(linked_file.characters(), &statbuf) < 0);++ (void)unlink(allowed_file.characters());+ (void)unlink(hidden_file.characters());+ (void)rmdir(allowed.characters());+ (void)rmdir(hidden.characters());+ (void)rmdir(base.characters());+}++TEST_CASE(a_thread_that_blocks_every_signal_still_reaches_the_broker)+{+ char base_template[] = "/tmp/lb-file-broker-XXXXXX";+ VERIFY(mkdtemp(base_template));+ ByteString base { base_template };+ auto file = ByteString::formatted("{}/file", base);+ make_file(file);++ auto child = fork();+ VERIFY(child >= 0);+ if (child == 0) {+ rlimit limit { 0, 0 };+ setrlimit(RLIMIT_CORE, &limit);++ Vector<PathRule> rules;+ MUST(Sandbox::add_path_if_exists(rules, base, PathRule::Access::ReadOnly));+ leave_only_the_broker_available();+ check(50, !Sandbox::restrict_filesystem(rules).is_error());++ Sandbox::SeccompPolicy policy;+ policy.allow_readonly_file_opens();+ policy.allow_file_descriptor_operations();+ policy.allow_threads();+ policy.allow_common_runtime();+ check(52, !policy.install().is_error());++ // As glibc does while a thread exits, which can still open a file.+ sigset_t all_signals;+ sigfillset(&all_signals);+ check(1, pthread_sigmask(SIG_BLOCK, &all_signals, nullptr) == 0);+ check(2, error_opening(file, O_RDONLY) == 0);++ sigset_t blocked;+ check(3, pthread_sigmask(SIG_SETMASK, nullptr, &blocked) == 0);+ check(4, sigismember(&blocked, SIGUSR1) == 1 && sigismember(&blocked, SIGSYS) == 0);++ sigset_t user_signal;+ sigemptyset(&user_signal);+ sigaddset(&user_signal, SIGUSR1);+ check(5, pthread_sigmask(SIG_UNBLOCK, &user_signal, nullptr) == 0);+ check(6, pthread_sigmask(SIG_SETMASK, nullptr, &blocked) == 0);+ check(7, sigismember(&blocked, SIGUSR1) == 0 && sigismember(&blocked, SIGUSR2) == 1);+ _exit(0);+ }++ int status = 0;+ VERIFY(waitpid(child, &status, 0) == child);+ EXPECT(WIFEXITED(status));+ if (WIFEXITED(status))+ EXPECT_EQ(WEXITSTATUS(status), 0);++ (void)unlink(file.characters());+ (void)rmdir(base.characters());+}++TEST_CASE(a_policy_that_refuses_a_path_still_wins_over_the_broker)+{+ char base_template[] = "/tmp/lb-file-broker-XXXXXX";+ VERIFY(mkdtemp(base_template));+ ByteString base { base_template };+ auto file = ByteString::formatted("{}/file", base);+ make_file(file);++ auto child = fork();+ VERIFY(child >= 0);+ if (child == 0) {+ Vector<PathRule> rules;+ MUST(Sandbox::add_path_if_exists(rules, base, PathRule::Access::ReadOnly));+ leave_only_the_broker_available();+ check(50, !Sandbox::restrict_filesystem(rules).is_error());+ check(1, error_opening(file, O_RDONLY) == 0);++ Sandbox::SeccompPolicy policy;+ policy.deny_readonly_filesystem_probes();+ policy.allow_file_descriptor_operations();+ policy.allow_common_runtime();+ check(52, !policy.install().is_error());+ check(2, error_opening(file, O_RDONLY) == EACCES);+ _exit(0);+ }++ int status = 0;+ VERIFY(waitpid(child, &status, 0) == child);+ EXPECT(WIFEXITED(status));+ if (WIFEXITED(status))+ EXPECT_EQ(WEXITSTATUS(status), 0);++ (void)unlink(file.characters());+ (void)rmdir(base.characters());+}++TEST_CASE(process_creation_without_landlock_cannot_signal_other_processes)+{+ auto parent = getpid();+ auto child = fork();+ VERIFY(child >= 0);+ if (child == 0) {+ leave_only_the_broker_available();+ check(50, !Sandbox::restrict_filesystem().is_error());+ check(51, !Sandbox::signals_stay_within_the_process_tree());++ Sandbox::SeccompPolicy policy;+ policy.allow_common_runtime();+ policy.allow_process_creation();+ policy.allow_file_descriptor_operations();+ check(52, !policy.install().is_error());++ check(1, syscall(__NR_tgkill, getpid(), syscall(__NR_gettid), 0) == 0);+ check(2, syscall(__NR_tgkill, parent, parent, 0) < 0 && errno == EPERM);++ auto grandchild = fork();+ check(3, grandchild >= 0);+ if (grandchild == 0) {+ check(4, syscall(__NR_tgkill, parent, parent, 0) < 0 && errno == EPERM);+ _exit(0);+ }+ int status = 0;+ check(6, waitpid(grandchild, &status, 0) == grandchild);+ check(WIFEXITED(status) ? WEXITSTATUS(status) : 7, WIFEXITED(status) && WEXITSTATUS(status) == 0);+ _exit(0);+ }++ int status = 0;+ VERIFY(waitpid(child, &status, 0) == child);+ EXPECT(WIFEXITED(status));+ if (WIFEXITED(status))+ EXPECT_EQ(WEXITSTATUS(status), 0);+}++TEST_CASE(a_policy_that_sends_nothing_to_the_broker_still_cannot_pair_sockets)+{+ // ImageDecoder's sandbox: no paths at all, and no sockets of its own.+ auto child = fork();+ VERIFY(child >= 0);+ if (child == 0) {+ rlimit limit { 0, 0 };+ setrlimit(RLIMIT_CORE, &limit);+ leave_only_the_broker_available();+ check(50, !Sandbox::restrict_filesystem().is_error());++ Sandbox::SeccompPolicy policy;+ policy.deny_readonly_filesystem_probes();+ policy.allow_file_descriptor_operations();+ policy.allow_ipc();+ policy.allow_common_runtime();+ check(52, !policy.install().is_error());++ check(1, error_opening("/", O_RDONLY) == EACCES);+ int fds[2];+ (void)socketpair(AF_UNIX, SOCK_STREAM, 0, fds);+ _exit(0);+ }++ int status = 0;+ VERIFY(waitpid(child, &status, 0) == child);+ EXPECT(WIFSIGNALED(status));+ if (WIFSIGNALED(status))+ EXPECT_EQ(WTERMSIG(status), SIGSYS);+}++TEST_CASE(the_broker_goes_away_with_the_helper)+{+ int pipe_fds[2];+ VERIFY(pipe(pipe_fds) == 0);++ auto child = fork();+ VERIFY(child >= 0);+ if (child == 0) {+ close(pipe_fds[0]);+ leave_only_the_broker_available();+ check(1, !Sandbox::restrict_filesystem().is_error());+ // Our write end stays open in the broker only if it failed to close what it inherited.+ _exit(0);+ }++ close(pipe_fds[1]);+ int status = 0;+ VERIFY(waitpid(child, &status, 0) == child);+ EXPECT(WIFEXITED(status) && WEXITSTATUS(status) == 0);++ char byte;+ EXPECT_EQ(read(pipe_fds[0], &byte, 1), 0);+ close(pipe_fds[0]);+}diff --git a/Tests/LibSandbox/TestLandlock.cpp b/Tests/LibSandbox/TestLandlock.cppindex 8c69bb6ca47..8e660711e62 100644--- a/Tests/LibSandbox/TestLandlock.cpp+++ b/Tests/LibSandbox/TestLandlock.cpp@@ -8,6 +8,7 @@#include <LibSandbox/Seccomp.h>#include <LibTest/TestCase.h>#include <errno.h>+#include <fcntl.h>#include <linux/audit.h>#include <linux/filter.h>#include <linux/landlock.h>@@ -22,21 +23,19 @@#include <sys/wait.h>#include <unistd.h>-enum class Outcome {- Refused,- Confined,-};-// Makes the kernel answer the Landlock version probe with the given errno (0 makes the probe return an ABI of 0), then-// asks for a Landlock sandbox in a child process.-static Outcome restrict_filesystem_when_version_probe_returns(u32 error)+// asks for a sandbox in a child process. Whatever else the kernel can do, a helper must still get one, and it must keep+// the helper from its files at once.+static bool can_restrict_filesystem_when_version_probe_returns(u32 error){+ char file_template[] = "/tmp/lb-landlock-XXXXXX";+ auto file_fd = mkstemp(file_template);+ VERIFY(file_fd >= 0);+ close(file_fd);+auto child = fork();VERIFY(child >= 0);if (child == 0) {- // CI allows a missing Landlock for the helpers it starts. This test is about the default.- unsetenv("LADYBIRD_UNSAFE_ALLOW_MISSING_LANDLOCK");-sock_filter filter[] = {BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(seccomp_data, nr)),BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_landlock_create_ruleset, 0, 1),@@ -50,64 +49,38 @@ static Outcome restrict_filesystem_when_version_probe_returns(u32 error)if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0 || prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &program) < 0)_exit(2);- auto result = Sandbox::restrict_filesystem();- _exit(result.is_error() ? 0 : 1);+ if (Sandbox::restrict_filesystem().is_error())+ _exit(1);+ auto fd = open(file_template, O_RDONLY | O_CLOEXEC);+ _exit(fd < 0 && errno == EACCES ? 0 : 3);}int status = 0;VERIFY(waitpid(child, &status, 0) == child);+ (void)unlink(file_template);VERIFY(WIFEXITED(status));- VERIFY(WEXITSTATUS(status) == 0 || WEXITSTATUS(status) == 1);- return WEXITSTATUS(status) == 0 ? Outcome::Refused : Outcome::Confined;-}--TEST_CASE(a_kernel_without_landlock_refuses_the_sandbox)-{- EXPECT_EQ(restrict_filesystem_when_version_probe_returns(ENOSYS), Outcome::Refused);+ VERIFY(WEXITSTATUS(status) == 0 || WEXITSTATUS(status) == 1 || WEXITSTATUS(status) == 3);+ return WEXITSTATUS(status) == 0;}-TEST_CASE(a_kernel_with_landlock_disabled_refuses_the_sandbox)+TEST_CASE(a_kernel_without_landlock_still_gets_a_sandbox){- EXPECT_EQ(restrict_filesystem_when_version_probe_returns(EOPNOTSUPP), Outcome::Refused);+ EXPECT(can_restrict_filesystem_when_version_probe_returns(ENOSYS));}-TEST_CASE(a_landlock_abi_of_zero_refuses_the_sandbox)+TEST_CASE(a_kernel_with_landlock_disabled_still_gets_a_sandbox){- EXPECT_EQ(restrict_filesystem_when_version_probe_returns(0), Outcome::Refused);+ EXPECT(can_restrict_filesystem_when_version_probe_returns(EOPNOTSUPP));}-TEST_CASE(a_container_that_blocks_landlock_refuses_the_sandbox)+TEST_CASE(a_landlock_abi_of_zero_still_gets_a_sandbox){- EXPECT_EQ(restrict_filesystem_when_version_probe_returns(EPERM), Outcome::Refused);+ EXPECT(can_restrict_filesystem_when_version_probe_returns(0));}-TEST_CASE(a_missing_landlock_can_be_allowed_explicitly)+TEST_CASE(a_container_that_blocks_landlock_still_gets_a_sandbox){- auto child = fork();- VERIFY(child >= 0);- if (child == 0) {- setenv("LADYBIRD_UNSAFE_ALLOW_MISSING_LANDLOCK", "1", 1);- sock_filter filter[] = {- BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(seccomp_data, nr)),- BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_landlock_create_ruleset, 0, 1),- BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | ENOSYS),- BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),- };- sock_fprog program {- .len = sizeof(filter) / sizeof(filter[0]),- .filter = filter,- };- if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0 || prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &program) < 0)- _exit(2);-- auto result = Sandbox::restrict_filesystem();- _exit(result.is_error() ? 1 : 0);- }-- int status = 0;- VERIFY(waitpid(child, &status, 0) == child);- VERIFY(WIFEXITED(status));- EXPECT_EQ(WEXITSTATUS(status), 0);+ EXPECT(can_restrict_filesystem_when_version_probe_returns(EPERM));}TEST_CASE(a_process_with_a_second_thread_refuses_the_sandbox)@@ -226,6 +199,7 @@ TEST_CASE(signals_stay_within_the_landlock_process_tree)if (child == 0) {MUST(Sandbox::install_no_new_privileges());MUST(Sandbox::restrict_filesystem());+ VERIFY(Sandbox::signals_stay_within_the_process_tree());Sandbox::SeccompPolicy policy;policy.allow_common_runtime();policy.allow_process_creation();diff --git a/Tests/LibWebView/test-webdriver-compositor-reconnect.py b/Tests/LibWebView/test-webdriver-compositor-reconnect.pyindex 76442fdff17..aa42fadf6b9 100755--- a/Tests/LibWebView/test-webdriver-compositor-reconnect.py+++ b/Tests/LibWebView/test-webdriver-compositor-reconnect.py@@ -42,10 +42,12 @@ def descendants_named(root_pid, process_name):found = []while pending:for pid, command in children.get(pending.pop(), []):- pending.append(pid)arguments = shlex.split(command)+ # A helper's own children, such as its file broker, carry the helper's command line but are not the helper.if arguments and Path(arguments[0]).name == process_name:found.append(pid)+ else:+ pending.append(pid)return founddiff --git a/Tests/LibWebView/test-webdriver-crash-report.py b/Tests/LibWebView/test-webdriver-crash-report.pyindex cafa6343b35..ceeab814417 100755--- a/Tests/LibWebView/test-webdriver-crash-report.py+++ b/Tests/LibWebView/test-webdriver-crash-report.py@@ -46,12 +46,14 @@ def crash_helper(webdriver_pid, process_name):targets = []while pending:for pid, command in children.get(pending.pop(), []):- pending.append(pid)arguments = shlex.split(command)+ # A helper's own children, such as its file broker, carry the helper's command line but are not the helper.if arguments and Path(arguments[0]).name == process_name:assert "--crash-report-fd" in arguments, f"{process_name} has no capture descriptor"assert "--disable-sandbox" not in arguments, f"{process_name} is not sandboxed"targets.append(pid)+ else:+ pending.append(pid)assert len(targets) == 1, f"Expected one {process_name} child, found {len(targets)}"os.kill(targets[0], signal.SIGSEGV)