### minijail0 CLI Examples Source: https://context7.com/google/minijail/llms.txt Examples of using the minijail0 command-line executable to sandbox processes with different configurations. ```APIDOC ## minijail0 CLI — Sandbox a Process from the Shell The `minijail0` executable applies a full set of restrictions to any program invoked on the command line. It is the primary interface for sandboxing daemons and services on ChromeOS and Android. ### Example 1: Drop privileges and capabilities ```sh minijail0 -u nobody -g nobody -c 0 -G -- /usr/bin/whoami # Output: nobody ``` ### Example 2: New PID + VFS namespace with read-only /proc ```sh minijail0 -p -v -r -c 0 -- /bin/ps # PID TTY TIME CMD # 1 pts/0 00:00:00 minijail0 # 2 pts/0 00:00:00 ps ``` ### Example 3: Seccomp-bpf policy and privilege dropping ```sh minijail0 -n -S /usr/share/minijail0/$(uname -m)/cat.policy -- /bin/cat /proc/self/status ``` ### Example 4: Full isolation ```sh minijail0 -u svc -g svc \ -p -v -r -l -e -N \ -P /var/empty \ -b /usr/bin -b /lib64 \ -n -S /etc/svc.policy \ -- /usr/bin/my-service --config /etc/svc.conf ``` ### Example 5: Daemonize ```sh minijail0 -i -I -p -u svc -- /usr/bin/my-daemon ``` ### Example 6: Set resource limits and write PID file ```sh minijail0 -R RLIMIT_AS,268435456,268435456 \ -f /run/myservice.pid \ -u svc -- /usr/bin/my-service ``` ### Example 7: Use a config file ```sh # /etc/minijail/my-service.conf: # % minijail-config-file v0 # user=svc # group=svc # no-new-privs # seccomp-filter=/etc/minijail/my-service.policy minijail0 --config /etc/minijail/my-service.conf -- /usr/bin/my-service ``` ``` -------------------------------- ### Setup Hooks with minijail_add_hook (C) Source: https://context7.com/google/minijail/llms.txt Register callbacks that execute at specific points within the forked process during jail setup. This allows for custom initialization before capabilities are dropped or exec is called. Use `MINIJAIL_HOOK_EVENT_PRE_EXECVE` for actions before `execve` and `MINIJAIL_HOOK_EVENT_PRE_DROP_CAPS` for actions before dropping capabilities. ```c #include #include static int pre_execve_hook(void *ctx) { const char *msg = (const char *)ctx; printf("Pre-execve hook running: %s\n", msg); /* Return non-zero (interpreted as -errno) to abort */ return 0; } static int pre_drop_caps_hook(void *ctx) { /* e.g., open sockets that require elevated privileges here */ return 0; } int main(void) { struct minijail *j = minijail_new(); minijail_no_new_privs(j); char *msg = "hello from hook"; /* Hook fires just before execve(2) in the child */ minijail_add_hook(j, pre_execve_hook, msg, MINIJAIL_HOOK_EVENT_PRE_EXECVE); /* Hook fires just before capabilities are dropped */ minijail_add_hook(j, pre_drop_caps_hook, NULL, MINIJAIL_HOOK_EVENT_PRE_DROP_CAPS); char *argv[] = { "/usr/bin/my-service", NULL }; minijail_run(j, "/usr/bin/my-service", argv); minijail_wait(j); minijail_destroy(j); return 0; } ``` -------------------------------- ### Seccomp Policy File Syntax Examples Source: https://context7.com/google/minijail/llms.txt Demonstrates the syntax for Minijail seccomp policy files, including unconditional allowances, conditional arguments, and including shared policies. These policies are compiled to BPF. ```text # Allow unconditionally read: 1 write: 1 exit_group: 1 rt_sigreturn: 1 # Allow open only for read-only access (named constants preferred over numbers) open: arg1 in O_RDONLY|O_CLOEXEC|O_NONBLOCK # Enforce W^X: mmap cannot be both PROT_WRITE and PROT_EXEC mmap: arg2 in ~PROT_EXEC || arg2 in ~PROT_WRITE mprotect: arg2 in ~PROT_EXEC || arg2 in ~PROT_WRITE # Block a syscall and return a specific errno instead of killing socket: return EACCES # Conditional: allow read from fd 0 only; else return EBADF read: arg0 == 0; return EBADF # Include a shared base policy @include /usr/share/minijail0/common.policy ``` -------------------------------- ### Run with Full I/O Control using minijail_run_pid_pipes (C) Source: https://context7.com/google/minijail/llms.txt Launches a sandboxed child process and provides file descriptors for its stdin, stdout, and stderr. Use this when you need to interact with the child's I/O streams after it has started. ```c #include #include #include int main(void) { struct minijail *j = minijail_new(); minijail_no_new_privs(j); minijail_parse_seccomp_filters(j, "/etc/worker.policy"); minijail_use_seccomp_filter(j); pid_t child_pid; int stdin_fd, stdout_fd, stderr_fd; char *argv[] = { "/usr/bin/worker", "--json", NULL }; int ret = minijail_run_pid_pipes(j, "/usr/bin/worker", argv, &child_pid, &stdin_fd, &stdout_fd, &stderr_fd); if (ret != 0) { fprintf(stderr, "Failed to launch sandboxed worker\n"); minijail_destroy(j); return 1; } /* Send input to the sandboxed process */ const char *input = "{\"task\": \"process\"}\n"; write(stdin_fd, input, strlen(input)); close(stdin_fd); /* Read its output */ char buf[4096]; ssize_t n; while ((n = read(stdout_fd, buf, sizeof(buf) - 1)) > 0) { buf[n] = '\0'; printf("Worker output: %s", buf); } close(stdout_fd); close(stderr_fd); /* Wait for exit and check status */ int status = minijail_wait(j); /* status == 0 on success, MINIJAIL_ERR_SECCOMP_VIOLATION (253) on seccomp kill */ printf("Worker exited with status %d (pid %d)\n", status, child_pid); minijail_destroy(j); return status; } ``` -------------------------------- ### Change Root User with Minijail Source: https://github.com/google/minijail/blob/main/README.md Example of using minijail to change the root user and group for a process. This is useful for dropping privileges after initial setup. ```shell # id uid=0(root) gid=0(root) groups=0(root),128(pkcs11) # minijail0 -u jorgelo -g 5000 /usr/bin/id uid=72178(jorgelo) gid=5000(eng) groups=5000(eng) ``` -------------------------------- ### minijail0 CLI Examples Source: https://context7.com/google/minijail/llms.txt Use the minijail0 executable to apply a full set of restrictions to any program invoked on the command line. It is the primary interface for sandboxing daemons and services. ```sh # Drop to user "nobody", group "nobody", zero capabilities, inherit supplementary groups minijail0 -u nobody -g nobody -c 0 -G -- /usr/bin/whoami ``` ```sh # Run in a new PID + VFS namespace with read-only /proc, no root capabilities minijail0 -p -v -r -c 0 -- /bin/ps ``` ```sh # Apply a seccomp-bpf policy file and drop privileges minijail0 -n -S /usr/share/minijail0/$(uname -m)/cat.policy -- /bin/cat /proc/self/status ``` ```sh # Full isolation: user+PID+VFS+IPC+network namespace, pivot_root, seccomp, no-new-privs minijail0 -u svc -g svc \ -p -v -r -l -e -N \ -P /var/empty \ -b /usr/bin -b /lib64 \ -n -S /etc/svc.policy \ -- /usr/bin/my-service --config /etc/svc.conf ``` ```sh # Daemonize: exit the minijail0 parent immediately (-i), run as init in PID ns (-I) minijail0 -i -I -p -u svc -- /usr/bin/my-daemon ``` ```sh # Set resource limits and write a PID file minijail0 -R RLIMIT_AS,268435456,268435456 \ -f /run/myservice.pid \ -u svc -- /usr/bin/my-service ``` ```sh # Use a config file instead of command-line flags # /etc/minijail/my-service.conf: # % minijail-config-file v0 # user=svc # group=svc # no-new-privs # seccomp-filter=/etc/minijail/my-service.policy minijail0 --config /etc/minijail/my-service.conf -- /usr/bin/my-service ``` -------------------------------- ### Push Minijail Tag Source: https://github.com/google/minijail/blob/main/RELEASE.md Push the newly created Git tag to the remote repository (aosp in this example). ```bash minijail$ git push aosp linux-v ``` -------------------------------- ### Sandbox with Linux Namespaces (C) Source: https://context7.com/google/minijail/llms.txt Configures Minijail to use various Linux namespaces for process isolation, including VFS, PID, IPC, Network, UTS, Cgroup, and User namespaces. This example also demonstrates pivot_root and binding necessary files. ```c #include #include int sandbox_with_namespaces(void) { struct minijail *j = minijail_new(); /* VFS namespace: mounts don't propagate to the parent */ minijail_namespace_vfs(j); /* PID namespace: process cannot see or signal other processes */ /* Implies -v and remounts /proc read-only */ minijail_namespace_pids(j); /* IPC namespace: isolate System V IPC resources */ minijail_namespace_ipc(j); /* Network namespace with loopback interface */ minijail_namespace_net(j); /* UTS namespace: set a private hostname */ minijail_namespace_uts(j); minijail_namespace_set_hostname(j, "sandbox"); /* Cgroup namespace */ minijail_namespace_cgroups(j); /* User namespace with UID/GID mapping */ minijail_namespace_user(j); minijail_uidmap(j, "0 1000 1"); /* map uid 1000 -> root inside */ minijail_gidmap(j, "0 1000 1"); /* Use pivot_root for a minimal filesystem environment */ minijail_enter_pivot_root(j, "/var/empty"); /* Bind in only what is needed */ minijail_bind(j, "/usr/bin/my-service", "/usr/bin/my-service", 0); minijail_bind(j, "/lib64", "/lib64", 0); minijail_mount_tmp(j); /* 64M tmpfs at /tmp */ minijail_mount_dev(j); /* minimal /dev with null, zero, urandom, etc. */ char *argv[] = { "/usr/bin/my-service", NULL }; int ret = minijail_run(j, "/usr/bin/my-service", argv); int status = minijail_wait(j); minijail_destroy(j); return status; } ``` -------------------------------- ### minijail_add_hook Source: https://context7.com/google/minijail/llms.txt Registers callback functions that execute at specific stages of the jail setup process within the forked child. This allows for custom initialization, such as dropping privileges or preparing the environment before executing the main process. ```APIDOC ## minijail_add_hook — Setup Hooks (C) Register callbacks that run at specific points during the jail setup within the forked process, allowing custom initialization before capabilities are dropped or exec is called. ### Function Signature ```c int minijail_add_hook(struct minijail *j, int (*hook)(void *), void *ctx, enum minijail_hook_event event); ``` ### Parameters - **j** (struct minijail *): Pointer to an initialized minijail context. - **hook** (int (*)(void *)): Pointer to the callback function to be executed. - **ctx** (void *): A context pointer to be passed to the hook function. - **event** (enum minijail_hook_event): The event that triggers the hook. Possible values include `MINIJAIL_HOOK_EVENT_PRE_EXECVE` and `MINIJAIL_HOOK_EVENT_PRE_DROP_CAPS`. ### Return Value Returns 0 on success, or a non-zero error code on failure. ### Example Usage ```c #include #include static int pre_execve_hook(void *ctx) { const char *msg = (const char *)ctx; printf("Pre-execve hook running: %s\n", msg); /* Return non-zero (interpreted as -errno) to abort */ return 0; } static int pre_drop_caps_hook(void *ctx) { /* e.g., open sockets that require elevated privileges here */ return 0; } int main(void) { struct minijail *j = minijail_new(); minijail_no_new_privs(j); char *msg = "hello from hook"; /* Hook fires just before execve(2) in the child */ minijail_add_hook(j, pre_execve_hook, msg, MINIJAIL_HOOK_EVENT_PRE_EXECVE); /* Hook fires just before capabilities are dropped */ minijail_add_hook(j, pre_drop_caps_hook, NULL, MINIJAIL_HOOK_EVENT_PRE_DROP_CAPS); char *argv[] = { "/usr/bin/my-service", NULL }; minijail_run(j, "/usr/bin/my-service", argv); minijail_wait(j); minijail_destroy(j); return 0; } ``` ``` -------------------------------- ### Control Filesystem Access with Minijail Mounts (C) Source: https://context7.com/google/minijail/llms.txt Manage visible paths within a jail using bind-mounts and custom mounts. Use `minijail_namespace_vfs` and `minijail_enter_pivot_root` for VFS isolation. `minijail_mount_dev` and `minijail_mount_tmp` provide basic device and temporary file system setups. ```c #include #include int main(void) { struct minijail *j = minijail_new(); minijail_namespace_vfs(j); minijail_enter_pivot_root(j, "/var/empty"); /* Read-only bind mount */ minijail_bind(j, "/usr/bin", "/usr/bin", 0 /* read-only */); /* Writable bind mount */ minijail_bind(j, "/var/svc/data", "/data", 1 /* writable */); /* Custom tmpfs mount with explicit size and mode */ minijail_mount_with_data(j, "tmpfs", "/run", "tmpfs", MS_NODEV | MS_NOSUID | MS_NOEXEC, "mode=0755,size=32M"); /* Minimal /dev with null, zero, urandom, tty, full */ minijail_mount_dev(j); /* 64M tmpfs on /tmp */ minijail_mount_tmp(j); /* Custom size tmpfs on /tmp */ /* minijail_mount_tmp_size(j, 128 * 1024 * 1024); */ char *argv[] = { "/usr/bin/my-service", NULL }; minijail_run(j, "/usr/bin/my-service", argv); minijail_wait(j); minijail_destroy(j); return 0; } ``` -------------------------------- ### Manage GitHub Pages Branch Source: https://github.com/google/minijail/blob/main/README.md Commands to fetch, checkout, and push changes to the gh-pages branch for updating the GitHub Pages homepage. Ensure all branches are fetched before starting. ```shell git fetch # Create a new local branch tracking the remote "gh-pages". # Git should automatically detect the remote and track it for you. $ git checkout gh-pages # If git can't auto-detect the remote, try one of these. $ git checkout -b gh-pages origin/gh-pages $ git checkout -b gh-pages cros/gh-pages # Make your changes like normal, then push them to Gerrit for review. # Here's a couple of different ways to post changes; you only need one! $ repo upload -D gh-pages $ git push origin HEAD:refs/for/gh-pages $ git push cros HEAD:refs/for/gh-pages # Now review your changes via Gerrit like normal. ``` -------------------------------- ### Download and Build Google Test Source: https://github.com/google/minijail/blob/main/HACKING.md Download the Google Test framework using the provided script and then build the Minijail tests. Building the tests will automatically execute them. ```bash ./get_googletest.sh make tests ``` -------------------------------- ### Seccomp-BPF Policy Loading Source: https://context7.com/google/minijail/llms.txt Demonstrates how to load and apply a seccomp-bpf policy using `minijail_parse_seccomp_filters` and `minijail_use_seccomp_filter`. It also shows related configurations like `minijail_no_new_privs` and `minijail_set_seccomp_filter_tsync`. ```APIDOC ## `minijail_use_seccomp_filter` / `minijail_parse_seccomp_filters` — Seccomp-BPF Policy (C) Load a text policy file that defines which syscalls are allowed, with optional argument filtering. Blocked syscalls kill the process with SIGSYS by default. ```c #include /* Policy file /etc/myapp.policy: * * read: 1 * write: 1 * open: arg1 in O_RDONLY|O_CLOEXEC * openat: arg2 in O_RDONLY|O_CLOEXEC * close: 1 * fstat: 1 * mmap: arg2 in ~PROT_EXEC || arg2 in ~PROT_WRITE * munmap: 1 * exit_group: 1 * rt_sigreturn: 1 */ int sandbox_with_seccomp(const char *policy_path) { struct minijail *j = minijail_new(); /* Prevent privilege escalation via no-new-privs */ minijail_no_new_privs(j); /* Parse and apply the seccomp-bpf policy */ minijail_parse_seccomp_filters(j, policy_path); minijail_use_seccomp_filter(j); /* Sync filter across all threads in the process */ minijail_set_seccomp_filter_tsync(j); /* Log blocked syscalls instead of killing (dev/debug only) */ /* minijail_log_seccomp_filter_failures(j); */ char *argv[] = { "/usr/bin/my-service", NULL }; int ret = minijail_run(j, "/usr/bin/my-service", argv); minijail_wait(j); minijail_destroy(j); return ret; } ``` ``` -------------------------------- ### Build and Run Minijail Locally Source: https://github.com/google/minijail/blob/main/HACKING.md Build Minijail using make and then run it with specific user and group IDs. This is useful for local experimentation with Minijail libraries directly from the source directory. ```bash make LIBDIR=/lib64 sudo ./minijail0.sh -u ${USER} -g 5000 -- /usr/bin/id ``` -------------------------------- ### Generate and Compile Seccomp Policies (Shell) Source: https://context7.com/google/minijail/llms.txt Shows how to generate a seccomp policy from strace output and compile it into an optimized BPF binary for use with minijail0. This is an alternative to loading text policies directly. ```sh # Generate a policy from strace output strace -f -e raw=all -o /tmp/strace.txt -- /usr/bin/my-service ./tools/generate_seccomp_policy.py /tmp/strace.txt > /etc/myapp.policy # Compile a policy to an optimized BPF binary and use it ./tools/compile_seccomp_policy.py /etc/myapp.policy /etc/myapp.bpf minijail0 --seccomp-bpf-binary=/etc/myapp.bpf -- /usr/bin/my-service ``` -------------------------------- ### Run Program Under Minijail with Empty Policy Source: https://github.com/google/minijail/blob/main/tools/README.md Execute your program using minijail0 with an empty seccomp policy. This is part of the audit log-based policy generation process. ```shell minijail0 -u $UID -g $GID -L -S /tmp/empty.policy -- ``` -------------------------------- ### Minijail Lifecycle Management (C) Source: https://context7.com/google/minijail/llms.txt Use minijail_new() to allocate a new unrestricted jail configuration and minijail_destroy() to free it. Every program using libminijail must call both. ```c #include #include int main(void) { struct minijail *j = minijail_new(); if (!j) { fprintf(stderr, "Failed to allocate minijail\n"); return 1; } /* Configure restrictions here … */ /* Enter the jail in this process (irrevocable) */ minijail_enter(j); /* aborts on failure */ /* j is still valid for destroy even after enter */ minijail_destroy(j); /* Restrictions are now in effect for this process */ execv("/usr/bin/my-service", argv); return 0; } ``` -------------------------------- ### Drop Root Capabilities with Minijail Source: https://github.com/google/minijail/blob/main/README.md Demonstrates dropping root privileges while retaining specific capabilities using minijail. The output shows the capabilities inherited, permitted, effective, and bounded. ```shell # minijail0 -u jorgelo -c 3000 -- /bin/cat /proc/self/status Name: cat ... CapInh: 0000000000003000 CapPrm: 0000000000003000 CapEff: 0000000000003000 CapBnd: 0000000000003000 ``` -------------------------------- ### Apply Seccomp-BPF Policy with Minijail (C) Source: https://context7.com/google/minijail/llms.txt Applies a seccomp-bpf policy from a text file to a Minijail process. Ensure the policy file path is correct and the policy syntax is valid. This function also enables no-new-privs. ```c #include /* Policy file /etc/myapp.policy: * * read: 1 * write: 1 * open: arg1 in O_RDONLY|O_CLOEXEC * openat: arg2 in O_RDONLY|O_CLOEXEC * close: 1 * fstat: 1 * mmap: arg2 in ~PROT_EXEC || arg2 in ~PROT_WRITE * munmap: 1 * exit_group: 1 * rt_sigreturn: 1 */ int sandbox_with_seccomp(const char *policy_path) { struct minijail *j = minijail_new(); /* Prevent privilege escalation via no-new-privs */ minijail_no_new_privs(j); /* Parse and apply the seccomp-bpf policy */ minijail_parse_seccomp_filters(j, policy_path); minijail_use_seccomp_filter(j); /* Sync filter across all threads in the process */ minijail_set_seccomp_filter_tsync(j); /* Log blocked syscalls instead of killing (dev/debug only) */ /* minijail_log_seccomp_filter_failures(j); */ char *argv[] = { "/usr/bin/my-service", NULL }; int ret = minijail_run(j, "/usr/bin/my-service", argv); minijail_wait(j); minijail_destroy(j); return ret; } ``` -------------------------------- ### Set Resource Limits and Cgroups with minijail_rlimit/minijail_add_to_cgroup (C) Source: https://context7.com/google/minijail/llms.txt Configures resource limits (rlimits) such as virtual address space and open file descriptors, and assigns the jailed process to specified cgroups. Use `minijail_rlimit` to set limits and `minijail_add_to_cgroup` to specify cgroup paths. ```c #include #include int main(void) { struct minijail *j = minijail_new(); /* Limit virtual address space to 256 MB */ minijail_rlimit(j, RLIMIT_AS, 256*1024*1024, 256*1024*1024); /* Limit open file descriptors */ minijail_rlimit(j, RLIMIT_NOFILE, 64, 64); /* Limit CPU time (seconds) */ minijail_rlimit(j, RLIMIT_CPU, 10, 10); /* Assign to a cgroup's tasks file */ minijail_add_to_cgroup(j, "/sys/fs/cgroup/cpu/jailed/tasks"); minijail_add_to_cgroup(j, "/sys/fs/cgroup/memory/jailed/tasks"); char *argv[] = { "/usr/bin/my-service", NULL }; minijail_run(j, "/usr/bin/my-service", argv); minijail_wait(j); minijail_destroy(j); return 0; } ``` -------------------------------- ### Minijail CLI Sandboxing Profiles Source: https://context7.com/google/minijail/llms.txt Utilizes pre-built sandboxing profiles for standardized environments. Profiles like `minimalistic-mountns` simplify configuration by defining common settings. ```sh # minimalistic-mountns: equivalent to -v -P /var/empty -b / -b /proc -b /dev/log -t -r --mount-dev minijail0 --profile minimalistic-mountns \ -u svc -g svc \ -n -S /etc/svc.policy \ -b /usr/bin/svc,,0 \ -b /etc/svc,,0 \ -b /var/lib/svc,,1 \ -- /usr/bin/svc # minimalistic-mountns-nodev: same but without /dev mount # Equivalent to: -v -P /var/empty -b / -b /proc -t -r minijail0 --profile minimalistic-mountns-nodev \ -u svc -g svc \ -- /usr/bin/svc # Add Landlock path restrictions alongside a profile minijail0 --profile minimalistic-mountns \ --enable-profile-fs-restrictions \ --fs-default-paths \ --fs-path-rx /usr/bin/svc \ --fs-path-ro /etc/svc \ --fs-path-rw /var/lib/svc \ -u svc -n -S /etc/svc.policy \ -- /usr/bin/svc ``` -------------------------------- ### Compile Seccomp Policy to BPF Binary Source: https://github.com/google/minijail/blob/main/tools/README.md Compile a Minijail seccomp policy file into a BPF binary. This requires a constants.json file and generates optimized BPF code. ```shell make minijail0 constants.json ``` ```shell cat > test/seccomp.policy < ``` -------------------------------- ### Configure Audit Rules for Seccomp Policy Generation Source: https://github.com/google/minijail/blob/main/tools/README.md Set up Linux audit rules to enable syscall auditing for finer-grained filtering. This requires python3-audit bindings. ```shell for arch in b32 b64; do auditctl -a exit,always -F uid=$UID -F arch=$arch -S ioctl -S socket \ -S prctl -S mmap -S mprotect \ $([ "$arch" = "b32" ] && echo "-S mmap2") -c done touch /tmp/empty.policy ``` -------------------------------- ### Restrict Linux Capabilities with minijail_use_caps (C) Source: https://context7.com/google/minijail/llms.txt Use this to precisely define the capabilities a process should have, or drop them entirely. Ensure capabilities are correctly mapped using CAP_TO_MASK. ```c #include #include int main(void) { struct minijail *j = minijail_new(); minijail_change_user(j, "svc"); minijail_change_group(j, "svc"); /* Keep only CAP_NET_BIND_SERVICE and CAP_SYS_CHROOT */ uint64_t caps = CAP_TO_MASK(CAP_NET_BIND_SERVICE) | CAP_TO_MASK(CAP_SYS_CHROOT); minijail_use_caps(j, caps); /* Raise ambient capabilities so child processes inherit them across execve without needing file capabilities */ minijail_set_ambient_caps(j); /* OR: drop specific caps from the bounding set (mutually exclusive with use_caps) */ /* minijail_capbset_drop(j, CAP_TO_MASK(CAP_SYS_ADMIN)); */ char *argv[] = { "/usr/sbin/my-daemon", NULL }; minijail_run(j, "/usr/sbin/my-daemon", argv); minijail_wait(j); minijail_destroy(j); return 0; } ``` -------------------------------- ### Linux Namespace Isolation Source: https://context7.com/google/minijail/llms.txt Illustrates how to configure various Linux namespaces for process isolation using functions like `minijail_namespace_vfs`, `minijail_namespace_pids`, `minijail_namespace_net`, etc. It also covers setting hostnames, UID/GID mapping, and filesystem manipulation with `minijail_enter_pivot_root`. ```APIDOC ## `minijail_namespace_*` — Linux Namespace Isolation (C) Enable one or more Linux namespaces to limit the process's view of the system. ```c #include #include int sandbox_with_namespaces(void) { struct minijail *j = minijail_new(); /* VFS namespace: mounts don't propagate to the parent */ minijail_namespace_vfs(j); /* PID namespace: process cannot see or signal other processes */ /* Implies -v and remounts /proc read-only */ minijail_namespace_pids(j); /* IPC namespace: isolate System V IPC resources */ minijail_namespace_ipc(j); /* Network namespace with loopback interface */ minijail_namespace_net(j); /* UTS namespace: set a private hostname */ minijail_namespace_uts(j); minijail_namespace_set_hostname(j, "sandbox"); /* Cgroup namespace */ minijail_namespace_cgroups(j); /* User namespace with UID/GID mapping */ minijail_namespace_user(j); minijail_uidmap(j, "0 1000 1"); /* map uid 1000 -> root inside */ minijail_gidmap(j, "0 1000 1"); /* Use pivot_root for a minimal filesystem environment */ minijail_enter_pivot_root(j, "/var/empty"); /* Bind in only what is needed */ minijail_bind(j, "/usr/bin/my-service", "/usr/bin/my-service", 0); minijail_bind(j, "/lib64", "/lib64", 0); minijail_mount_tmp(j); /* 64M tmpfs at /tmp */ minijail_mount_dev(j); /* minimal /dev with null, zero, urandom, etc. */ char *argv[] = { "/usr/bin/my-service", NULL }; int ret = minijail_run(j, "/usr/bin/my-service", argv); int status = minijail_wait(j); minijail_destroy(j); return status; } ``` ``` -------------------------------- ### Fork into the Jail using minijail_fork (C) Source: https://context7.com/google/minijail/llms.txt Behaves like fork(2) but places the child process into the configured jail. This is required when using PID or user namespaces. The parent receives the child's PID, and the child receives 0. ```c #include #include #include int main(void) { struct minijail *j = minijail_new(); minijail_namespace_pids(j); minijail_namespace_vfs(j); minijail_namespace_net(j); minijail_no_new_privs(j); minijail_parse_seccomp_filters(j, "/etc/worker.policy"); minijail_use_seccomp_filter(j); pid_t pid = minijail_fork(j); if (pid < 0) { fprintf(stderr, "minijail_fork failed: %d\n", pid); minijail_destroy(j); return 1; } if (pid == 0) { /* Child: inside the jail */ execl("/usr/bin/worker", "worker", NULL); _exit(127); /* exec failed */ } /* Parent: wait for child */ int status = minijail_wait(j); printf("Child (pid %d) exited with status %d\n", pid, status); minijail_destroy(j); return status; } ``` -------------------------------- ### Generate Seccomp Policy from Strace Source: https://github.com/google/minijail/blob/main/tools/README.md Use this script to build a Minijail seccomp-bpf filter from strace output. Ensure failure cases are exercised during tracing. ```shell strace -f -e raw=all -o strace.txt -- ``` ```shell ./tools/generate_seccomp_policy.py strace.txt > .policy ``` -------------------------------- ### Find Latest Minijail Tag Source: https://github.com/google/minijail/blob/main/RELEASE.md Use this command to list existing tags matching the 'linux-v*' pattern to determine the next version number. ```bash minijail$ git tag -l "linux-v*" ``` -------------------------------- ### Generate Seccomp Policy from Audit Log Source: https://github.com/google/minijail/blob/main/tools/README.md Generate a Minijail seccomp policy from Linux audit logs. The tool can also process multiple logs and strace traces. ```shell ./tools/generate_seccomp_policy.py --audit-comm $PROGRAM_NAME audit.log \ > $PROGRAM_NAME.policy ``` -------------------------------- ### minijail_new / minijail_destroy (C) Source: https://context7.com/google/minijail/llms.txt Functions for allocating and freeing a new unrestricted jail configuration in C. ```APIDOC ## `minijail_new` / `minijail_destroy` — Lifecycle Management (C) `minijail_new()` allocates a new unrestricted jail configuration; `minijail_destroy()` frees it. Every program using `libminijail` must call both. ### Usage ```c #include #include int main(void) { struct minijail *j = minijail_new(); if (!j) { fprintf(stderr, "Failed to allocate minijail\n"); return 1; } /* Configure restrictions here … */ /* Enter the jail in this process (irrevocable) */ minijail_enter(j); /* aborts on failure */ /* j is still valid for destroy even after enter */ minijail_destroy(j); /* Restrictions are now in effect for this process */ execv("/usr/bin/my-service", argv); return 0; } ``` ``` -------------------------------- ### minijail_bind / minijail_mount / minijail_mount_with_data Source: https://context7.com/google/minijail/llms.txt Control filesystem visibility within a jail using bind-mounts and custom mounts. This allows for read-only or writable bind mounts, as well as creating custom mounts like tmpfs with specific configurations. ```APIDOC ## `minijail_bind` / `minijail_mount` / `minijail_mount_with_data` — Filesystem Mounts (C) Control exactly which paths are visible inside the jail through bind-mounts and custom mounts. ```c #include #include int main(void) { struct minijail *j = minijail_new(); minijail_namespace_vfs(j); minijail_enter_pivot_root(j, "/var/empty"); /* Read-only bind mount */ minijail_bind(j, "/usr/bin", "/usr/bin", 0 /* read-only */); /* Writable bind mount */ minijail_bind(j, "/var/svc/data", "/data", 1 /* writable */); /* Custom tmpfs mount with explicit size and mode */ minijail_mount_with_data(j, "tmpfs", "/run", "tmpfs", MS_NODEV | MS_NOSUID | MS_NOEXEC, "mode=0755,size=32M"); /* Minimal /dev with null, zero, urandom, tty, full */ minijail_mount_dev(j); /* 64M tmpfs on /tmp */ minijail_mount_tmp(j); /* Custom size tmpfs on /tmp */ /* minijail_mount_tmp_size(j, 128 * 1024 * 1024); */ char *argv[] = { "/usr/bin/my-service", NULL }; minijail_run(j, "/usr/bin/my-service", argv); minijail_wait(j); minijail_destroy(j); return 0; } ``` ``` -------------------------------- ### minijail_rlimit / minijail_add_to_cgroup Source: https://context7.com/google/minijail/llms.txt Configures resource limits (rlimits) for the jailed process, such as virtual memory size and the number of open file descriptors. It also allows assigning the process to a specific cgroup for further resource control. ```APIDOC ## minijail_rlimit / minijail_add_to_cgroup — Resource Limits and Cgroups (C) Set hard and soft resource limits (rlimits) and assign the jailed process to a cgroup. ### Function Signatures ```c void minijail_rlimit(struct minijail *j, int resource, rlim_t soft, rlim_t hard); void minijail_add_to_cgroup(struct minijail *j, const char *path); ``` ### Parameters - **minijail_rlimit**: - **j** (struct minijail *): Pointer to an initialized minijail context. - **resource** (int): The resource to limit (e.g., `RLIMIT_AS`, `RLIMIT_NOFILE`). - **soft** (rlim_t): The soft limit for the resource. - **hard** (rlim_t): The hard limit for the resource. - **minijail_add_to_cgroup**: - **j** (struct minijail *): Pointer to an initialized minijail context. - **path** (const char *): The path to the cgroup's tasks file (e.g., `/sys/fs/cgroup/cpu/jailed/tasks`). ### Example Usage ```c #include #include int main(void) { struct minijail *j = minijail_new(); /* Limit virtual address space to 256 MB */ minijail_rlimit(j, RLIMIT_AS, 256*1024*1024, 256*1024*1024); /* Limit open file descriptors */ minijail_rlimit(j, RLIMIT_NOFILE, 64, 64); /* Limit CPU time (seconds) */ minijail_rlimit(j, RLIMIT_CPU, 10, 10); /* Assign to a cgroup's tasks file */ minijail_add_to_cgroup(j, "/sys/fs/cgroup/cpu/jailed/tasks"); minijail_add_to_cgroup(j, "/sys/fs/cgroup/memory/jailed/tasks"); char *argv[] = { "/usr/bin/my-service", NULL }; minijail_run(j, "/usr/bin/my-service", argv); minijail_wait(j); minijail_destroy(j); return 0; } ``` ``` -------------------------------- ### Clone Minijail Repository Source: https://github.com/google/minijail/blob/main/README.md Clone the official Minijail source repository using git. ```shell git clone https://chromium.googlesource.com/chromiumos/platform/minijail cd minijail ``` -------------------------------- ### minijail_run_pid_pipes Source: https://context7.com/google/minijail/llms.txt Runs a sandboxed child process, providing access to its PID, stdin, stdout, and stderr for interaction and monitoring. This is useful for scenarios where you need to feed input to a process and read its output programmatically. ```APIDOC ## minijail_run_pid_pipes — Run with Full I/O Control (C) Fork a sandboxed child while retaining handles to its stdin/stdout/stderr and its PID for interaction and monitoring. ### Function Signature ```c int minijail_run_pid_pipes(struct minijail *j, const char *path, char *const argv[], pid_t *child_pid, int *stdin_fd, int *stdout_fd, int *stderr_fd); ``` ### Parameters - **j** (struct minijail *): Pointer to an initialized minijail context. - **path** (const char *): The path to the executable to run. - **argv** (char *const argv[]): An array of strings representing the arguments for the executable. - **child_pid** (pid_t *): Pointer to store the PID of the child process. - **stdin_fd** (int *): Pointer to store the file descriptor for the child's stdin. - **stdout_fd** (int *): Pointer to store the file descriptor for the child's stdout. - **stderr_fd** (int *): Pointer to store the file descriptor for the child's stderr. ### Return Value Returns 0 on success, or a non-zero error code on failure. ### Example Usage ```c #include #include #include int main(void) { struct minijail *j = minijail_new(); minijail_no_new_privs(j); minijail_parse_seccomp_filters(j, "/etc/worker.policy"); minijail_use_seccomp_filter(j); pid_t child_pid; int stdin_fd, stdout_fd, stderr_fd; char *argv[] = { "/usr/bin/worker", "--json", NULL }; int ret = minijail_run_pid_pipes(j, "/usr/bin/worker", argv, &child_pid, &stdin_fd, &stdout_fd, &stderr_fd); if (ret != 0) { fprintf(stderr, "Failed to launch sandboxed worker\n"); minijail_destroy(j); return 1; } /* Send input to the sandboxed process */ const char *input = "{\"task\": \"process\"}\n"; write(stdin_fd, input, strlen(input)); close(stdin_fd); /* Read its output */ char buf[4096]; ssize_t n; while ((n = read(stdout_fd, buf, sizeof(buf) - 1)) > 0) { buf[n] = '\0'; printf("Worker output: %s", buf); } close(stdout_fd); close(stderr_fd); /* Wait for exit and check status */ int status = minijail_wait(j); /* status == 0 on success, MINIJAIL_ERR_SECCOMP_VIOLATION (253) on seccomp kill */ printf("Worker exited with status %d (pid %d)\n", status, child_pid); minijail_destroy(j); return status; } ``` ``` -------------------------------- ### minijail_use_caps / minijail_capbset_drop Source: https://context7.com/google/minijail/llms.txt Manage Linux capabilities for a process within a Minijail. You can either specify the exact capabilities to keep using `minijail_use_caps` or drop specific capabilities from the bounding set using `minijail_capbset_drop`. ```APIDOC ## `minijail_use_caps` / `minijail_capbset_drop` — Capability Management (C) Restrict Linux capabilities to precisely what the program requires, or drop them entirely. ```c #include #include int main(void) { struct minijail *j = minijail_new(); minijail_change_user(j, "svc"); minijail_change_group(j, "svc"); /* Keep only CAP_NET_BIND_SERVICE and CAP_SYS_CHROOT */ uint64_t caps = CAP_TO_MASK(CAP_NET_BIND_SERVICE) | CAP_TO_MASK(CAP_SYS_CHROOT); minijail_use_caps(j, caps); /* Raise ambient capabilities so child processes inherit them across execve without needing file capabilities */ minijail_set_ambient_caps(j); /* OR: drop specific caps from the bounding set (mutually exclusive with use_caps) */ /* minijail_capbset_drop(j, CAP_TO_MASK(CAP_SYS_ADMIN)); */ char *argv[] = { "/usr/sbin/my-daemon", NULL }; minijail_run(j, "/usr/sbin/my-daemon", argv); minijail_wait(j); minijail_destroy(j); return 0; } ``` ```