eBPF-based security platform
upatches/app-sandbox: add a package that sandboxes applications
John Fastabend854744fea7ca
diff --git a/Documentation/upatches/learn/examples.rst b/Documentation/upatches/learn/examples.rstindex ed157dc5..ff0b2174 100644--- a/Documentation/upatches/learn/examples.rst+++ b/Documentation/upatches/learn/examples.rst@@ -10,9 +10,10 @@ Example packagesThe tree ships packages under :src:`upatches/`: ``kernel-obs``, acomplete observability package with arena tables, serializers, decoders-and generated ``.rodata``, and in ``kernel-cve`` three small CVE+and generated ``.rodata``, in ``kernel-cve`` three small CVEdetectors exported from a mitigation campaign and one CVE mitigation,-each a package of its own.+each a package of its own, and ``app-sandbox``, which enforces with+policy labels and generated ``.rodata``.kernel-obs----------@@ -125,6 +126,63 @@ through a pipe into an ``AF_ALG`` aead socket and reports whether thebug corrupted it; ``t3115-af-alg-block`` drives it to check themitigation refuses the socket.+app-sandbox+-----------++.. list-table::+ :header-rows: 1+ :widths: 28 72++ * - Item+ - Content+ * - Package+ - ``app-sandbox``, from :src:`upatches/app-sandbox/Beefile`+ * - upatch+ - ``app-sandbox``, built from ``app-sandbox.bpf.c``: twelve ``lsm``+ programs and no state of its own+ * - Policy labels+ - one ``[[upatches.policy]]`` table per sandbox, ``apache`` and+ ``php-fpm``, each a bit and the executables that put a task in+ the sandbox+ * - Generated data+ - ``sandbox_policy``, which ``gen_policy.py`` writes from+ ``sandbox.toml`` and the policy bits of the Beefile+ * - Tree entry+ - ``app-sandbox``, without a selector++A task that executed a file of a sandbox carries its policy bit in+``shirudo_task_policy``, and so do its children. The programs read that+bit and the rules of ``sandbox_policy``, and refuse with ``EACCES``:++.. list-table::+ :header-rows: 1+ :widths: 34 66++ * - Hook+ - Refuses, for a task in a sandbox+ * - ``lsm.s/bprm_check_security``+ - executing a file that carries neither the sandbox's bit nor one+ its ``exec`` rule names+ * - ``lsm/socket_connect``, ``lsm/socket_sendmsg``+ - an IPv4 or IPv6 peer outside the networks of its ``network`` rule+ * - ``lsm/socket_create``+ - a raw or packet socket, when it has a ``network`` rule+ * - ``lsm/inode_create``, ``lsm/inode_mkdir``, ``lsm/inode_mknod``,+ ``lsm/inode_symlink``, ``lsm/inode_link``+ - a new name that matches a ``deny.create`` pattern+ * - ``lsm/inode_rename``+ - a rename from or to a name that matches a ``deny.rename`` pattern+ * - ``lsm/file_open``, ``lsm/inode_setattr``+ - opening for writing, or truncating, a name that matches a+ ``deny.write`` pattern++``gen_policy.py`` joins the two halves of a sandbox by its name: it+reads the bit from the Beefile and the rules from ``sandbox.toml``, and+fails the build for rules without a policy table. The package's+``README.md`` describes the rule keys and what the sandboxes do not+cover. :src:`tools/put-shields` publishes it with the shields of+``kernel-cve``.+Related-------diff --git a/Documentation/upatches/publish/publishing.rst b/Documentation/upatches/publish/publishing.rstindex 461c3b85..5d350be5 100644--- a/Documentation/upatches/publish/publishing.rst+++ b/Documentation/upatches/publish/publishing.rst@@ -178,7 +178,9 @@ It builds every ``Beefile`` and ``*.bee`` under :src:`upatches/` that hasan ``[upatches.tree]`` entry, or, when you name Beefiles and directoriesafter the namespace, those Beefiles and the ones under thosedirectories, each once, and pushes each package to-``oci://<registry>/<namespace>/<package>``. Each entry of+``oci://<registry>/<namespace>/<package>``. A build finds the checkout's+BPF headers, and a package that brings no ``vmlinux.h`` builds against+``vendor/linux/vmlinux.h`` of the checkout. Each entry of``<namespace>/bpm-index:stable`` then names a shield's repository,version and digests. Give ``--new-index`` for a namespace that has noindex, and a new ``--version`` for every run after the first: ``bpmdiff --git a/tools/put-shields b/tools/put-shieldsindex ff5f9d07..70d3ecac 100755--- a/tools/put-shields+++ b/tools/put-shields@@ -15,7 +15,8 @@# Beefiles are the ones given and, for each directory given, every# Beefile and *.bee under it that has one; without either, those under# upatches/. Each is built with `shirudo bpm build` at-# <version> and pushed with `shirudo bpm push` to+# <version>, with the BPF headers of this checkout and, for a package+# without a vmlinux.h of its own, its vendor/linux/vmlinux.h, and pushed with `shirudo bpm push` to# oci://<registry>/<namespace>/<package>, which adds it to# <namespace>/bpm-index:stable, signed with the same keys. --new-index# starts that index with the first package, for a namespace that never@@ -164,6 +165,8 @@ case "${SHIRUDO_BUILD:-}" inesacmkdir "$work/out"+# bpm build looks for shirudo's BPF headers in the directory it runs in.+[ ! -d "$repo/bpf/lib" ] || ln -s "$repo/bpf" "$work/out/bpf"while read -r beefile; do# A Java shield's source is a prebuilt .jar; its build.sh --jar-only# makes it, where a BPF shield's source compiles in bpm build.@@ -172,8 +175,13 @@ while read -r beefile; do( cd "$dir" && ./build.sh --jar-only ) </dev/null ||fail "cannot build the jar of $beefile"fi+ # A package that brings no vmlinux.h builds against the checkout's.+ vmlinux=+ [ -e "$dir/vmlinux.h" ] || [ ! -e "$repo/vendor/linux/vmlinux.h" ] ||+ vmlinux=$repo/vendor/linux/vmlinux.hbuilt=$(cd "$work/out" && "$shirudo" bpm build "$dir" \- --file "$beefile" --version "$version" --keys-dir "$keys" </dev/null) ||+ --file "$beefile" --version "$version" --keys-dir "$keys" \+ ${vmlinux:+--vmlinux "$vmlinux"} </dev/null) ||fail "cannot build $beefile"bee=$(basename "$(printf '%s\n' "$built" | tail -n 1)")name=$(basename "$bee" "-$version.bee")diff --git a/upatches/app-sandbox/.gitignore b/upatches/app-sandbox/.gitignorenew file mode 100644index 00000000..ac072e70--- /dev/null+++ b/upatches/app-sandbox/.gitignore@@ -0,0 +1 @@+/*.beediff --git a/upatches/app-sandbox/Beefile b/upatches/app-sandbox/Beefilenew file mode 100644index 00000000..7b465d8a--- /dev/null+++ b/upatches/app-sandbox/Beefile@@ -0,0 +1,35 @@+[package]+name = "app-sandbox"+description = "Sandboxes for applications: what they execute, where they connect, which files they write"+license = "GPL-2.0 OR BSD-2-Clause"+authors = ["Authors of shirudo"]++[[files]]+source = "sandbox.toml"++[[files]]+source = "gen_policy.py"++[[upatches]]+source = "app-sandbox.bpf.c"++[[upatches.rodata]]+symbol = "sandbox_policy"+input = "sandbox.toml"+generator = ["python3", "gen_policy.py"]+update = ["python3", "gen_policy.py"]++# One table per sandbox: sandbox.toml gives the rules of the tasks that+# execute one of its paths.+[[upatches.policy]]+id = "apache"+bit = 0x1+paths = ["/usr/sbin/apache2", "/usr/sbin/httpd", "/usr/local/apache2/bin/httpd"]++[[upatches.policy]]+id = "php-fpm"+bit = 0x2+paths = ["/usr/sbin/php-fpm8.2", "/usr/sbin/php-fpm8.3", "/usr/sbin/php-fpm8.4", "/usr/local/sbin/php-fpm"]++[upatches.tree]+id = "app-sandbox"diff --git a/upatches/app-sandbox/README.md b/upatches/app-sandbox/README.mdnew file mode 100644index 00000000..10e78fd2--- /dev/null+++ b/upatches/app-sandbox/README.md@@ -0,0 +1,147 @@+# app-sandbox++The `app-sandbox` package installs the `app-sandbox` upatch, which puts+applications in sandboxes. A sandbox restricts every task that executed+one of its files, and the tasks those start, in three things:++- what it executes: its own files and those of the policies it names;+- where it connects and sends: the networks it names;+- which files it creates, renames and opens for writing or truncates:+ none whose name matches a pattern it denies.++The package ships sandboxes for Apache httpd and PHP-FPM that keep a web+application from writing the PHP files it serves, from starting other+programs and from reaching beyond private networks: what an attacker+who found a hole in the application does first. Replace them with+sandboxes for your own applications.++A sandbox restricts and never grants: a task in it keeps every limit it+had. It is not a boundary against root outside the sandbox, and a file+replaced after the load is a new file without the label, see "Limits".++## Define a sandbox++A sandbox has two parts. The `Beefile` gives it a name, a policy bit and+the executables that put a task in it, as a `[[upatches.policy]]` table+(see `Documentation/reference/formats/beefile.rst`):++```toml+[[upatches.policy]]+id = "apache"+bit = 0x1+paths = ["/usr/sbin/apache2", "/usr/sbin/httpd"]+```++`sandbox.toml` gives the rules of the sandbox of that name:++```toml+[networks]+localnet = ["127.0.0.0/8", "10.0.0.0/8", "::1/128"]++[sandbox.apache]+exec = ["apache-helpers"]+network = ["@localnet", "192.0.2.10/32"]++[sandbox.apache.deny]+create = ["*.php"]+rename = ["*.php"]+write = ["*.php"]+```++| Key | Without it | With it |+|---|---|---|+| `exec` | The task executes anything. | It executes only files labeled with its own policy or with one of the policy IDs listed, each a `[[upatches.policy]]` table of the Beefile. `exec = []` allows its own files alone. |+| `network` | The task connects anywhere. | It connects and sends only to the networks listed, IPv4 or IPv6 in CIDR form, or `@<name>` for a list of `[networks]`. An IPv4 network also covers its IPv4-mapped IPv6 form. It creates no raw and no packet socket. `network = []` allows no IP peer. |+| `deny.create` | | It creates no file, directory, device, symbolic link or hard link with a matching name. |+| `deny.rename` | | It renames no file from or to a matching name. |+| `deny.write` | | It opens no file with a matching name for writing and does not truncate one. |++A pattern is matched against the last component of the path. It is the+name itself, or holds one `*` for any run of bytes, and `?` for any one+byte, with at most 32 bytes on each side of the `*`.++A script is executed with its interpreter, and the kernel asks for+both: a sandbox with `exec` runs a script only when the script and its+interpreter are each labeled with a policy the sandbox allows.++The package holds up to 32 sandboxes with `exec`, 128 networks and 64+patterns. A task in two sandboxes, one that executed files of both, is+held to the rules of each.++`gen_policy.py` turns `sandbox.toml` into the `sandbox_policy` variable+of the upatch when `shirudo bpm build` runs, and fails the build for a+sandbox the Beefile declares no policy for, a network or a pattern it+cannot read and a table it does not know. Read back what a build holds+with:++```sh+shirudo bpm info data app-sandbox-<version>.bee upatches/app-sandbox.upatch+```++## Build and publish++Build in a directory that holds shirudo's BPF headers and a `vmlinux.h`+(see `Documentation/start/guides/publish-package.rst`):++```sh+shirudo bpm build upatches/app-sandbox --version 1.0.0 --keys-dir <keys>+shirudo bpm push app-sandbox-1.0.0.bee oci://<registry>/<namespace>/app-sandbox --keys-dir <keys>+shirudo bpm tree append app-sandbox-1.0.0.bee oci://<registry>/<tree> --keys-dir <keys>+```++The Beefile has a tree entry without a selector, so every node that+syncs the tree loads the upatch; on a node without the applications it+labels nothing and restricts nothing. Add a selector to load it only+where they run:++```toml+[upatches.tree.selector.labels]+role = ["web"]+```++`tools/put-shields`, and `make shields` with it, publishes the package+with the other shields of `upatches/`.++`--rodata-input sandbox=<file>` builds with other rules for the+policies of the Beefile, and `shirudo bpm config update` signs new rules+into a package already built, without compiling it again.++## What a load does++The load labels each path of the Beefile that exists on the target with+its policy bit, in the `security.bpf.shirudo.policy` xattr. shirudo+gives a task the bits of every file it executes, and its children+inherit them, so a task enters a sandbox at its next `execve()` of a+labeled file: restart the application after the first load. An unload+leaves the labels, which restrict nothing once the upatch is gone.++Every refusal is `EACCES`.++## Limits++- A path that does not exist at the load is not labeled, and a file+ that replaces a labeled one, as a package upgrade does, is a new file+ without the label. Load the upatch again after the application is+ installed or upgraded.+- The file rules name files, not their contents: a descriptor that was+ open for writing before the task entered the sandbox, or that another+ process passes to it, still writes.+- The network rules cover `connect()` and the address of `sendmsg()`+ and `sendto()` on IPv4 and IPv6 sockets. Other address families pass,+ and so does what a task receives or accepts.+- Root outside a sandbox can remove nothing of it, as only shirudo's+ runtime sets the label, but a task that root starts from an unlabeled+ file is in no sandbox.++## Kernels and cost++The programs keep no state of their own: they read the task's policy+bits and the rules, which never change after the load, so they are+right on every preemption model.++A task in no sandbox pays one task-storage lookup at each hook, and+none when it opens a file for reading. The hooks are the LSM hooks of+`execve()`, `connect()`, `sendmsg()`, `socket()`, the creation, linking+and renaming of a directory entry, an open for writing and a change of+size. A task in a sandbox pays a scan of the rules on top: at most 128+networks, or 64 patterns of at most 64 bytes.diff --git a/upatches/app-sandbox/app-sandbox.bpf.c b/upatches/app-sandbox/app-sandbox.bpf.cnew file mode 100644index 00000000..75c9b4f1--- /dev/null+++ b/upatches/app-sandbox/app-sandbox.bpf.c@@ -0,0 +1,433 @@+// SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause+/*+ * Copyright (c) 2026 Authors of shirudo+ *+ * app-sandbox: a task that carries a sandbox's policy bit executes only+ * the files its sandbox names, connects only to the networks it names,+ * and does not create, rename or open for writing a file whose name+ * matches a pattern it denies. gen_policy.py writes sandbox_policy.+ */+#include "vmlinux.h"+#include <bpf/bpf_endian.h>+#include <bpf/bpf_helpers.h>+#include <bpf/bpf_tracing.h>+#include "policy.h"++char _license[] SEC("license") = "Dual BSD/GPL";++#define SANDBOX_MAX 32+#define SANDBOX_NET_MAX 128+#define SANDBOX_FIM_MAX 64+#define SANDBOX_GLOB_MAX 32++#define SANDBOX_FIM_CREATE 0x1+#define SANDBOX_FIM_RENAME 0x2+#define SANDBOX_FIM_WRITE 0x4++#define EACCES 13+#define ENODATA 61+#define EOPNOTSUPP 95+#define AF_UNSPEC 0+#define AF_INET 2+#define AF_INET6 10+#define AF_PACKET 17+#define SOCK_RAW 3+#define SOCK_TYPE_MASK 0xf+#define FMODE_WRITE 0x2+#define ATTR_SIZE 0x8+#define NAME_MAX 255++/* gen_policy.py packs these structs byte for byte. */+struct sandbox_exec_rule {+ __u64 sandbox;+ __u64 allowed;+};++/* An address in network byte order, IPv4 as ::ffff:a.b.c.d. */+union sandbox_addr {+ __u8 bytes[16];+ __be32 words[4];+ __u64 halves[2];+};++struct sandbox_net_rule {+ __u64 sandboxes;+ __u64 addr[2];+ __u64 mask[2];+};++struct sandbox_fim_rule {+ __u64 sandboxes;+ __u8 ops;+ __u8 prefix_len;+ __u8 suffix_len;+ __u8 wildcard;+ __u8 reserved[4];+ __u8 prefix[SANDBOX_GLOB_MAX];+ __u8 suffix[SANDBOX_GLOB_MAX];+};++struct sandbox_policy {+ __u64 sandboxes;+ __u64 exec_enforced;+ __u64 net_enforced;+ __u32 nr_exec;+ __u32 nr_net;+ __u32 nr_fim;+ __u32 reserved;+ struct sandbox_exec_rule exec[SANDBOX_MAX];+ struct sandbox_net_rule net[SANDBOX_NET_MAX];+ struct sandbox_fim_rule fim[SANDBOX_FIM_MAX];+};++const volatile struct sandbox_policy sandbox_policy = {};++struct sandbox_label {+ __u64 bits;+};++/* bpf_dynptr_from_mem() takes map memory only, and the exec hook sleeps. */+struct {+ __uint(type, BPF_MAP_TYPE_TASK_STORAGE);+ __uint(map_flags, BPF_F_NO_PREALLOC);+ __type(key, int);+ __type(value, struct sandbox_label);+} sandbox_label SEC(".maps");++/* The first and the last bytes of a file name, all a pattern compares. */+struct sandbox_name {+ __u32 len;+ __u32 tail_len;+ __u8 head[SANDBOX_GLOB_MAX];+ __u8 tail[SANDBOX_GLOB_MAX];+};++int bpf_get_file_xattr(struct file *file, const char *name__str,+ struct bpf_dynptr *value_p) __ksym;++static __always_inline __u64 current_sandboxes(void)+{+ struct task_policy *policy;++ policy = bpf_task_storage_get(&shirudo_task_policy,+ bpf_get_current_task_btf(), NULL, 0);+ return policy ? policy->active & sandbox_policy.sandboxes : 0;+}++static __always_inline int file_policy_bits(struct file *file, __u64 *bits)+{+ struct sandbox_label *label;+ struct bpf_dynptr value;+ int len;++ label = bpf_task_storage_get(&sandbox_label,+ bpf_get_current_task_btf(), NULL,+ BPF_LOCAL_STORAGE_GET_F_CREATE);+ if (!label ||+ bpf_dynptr_from_mem(&label->bits, sizeof(label->bits), 0, &value))+ return -EACCES;+ len = bpf_get_file_xattr(file, XATTR_POLICY, &value);+ if (len == -ENODATA || len == -EOPNOTSUPP) {+ *bits = 0;+ return 0;+ }+ if (len != sizeof(label->bits))+ return -EACCES;+ *bits = label->bits;+ return 0;+}++static __always_inline bool exec_allowed(__u64 sandboxes, __u64 file_bits)+{+ const volatile struct sandbox_exec_rule *rule;+ __u32 nr_exec = sandbox_policy.nr_exec;+ __u32 i;++ for (i = 0; i < SANDBOX_MAX; i++) {+ if (i >= nr_exec)+ break;+ rule = &sandbox_policy.exec[i];+ if ((sandboxes & rule->sandbox) && !(file_bits & rule->allowed))+ return false;+ }+ return true;+}++/* The kernel calls it for a script and again for each interpreter. */+SEC("lsm.s/bprm_check_security")+int BPF_PROG(sandbox_exec, struct linux_binprm *bprm, int ret)+{+ __u64 sandboxes, file_bits;++ if (ret)+ return ret;+ sandboxes = current_sandboxes() & sandbox_policy.exec_enforced;+ if (!sandboxes)+ return 0;+ if (!bprm->file || file_policy_bits(bprm->file, &file_bits))+ return -EACCES;+ return exec_allowed(sandboxes, file_bits) ? 0 : -EACCES;+}++static __always_inline bool net_allowed(__u64 sandboxes,+ const union sandbox_addr *addr)+{+ const volatile struct sandbox_net_rule *rule;+ __u32 nr_net = sandbox_policy.nr_net;+ __u64 allowed = 0;+ __u32 i;++ for (i = 0; i < SANDBOX_NET_MAX; i++) {+ if (i >= nr_net)+ break;+ rule = &sandbox_policy.net[i];+ if ((addr->halves[0] & rule->mask[0]) == rule->addr[0] &&+ (addr->halves[1] & rule->mask[1]) == rule->addr[1])+ allowed |= rule->sandboxes;+ }+ return !(sandboxes & ~allowed);+}++static __always_inline int peer_verdict(__u64 sandboxes, __u16 family,+ const struct sockaddr *address,+ int addrlen)+{+ union sandbox_addr addr = {};+ struct sockaddr_in6 sin6;+ struct sockaddr_in sin;++ if (family == AF_INET) {+ if (addrlen < (int)sizeof(sin) ||+ bpf_probe_read_kernel(&sin, sizeof(sin), address))+ return -EACCES;+ addr.words[2] = bpf_htonl(0xffff);+ addr.words[3] = sin.sin_addr.s_addr;+ } else if (family == AF_INET6) {+ if (addrlen < (int)sizeof(sin6) ||+ bpf_probe_read_kernel(&sin6, sizeof(sin6), address))+ return -EACCES;+ __builtin_memcpy(addr.bytes, &sin6.sin6_addr,+ sizeof(addr.bytes));+ } else {+ return 0;+ }+ return net_allowed(sandboxes, &addr) ? 0 : -EACCES;+}++SEC("lsm/socket_connect")+int BPF_PROG(sandbox_connect, struct socket *sock, struct sockaddr *address,+ int addrlen, int ret)+{+ __u64 sandboxes;+ __u16 family;++ if (ret)+ return ret;+ sandboxes = current_sandboxes() & sandbox_policy.net_enforced;+ if (!sandboxes)+ return 0;+ if (!address || addrlen < (int)sizeof(family) ||+ bpf_probe_read_kernel(&family, sizeof(family),+ &address->sa_family))+ return -EACCES;+ return peer_verdict(sandboxes, family, address, addrlen);+}++SEC("lsm/socket_sendmsg")+int BPF_PROG(sandbox_sendmsg, struct socket *sock, struct msghdr *msg,+ int size, int ret)+{+ struct sockaddr *address;+ __u64 sandboxes;+ struct sock *sk;+ __u16 family;+ int addrlen;++ if (ret)+ return ret;+ address = msg->msg_name;+ if (!address)+ return 0;+ sandboxes = current_sandboxes() & sandbox_policy.net_enforced;+ if (!sandboxes)+ return 0;+ addrlen = msg->msg_namelen;+ if (addrlen < (int)sizeof(family) ||+ bpf_probe_read_kernel(&family, sizeof(family),+ &address->sa_family))+ return -EACCES;+ /* IPv4 sends to an AF_UNSPEC address as to an AF_INET one. */+ sk = sock->sk;+ if (family == AF_UNSPEC && sk && sk->__sk_common.skc_family == AF_INET)+ family = AF_INET;+ return peer_verdict(sandboxes, family, address, addrlen);+}++/* A raw or packet socket writes its own headers, past both hooks above. */+SEC("lsm/socket_create")+int BPF_PROG(sandbox_socket_create, int family, int type, int protocol,+ int kern, int ret)+{+ if (ret || kern)+ return ret;+ if (family != AF_PACKET &&+ !((family == AF_INET || family == AF_INET6) &&+ (type & SOCK_TYPE_MASK) == SOCK_RAW))+ return 0;+ return current_sandboxes() & sandbox_policy.net_enforced ? -EACCES : 0;+}++static __always_inline int read_name(struct dentry *dentry,+ struct sandbox_name *name)+{+ const unsigned char *bytes = dentry->d_name.name;+ __u32 len = dentry->d_name.len;+ __u32 part_len;++ if (!len || len > NAME_MAX)+ return -EACCES;+ part_len = len;+ if (part_len > SANDBOX_GLOB_MAX)+ part_len = SANDBOX_GLOB_MAX;+ if (bpf_probe_read_kernel(name->head, part_len, bytes) ||+ bpf_probe_read_kernel(name->tail, part_len, bytes + len - part_len))+ return -EACCES;+ name->len = len;+ name->tail_len = part_len;+ return 0;+}++static __always_inline bool byte_matches(__u8 pattern, __u8 byte)+{+ return pattern == '?' || pattern == byte;+}++static __always_inline bool+name_matches(const volatile struct sandbox_fim_rule *rule,+ const struct sandbox_name *name)+{+ __u32 prefix_len = rule->prefix_len;+ __u32 suffix_len = rule->suffix_len;+ __u32 i, tail_at;++ if (prefix_len > SANDBOX_GLOB_MAX || suffix_len > SANDBOX_GLOB_MAX)+ return true;+ if (rule->wildcard ? name->len < prefix_len + suffix_len :+ name->len != prefix_len)+ return false;+ for (i = 0; i < SANDBOX_GLOB_MAX; i++) {+ if (i >= prefix_len)+ break;+ if (!byte_matches(rule->prefix[i], name->head[i]))+ return false;+ }+ tail_at = name->tail_len - suffix_len;+ for (i = 0; i < SANDBOX_GLOB_MAX; i++) {+ if (i >= suffix_len)+ break;+ if (!byte_matches(rule->suffix[i],+ name->tail[(tail_at + i) &+ (SANDBOX_GLOB_MAX - 1)]))+ return false;+ }+ return true;+}++static __noinline bool name_denied(__u64 sandboxes, __u32 op,+ struct dentry *dentry)+{+ const volatile struct sandbox_fim_rule *rule;+ __u32 nr_fim = sandbox_policy.nr_fim;+ struct sandbox_name name = {};+ __u32 i;++ if (!dentry || read_name(dentry, &name))+ return true;+ for (i = 0; i < SANDBOX_FIM_MAX; i++) {+ if (i >= nr_fim)+ break;+ rule = &sandbox_policy.fim[i];+ if ((rule->sandboxes & sandboxes) && (rule->ops & op) &&+ name_matches(rule, &name))+ return true;+ }+ return false;+}++static __always_inline int name_verdict(__u32 op, struct dentry *dentry)+{+ __u64 sandboxes = current_sandboxes();++ if (!sandboxes)+ return 0;+ return name_denied(sandboxes, op, dentry) ? -EACCES : 0;+}++SEC("lsm/inode_create")+int BPF_PROG(sandbox_create, struct mnt_idmap *idmap, struct inode *dir,+ struct dentry *dentry, umode_t mode, int ret)+{+ return ret ? ret : name_verdict(SANDBOX_FIM_CREATE, dentry);+}++SEC("lsm/inode_mkdir")+int BPF_PROG(sandbox_mkdir, struct mnt_idmap *idmap, struct inode *dir,+ struct dentry *dentry, umode_t mode, int ret)+{+ return ret ? ret : name_verdict(SANDBOX_FIM_CREATE, dentry);+}++SEC("lsm/inode_symlink")+int BPF_PROG(sandbox_symlink, struct mnt_idmap *idmap, struct inode *dir,+ struct dentry *dentry, const char *old_name, int ret)+{+ return ret ? ret : name_verdict(SANDBOX_FIM_CREATE, dentry);+}++SEC("lsm/inode_mknod")+int BPF_PROG(sandbox_mknod, struct mnt_idmap *idmap, struct inode *dir,+ struct dentry *dentry, umode_t mode, dev_t dev, int ret)+{+ return ret ? ret : name_verdict(SANDBOX_FIM_CREATE, dentry);+}++SEC("lsm/inode_link")+int BPF_PROG(sandbox_link, struct mnt_idmap *idmap, struct dentry *old_dentry,+ struct inode *dir, struct dentry *new_dentry, int ret)+{+ return ret ? ret : name_verdict(SANDBOX_FIM_CREATE, new_dentry);+}++SEC("lsm/inode_rename")+int BPF_PROG(sandbox_rename, struct inode *old_dir, struct dentry *old_dentry,+ struct inode *new_dir, struct dentry *new_dentry, int ret)+{+ __u64 sandboxes;++ if (ret)+ return ret;+ sandboxes = current_sandboxes();+ if (!sandboxes)+ return 0;+ if (name_denied(sandboxes, SANDBOX_FIM_RENAME, old_dentry) ||+ name_denied(sandboxes, SANDBOX_FIM_RENAME, new_dentry))+ return -EACCES;+ return 0;+}++SEC("lsm/file_open")+int BPF_PROG(sandbox_open, struct file *file, int ret)+{+ if (ret || !(file->f_mode & FMODE_WRITE))+ return ret;+ return name_verdict(SANDBOX_FIM_WRITE, file->f_path.dentry);+}++SEC("lsm/inode_setattr")+int BPF_PROG(sandbox_truncate, struct mnt_idmap *idmap, struct dentry *dentry,+ struct iattr *attr, int ret)+{+ if (ret || !(attr->ia_valid & ATTR_SIZE))+ return ret;+ return name_verdict(SANDBOX_FIM_WRITE, dentry);+}diff --git a/upatches/app-sandbox/gen_policy.py b/upatches/app-sandbox/gen_policy.pynew file mode 100644index 00000000..675d90e9--- /dev/null+++ b/upatches/app-sandbox/gen_policy.py@@ -0,0 +1,170 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+"""Generate sandbox_policy of app-sandbox as a raw BTF variable value.++The rules of each sandbox come from the input, the policy bit of each+from the [[upatches.policy]] table of the Beefile that has its name.+"""++import argparse+import ipaddress+from pathlib import Path+import struct+import tomllib++SANDBOX_MAX = 32+NET_MAX = 128+FIM_MAX = 64+GLOB_MAX = 32+OPS = {"create": 0x1, "rename": 0x2, "write": 0x4}+SANDBOX_KEYS = {"exec", "network", "deny"}+MAPPED_V4 = ipaddress.ip_network("::ffff:0:0/96")+++def strings(value, where):+ if not isinstance(value, list) or any(not isinstance(v, str) for v in value):+ raise ValueError(f"{where}: expected an array of strings")+ return value+++def policy_bits(beefile):+ """The bit of every policy ID the Beefile declares."""+ with beefile.open("rb") as stream:+ upatches = tomllib.load(stream).get("upatches", [])+ bits = {}+ for upatch in upatches:+ for policy in upatch.get("policy", []):+ name, bit = policy.get("id"), policy.get("bit")+ # shirudo reads a bit as hexadecimal, TOML reads it as+ # decimal without 0x: only a one-hot value is the same bit+ # to both.+ if not isinstance(bit, int) or bit <= 0 or bit & (bit - 1) or bit >> 64:+ raise ValueError(f"{beefile}: policy {name}: write the bit as "+ "one-hot hexadecimal with 0x")+ if bits.setdefault(name, bit) != bit:+ raise ValueError(f"{beefile}: policy {name} has two bits")+ return bits+++def network_rule(text, where):+ try:+ network = ipaddress.ip_network(text, strict=False)+ except ValueError as error:+ raise ValueError(f"{where}: {error}") from error+ if network.version == 4:+ address = int(MAPPED_V4.network_address) | int(network.network_address)+ network = ipaddress.ip_network((address, 96 + network.prefixlen))+ return network.network_address.packed, network.netmask.packed+++def networks(names, sets, where):+ rules = []+ for name in strings(names, where):+ if name.startswith("@"):+ if name[1:] not in sets:+ raise ValueError(f"{where}: no [networks] entry {name[1:]}")+ members = strings(sets[name[1:]], f"networks.{name[1:]}")+ else:+ members = [name]+ rules.extend(network_rule(member, where) for member in members)+ return rules+++def glob_rule(pattern, where):+ raw = pattern.encode()+ if not raw or b"/" in raw or b"\0" in raw or raw.count(b"*") > 1:+ raise ValueError(f"{where}: {pattern!r} is not a file name with at "+ "most one '*'")+ prefix, star, suffix = raw.partition(b"*")+ if len(prefix) > GLOB_MAX or len(suffix) > GLOB_MAX:+ raise ValueError(f"{where}: {pattern!r} has more than {GLOB_MAX} "+ "bytes on one side of its '*'")+ return prefix, suffix, bool(star)+++def read_policy(path, bits):+ with path.open("rb") as stream:+ config = tomllib.load(stream)+ unknown = set(config) - {"networks", "sandbox"}+ if unknown:+ raise ValueError(f"{path}: unknown table {sorted(unknown)[0]}")+ sets = config.get("networks", {})+ policy = {"sandboxes": 0, "exec_enforced": 0, "net_enforced": 0,+ "exec": [], "net": {}, "fim": {}}+ for name, sandbox in config.get("sandbox", {}).items():+ where = f"{path}: sandbox.{name}"+ if name not in bits:+ raise ValueError(f"{where}: the Beefile has no policy {name}")+ unknown = set(sandbox) - SANDBOX_KEYS+ if unknown:+ raise ValueError(f"{where}: unknown key {sorted(unknown)[0]}")+ bit = bits[name]+ policy["sandboxes"] |= bit+ if "exec" in sandbox:+ allowed = bit+ for other in strings(sandbox["exec"], f"{where}.exec"):+ if other not in bits:+ raise ValueError(f"{where}.exec: the Beefile has no "+ f"policy {other}")+ allowed |= bits[other]+ policy["exec_enforced"] |= bit+ policy["exec"].append((bit, allowed))+ if "network" in sandbox:+ policy["net_enforced"] |= bit+ for rule in networks(sandbox["network"], sets, f"{where}.network"):+ policy["net"][rule] = policy["net"].get(rule, 0) | bit+ deny = sandbox.get("deny", {})+ unknown = set(deny) - set(OPS)+ if unknown:+ raise ValueError(f"{where}.deny: unknown key {sorted(unknown)[0]}")+ for op, patterns in deny.items():+ for pattern in strings(patterns, f"{where}.deny.{op}"):+ rule = glob_rule(pattern, f"{where}.deny.{op}")+ sandboxes, ops = policy["fim"].get(rule, (0, 0))+ policy["fim"][rule] = (sandboxes | bit, ops | OPS[op])+ return policy+++def table(entries, limit, size, what):+ if len(entries) > limit:+ raise ValueError(f"{len(entries)} {what}; the object holds {limit}")+ return b"".join(entries).ljust(limit * size, b"\0")+++def encode(policy):+ """struct sandbox_policy of app-sandbox.bpf.c, little-endian."""+ execs = [struct.pack("<QQ", bit, allowed) for bit, allowed in policy["exec"]]+ nets = [struct.pack("<Q16s16s", sandboxes, address, mask)+ for (address, mask), sandboxes in sorted(policy["net"].items())]+ fims = [struct.pack(f"<QBBBB4x{GLOB_MAX}s{GLOB_MAX}s", sandboxes, ops,+ len(prefix), len(suffix), wildcard, prefix, suffix)+ for (prefix, suffix, wildcard), (sandboxes, ops)+ in sorted(policy["fim"].items())]+ header = struct.pack("<QQQIII4x", policy["sandboxes"],+ policy["exec_enforced"], policy["net_enforced"],+ len(execs), len(nets), len(fims))+ return (header + table(execs, SANDBOX_MAX, 16, "sandboxes with exec rules") ++ table(nets, NET_MAX, 40, "networks") ++ table(fims, FIM_MAX, 80, "file name patterns"))+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--input", required=True, type=Path)+ parser.add_argument("--symbol", required=True)+ parser.add_argument("--output", required=True, type=Path)+ parser.add_argument("--beefile", type=Path, default=Path("Beefile"))+ args = parser.parse_args()+ try:+ if args.symbol != "sandbox_policy":+ raise ValueError(f"unsupported symbol: {args.symbol}")+ policy = read_policy(args.input, policy_bits(args.beefile))+ args.output.write_bytes(encode(policy))+ except (OSError, ValueError, tomllib.TOMLDecodeError) as error:+ parser.error(str(error))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/upatches/app-sandbox/sandbox.toml b/upatches/app-sandbox/sandbox.tomlnew file mode 100644index 00000000..13e63847--- /dev/null+++ b/upatches/app-sandbox/sandbox.toml@@ -0,0 +1,35 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# The rules of each sandbox the Beefile declares as a policy. README.md+# describes the keys.++[networks]+localnet = [+ "127.0.0.0/8",+ "10.0.0.0/8",+ "172.16.0.0/12",+ "192.168.0.0/16",+ "169.254.0.0/16",+ "::1/128",+ "fc00::/7",+ "fe80::/10",+]++[sandbox.apache]+exec = []+network = ["@localnet"]++[sandbox.apache.deny]+create = ["*.php"]+rename = ["*.php"]+write = ["*.php"]++[sandbox.php-fpm]+exec = []+network = ["@localnet"]++[sandbox.php-fpm.deny]+create = ["*.php", "*.phar", "*.phtml", "*.pht", "*.php?"]+rename = ["*.php", "*.phar", "*.phtml", "*.pht", "*.php?"]+write = ["*.php", "*.phar", "*.phtml", "*.pht", "*.php?"]