apply-seccomp.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. /*
  2. * apply-seccomp.c - Apply seccomp BPF filter in an isolated PID namespace
  3. *
  4. * Usage: apply-seccomp <command> [args...]
  5. *
  6. * This program applies a baked-in seccomp BPF filter, isolates the
  7. * target command in a nested user+PID+mount namespace so it cannot see or
  8. * ptrace any process that lacks the filter, applies the filter with
  9. * prctl(PR_SET_SECCOMP), and execs the command.
  10. *
  11. * Process layout inside the outer bwrap sandbox:
  12. *
  13. * bwrap init (PID 1) <- outer PID ns, no seccomp
  14. * \_ bash / socat ... <- outer PID ns, no seccomp
  15. * \_ apply-seccomp [outer] <- outer PID ns, waits for inner init
  16. * ================================================= PID ns boundary
  17. * \_ apply-seccomp [inner init] <- inner PID 1, PR_SET_DUMPABLE=0
  18. * \_ user command <- inner PID 2, seccomp applied
  19. *
  20. * From the user command's point of view /proc contains only its own process
  21. * tree. The bwrap init, bash wrapper, and socat helpers are not addressable,
  22. * so they cannot be ptraced or patched via /proc/N/mem even on systems with
  23. * kernel.yama.ptrace_scope=0. The inner init (PID 1) sets PR_SET_DUMPABLE=0
  24. * so it cannot be ptraced either.
  25. *
  26. * Any failure to set up the nested namespaces aborts with a non-zero exit
  27. * status; we never fall back to running the command without isolation.
  28. *
  29. * Compile: gcc -static -O2 -o apply-seccomp apply-seccomp.c
  30. */
  31. #define _GNU_SOURCE
  32. #include <stddef.h>
  33. #include <stdio.h>
  34. #include <stdlib.h>
  35. #include <stdarg.h>
  36. #include <string.h>
  37. #include <unistd.h>
  38. #include <fcntl.h>
  39. #include <errno.h>
  40. #include <limits.h>
  41. #include <stdint.h>
  42. #include <sched.h>
  43. #include <signal.h>
  44. #include <sys/prctl.h>
  45. #include <sys/wait.h>
  46. #include <sys/mount.h>
  47. #include <sys/socket.h>
  48. #include <sys/un.h>
  49. #include <sys/uio.h>
  50. #include <sys/ioctl.h>
  51. #include <sys/syscall.h>
  52. #include <poll.h>
  53. #include <linux/seccomp.h>
  54. #include <linux/filter.h>
  55. #include <linux/audit.h>
  56. #include <linux/bpf_common.h>
  57. #include <linux/capability.h>
  58. #include "unix-block-bpf.h"
  59. #ifndef PR_SET_NO_NEW_PRIVS
  60. #define PR_SET_NO_NEW_PRIVS 38
  61. #endif
  62. #ifndef PR_CAP_AMBIENT
  63. #define PR_CAP_AMBIENT 47
  64. #define PR_CAP_AMBIENT_CLEAR_ALL 4
  65. #endif
  66. #ifndef SECCOMP_MODE_FILTER
  67. #define SECCOMP_MODE_FILTER 2
  68. #endif
  69. #ifndef SECCOMP_FILTER_FLAG_NEW_LISTENER
  70. #define SECCOMP_FILTER_FLAG_NEW_LISTENER (1UL << 3)
  71. #endif
  72. #ifndef SECCOMP_RET_USER_NOTIF
  73. #define SECCOMP_RET_USER_NOTIF 0x7fc00000U
  74. #endif
  75. #if defined(__x86_64__)
  76. # define SRT_AUDIT_ARCH AUDIT_ARCH_X86_64
  77. # define SRT_HAS_X32 1
  78. #elif defined(__aarch64__)
  79. # define SRT_AUDIT_ARCH AUDIT_ARCH_AARCH64
  80. # define SRT_HAS_X32 0
  81. #else
  82. # define SRT_AUDIT_ARCH 0
  83. # define SRT_HAS_X32 0
  84. #endif
  85. /* ---- Optional passive observation filter ---------------------------------
  86. *
  87. * When SRT_OBSERVE_SOCK is set the worker installs a second seccomp filter
  88. * that traps write-intent filesystem syscalls to
  89. * SECCOMP_RET_USER_NOTIF, then ships the listener fd to the OUTER STUB over
  90. * a pre-fork socketpair. The outer stub is never under either filter, so it
  91. * services every notification with SECCOMP_USER_NOTIF_FLAG_CONTINUE — the
  92. * workload's behaviour is unchanged — and writes one JSON line per
  93. * observed call to the SRT_OBSERVE_SOCK unix socket (a Node net.Server).
  94. *
  95. * Paths are read from the workload's address space with process_vm_readv.
  96. * That memory is ATTACKER-CONTROLLED and racy (the workload can rewrite the
  97. * buffer between trap and read). bwrap's mount table is the only enforcement
  98. * boundary; the path reported here is a HINT for diagnostics and must never
  99. * gate a policy decision.
  100. *
  101. * Every failure path is fail-open: any error before the filter is installed
  102. * disables observation and proceeds; any error after still drains the notify
  103. * fd with CONTINUE so the workload cannot wedge. */
  104. #ifndef SECCOMP_IOCTL_NOTIF_RECV
  105. # define SECCOMP_IOC_MAGIC '!'
  106. # define SECCOMP_IOCTL_NOTIF_RECV _IOWR(SECCOMP_IOC_MAGIC, 0, struct seccomp_notif)
  107. # define SECCOMP_IOCTL_NOTIF_SEND _IOWR(SECCOMP_IOC_MAGIC, 1, struct seccomp_notif_resp)
  108. # define SECCOMP_IOCTL_NOTIF_ID_VALID _IOW (SECCOMP_IOC_MAGIC, 2, __u64)
  109. #endif
  110. #ifndef SECCOMP_USER_NOTIF_FLAG_CONTINUE
  111. # define SECCOMP_USER_NOTIF_FLAG_CONTINUE (1UL << 0)
  112. #endif
  113. #ifndef SECCOMP_FILTER_FLAG_TSYNC_ESRCH
  114. # define SECCOMP_FILTER_FLAG_TSYNC_ESRCH (1UL << 4)
  115. #endif
  116. #ifndef AT_FDCWD
  117. # define AT_FDCWD (-100)
  118. #endif
  119. #ifndef SECCOMP_GET_NOTIF_SIZES
  120. # define SECCOMP_GET_NOTIF_SIZES 3
  121. #endif
  122. #ifndef __NR_pidfd_open
  123. # define __NR_pidfd_open 434
  124. #endif
  125. #ifndef __NR_fchmodat2
  126. # define __NR_fchmodat2 452
  127. #endif
  128. #define OBS_WRITE_MASK ((unsigned)(O_WRONLY | O_RDWR | O_CREAT | O_TRUNC | O_APPEND))
  129. #define OBS_PATH_MAX 4096
  130. #define OBS_LINE_CAP (OBS_PATH_MAX * 2 + 256)
  131. /* Single source of truth for the observed-syscall set. The BPF program and
  132. * the supervisor's name/path-arg lookup are both derived from this table so
  133. * they cannot drift. flags_arg >= 0 means the BPF gates the trap on
  134. * args[flags_arg] & OBS_WRITE_MASK; -1 means always trap. */
  135. struct observe_call {
  136. int nr;
  137. const char *name;
  138. int8_t path_arg;
  139. int8_t path2_arg;
  140. int8_t flags_arg;
  141. /* Argument index of the dirfd governing path_arg/path2_arg, or -1 when
  142. * the path is resolved against the caller's cwd (legacy entry points). */
  143. int8_t dirfd_arg;
  144. int8_t dirfd2_arg;
  145. };
  146. static const struct observe_call observe_calls[] = {
  147. { __NR_openat, "openat", 1, -1, 2, 0, -1 },
  148. #ifdef __NR_openat2
  149. { __NR_openat2, "openat2", 1, -1, -1, 0, -1 },
  150. #endif
  151. { __NR_unlinkat, "unlinkat", 1, -1, -1, 0, -1 },
  152. { __NR_mkdirat, "mkdirat", 1, -1, -1, 0, -1 },
  153. { __NR_mknodat, "mknodat", 1, -1, -1, 0, -1 },
  154. { __NR_symlinkat, "symlinkat", 2, -1, -1, 1, -1 },
  155. { __NR_linkat, "linkat", 1, 3, -1, 0, 2 },
  156. #ifdef __NR_renameat
  157. { __NR_renameat, "renameat", 1, 3, -1, 0, 2 },
  158. #endif
  159. { __NR_renameat2, "renameat2", 1, 3, -1, 0, 2 },
  160. { __NR_fchmodat, "fchmodat", 1, -1, -1, 0, -1 },
  161. { __NR_fchmodat2, "fchmodat2", 1, -1, -1, 0, -1 },
  162. { __NR_fchownat, "fchownat", 1, -1, -1, 0, -1 },
  163. { __NR_utimensat, "utimensat", 1, -1, -1, 0, -1 },
  164. #ifdef __x86_64__
  165. /* Legacy non-*at entry points: glibc/coreutils still call these directly
  166. * on x86_64. aarch64 only ever had the *at forms. */
  167. { __NR_open, "open", 0, -1, 1, -1, -1 },
  168. { __NR_creat, "creat", 0, -1, -1, -1, -1 },
  169. { __NR_unlink, "unlink", 0, -1, -1, -1, -1 },
  170. { __NR_rmdir, "rmdir", 0, -1, -1, -1, -1 },
  171. { __NR_rename, "rename", 0, 1, -1, -1, -1 },
  172. { __NR_link, "link", 0, 1, -1, -1, -1 },
  173. { __NR_symlink, "symlink", 1, -1, -1, -1, -1 },
  174. { __NR_mkdir, "mkdir", 0, -1, -1, -1, -1 },
  175. { __NR_mknod, "mknod", 0, -1, -1, -1, -1 },
  176. { __NR_truncate, "truncate", 0, -1, -1, -1, -1 },
  177. { __NR_chmod, "chmod", 0, -1, -1, -1, -1 },
  178. { __NR_chown, "chown", 0, -1, -1, -1, -1 },
  179. { __NR_lchown, "lchown", 0, -1, -1, -1, -1 },
  180. { __NR_utime, "utime", 0, -1, -1, -1, -1 },
  181. { __NR_utimes, "utimes", 0, -1, -1, -1, -1 },
  182. #endif
  183. };
  184. static const int n_observe_calls = (int)(sizeof(observe_calls)/sizeof(observe_calls[0]));
  185. static const struct observe_call *find_observe_call(int nr) {
  186. for (int i = 0; i < n_observe_calls; i++)
  187. if (observe_calls[i].nr == nr) return &observe_calls[i];
  188. return NULL;
  189. }
  190. static int build_observe_bpf(struct sock_filter *f, int cap) {
  191. int n = 0;
  192. #define EMIT(ins) do { if (n >= cap) return -1; f[n++] = (struct sock_filter)ins; } while (0)
  193. /* arch check */
  194. EMIT(BPF_STMT(BPF_LD | BPF_W | BPF_ABS,
  195. offsetof(struct seccomp_data, arch)));
  196. int j_arch = n;
  197. EMIT(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SRT_AUDIT_ARCH, 0, 0)); /* jf→ALLOW */
  198. /* nr */
  199. EMIT(BPF_STMT(BPF_LD | BPF_W | BPF_ABS,
  200. offsetof(struct seccomp_data, nr)));
  201. #if SRT_HAS_X32
  202. int j_x32 = n;
  203. EMIT(BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, 0x40000000u, 0, 0)); /* jt→ALLOW */
  204. #endif
  205. /* Always-trap syscalls (flags_arg < 0). */
  206. int j_trap[64], ntrap = 0;
  207. for (int i = 0; i < n_observe_calls; i++) {
  208. if (observe_calls[i].flags_arg >= 0) continue;
  209. j_trap[ntrap++] = n;
  210. EMIT(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K,
  211. (unsigned)observe_calls[i].nr, 0, 0)); /* jt→NOTIFY */
  212. }
  213. /* Flags-gated syscalls: trap only when args[flags_arg] & OBS_WRITE_MASK.
  214. * Each gated syscall emits a 4-instruction block; jf of the JEQ chains to
  215. * the next block, last chains to ALLOW. After the flags load the
  216. * accumulator no longer holds nr, so a non-match must reload nr — handled
  217. * by chaining JEQ jf directly past the load. */
  218. struct { int jeq, jflags; } gated[4];
  219. int ngated = 0;
  220. for (int i = 0; i < n_observe_calls; i++) {
  221. if (observe_calls[i].flags_arg < 0) continue;
  222. gated[ngated].jeq = n;
  223. EMIT(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K,
  224. (unsigned)observe_calls[i].nr, 0, 0)); /* jf→next gated / ALLOW */
  225. EMIT(BPF_STMT(BPF_LD | BPF_W | BPF_ABS,
  226. offsetof(struct seccomp_data, args) +
  227. (size_t)observe_calls[i].flags_arg * sizeof(__u64)));
  228. EMIT(BPF_STMT(BPF_ALU | BPF_AND | BPF_K, OBS_WRITE_MASK));
  229. gated[ngated].jflags = n;
  230. EMIT(BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 0)); /* jt→ALLOW jf→NOTIFY */
  231. ngated++;
  232. }
  233. int allow_at = n;
  234. EMIT(BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW));
  235. int notify_at = n;
  236. EMIT(BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_USER_NOTIF));
  237. #define TO(idx, tgt) ((unsigned char)((tgt) - (idx) - 1))
  238. f[j_arch].jf = TO(j_arch, allow_at);
  239. #if SRT_HAS_X32
  240. f[j_x32].jt = TO(j_x32, allow_at);
  241. #endif
  242. for (int i = 0; i < ntrap; i++) f[j_trap[i]].jt = TO(j_trap[i], notify_at);
  243. for (int i = 0; i < ngated; i++) {
  244. int next = (i + 1 < ngated) ? gated[i + 1].jeq : allow_at;
  245. f[gated[i].jeq].jf = TO(gated[i].jeq, next);
  246. f[gated[i].jflags].jt = TO(gated[i].jflags, allow_at);
  247. f[gated[i].jflags].jf = TO(gated[i].jflags, notify_at);
  248. }
  249. #undef TO
  250. #undef EMIT
  251. return n;
  252. }
  253. /* Send a single fd over a connected stream socket via SCM_RIGHTS. */
  254. static int send_fd(int sock, int fd) {
  255. char dummy = 'F';
  256. union { struct cmsghdr align; char ctl[CMSG_SPACE(sizeof(int))]; } u;
  257. memset(&u, 0, sizeof(u));
  258. struct iovec iov = { .iov_base = &dummy, .iov_len = 1 };
  259. struct msghdr msg = { .msg_iov = &iov, .msg_iovlen = 1,
  260. .msg_control = u.ctl, .msg_controllen = sizeof(u.ctl) };
  261. struct cmsghdr *c = CMSG_FIRSTHDR(&msg);
  262. c->cmsg_level = SOL_SOCKET; c->cmsg_type = SCM_RIGHTS;
  263. c->cmsg_len = CMSG_LEN(sizeof(int));
  264. memcpy(CMSG_DATA(c), &fd, sizeof(int));
  265. return sendmsg(sock, &msg, 0) < 0 ? -1 : 0;
  266. }
  267. /* Receive at most one fd. Returns the fd, or -1 if the peer sent no fd or
  268. * closed (worker declined to install the filter). */
  269. static int recv_fd(int sock) {
  270. char dummy;
  271. union { struct cmsghdr align; char ctl[CMSG_SPACE(sizeof(int))]; } u;
  272. memset(&u, 0, sizeof(u));
  273. struct iovec iov = { .iov_base = &dummy, .iov_len = 1 };
  274. struct msghdr msg = { .msg_iov = &iov, .msg_iovlen = 1,
  275. .msg_control = u.ctl, .msg_controllen = sizeof(u.ctl) };
  276. ssize_t r = recvmsg(sock, &msg, 0);
  277. if (r <= 0) return -1;
  278. for (struct cmsghdr *c = CMSG_FIRSTHDR(&msg); c; c = CMSG_NXTHDR(&msg, c)) {
  279. if (c->cmsg_level == SOL_SOCKET && c->cmsg_type == SCM_RIGHTS &&
  280. c->cmsg_len >= CMSG_LEN(sizeof(int))) {
  281. int fd; memcpy(&fd, CMSG_DATA(c), sizeof(int));
  282. return fd;
  283. }
  284. }
  285. return -1;
  286. }
  287. /* Called in the WORKER after PR_SET_NO_NEW_PRIVS. Installs the USER_NOTIF
  288. * filter and ships the listener fd to the outer stub over the pre-fork
  289. * socketpair. Never fatal: any pre-filter failure sends a no-fd marker and
  290. * returns; any post-filter failure raw-writes a diagnostic and _exit()s
  291. * (continuing would either wedge on the next matched syscall or leave a
  292. * filter with no listener, which makes matched syscalls fail ENOSYS).
  293. *
  294. * Audited syscalls between the seccomp() return and execve():
  295. * sendmsg, close, close, prctl(PR_SET_SECCOMP), execve
  296. * None are in the observe match set (write-intent fs) and none are
  297. * in the unix-block set (socket(AF_UNIX)/io_uring), so the worker cannot
  298. * trap on itself before exec. perror()/snprintf() are deliberately avoided
  299. * post-filter to keep this set closed. */
  300. static void install_observe_filter(int sp_fd) {
  301. if (sp_fd < 0) return;
  302. int debug = getenv("SRT_OBSERVE_DEBUG") != NULL;
  303. /* The supervisor replies with SECCOMP_USER_NOTIF_FLAG_CONTINUE, which
  304. * kernels older than 5.5 reject with EINVAL *without* completing the
  305. * notification — the trapped syscall would block forever. CONTINUE is
  306. * a response flag with no direct probe, so detect it the way
  307. * libseccomp does: validate a filter flag from the same era with a
  308. * NULL prog. EFAULT = flag known (nothing installed), EINVAL = too
  309. * old — skip the observer entirely and stay fail-open. */
  310. if (!(syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER,
  311. SECCOMP_FILTER_FLAG_TSYNC_ESRCH, NULL) == -1 &&
  312. errno == EFAULT)) {
  313. if (debug) dprintf(2, "apply-seccomp: observe feature probe failed: %s\n",
  314. strerror(errno));
  315. (void)!write(sp_fd, "E", 1);
  316. close(sp_fd);
  317. return;
  318. }
  319. struct sock_filter filt[80];
  320. int len = build_observe_bpf(filt, (int)(sizeof(filt)/sizeof(filt[0])));
  321. if (len < 0) { (void)!write(sp_fd, "E", 1); close(sp_fd); return; }
  322. struct sock_fprog prog = { .len = (unsigned short)len, .filter = filt };
  323. int nfd = (int)syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER,
  324. SECCOMP_FILTER_FLAG_NEW_LISTENER, &prog);
  325. if (nfd < 0) {
  326. /* EINVAL: kernel <5.0. EBUSY: another listener already installed.
  327. * Either way, no filter is active — fail open. */
  328. if (debug) dprintf(2, "apply-seccomp: observe listener failed: %s\n",
  329. strerror(errno));
  330. (void)!write(sp_fd, "E", 1);
  331. close(sp_fd);
  332. return;
  333. }
  334. /* --- filter is now live --- */
  335. if (send_fd(sp_fd, nfd) < 0) {
  336. static const char msg[] = "apply-seccomp: observe sendmsg failed\n";
  337. (void)!write(2, msg, sizeof(msg) - 1);
  338. _exit(125);
  339. }
  340. close(sp_fd);
  341. close(nfd); /* outer stub now holds the only reference */
  342. }
  343. /* ---- Outer-stub supervisor --------------------------------------------- */
  344. static void json_escape_into(char *dst, size_t dstcap, const char *src, size_t srclen) {
  345. static const char hex[] = "0123456789abcdef";
  346. size_t o = 0;
  347. for (size_t i = 0; i < srclen && o + 7 < dstcap; i++) {
  348. unsigned char c = (unsigned char)src[i];
  349. if (c == '"' || c == '\\') { dst[o++]='\\'; dst[o++]=(char)c; }
  350. else if (c < 0x20) { dst[o++]='\\'; dst[o++]='u'; dst[o++]='0'; dst[o++]='0';
  351. dst[o++]=hex[c>>4]; dst[o++]=hex[c&0xf]; }
  352. else { dst[o++]=(char)c; }
  353. }
  354. dst[o] = '\0';
  355. }
  356. static ssize_t read_remote_bytes(pid_t pid, unsigned long addr, char *dst, size_t cap) {
  357. if (addr == 0) return -1;
  358. struct iovec local = { .iov_base = dst, .iov_len = cap };
  359. struct iovec remote = { .iov_base = (void *)addr, .iov_len = cap };
  360. return process_vm_readv(pid, &local, 1, &remote, 1, 0);
  361. }
  362. static ssize_t read_remote_cstr(pid_t pid, unsigned long addr, char *dst, size_t cap) {
  363. ssize_t r = read_remote_bytes(pid, addr, dst, cap);
  364. if (r < 0 && errno == EFAULT) {
  365. /* String may sit at the tail of a mapping. */
  366. size_t first = 4096 - (addr & 4095);
  367. if (first > cap) first = cap;
  368. r = read_remote_bytes(pid, addr, dst, first);
  369. }
  370. if (r <= 0) return -1;
  371. char *nul = memchr(dst, '\0', (size_t)r);
  372. return nul ? (nul - dst) : r;
  373. }
  374. /* Resolve a relative path against the tracee's cwd or dirfd via the /proc
  375. * magic symlinks. The tracee is frozen inside the trapped syscall, so both
  376. * links are stable for single-threaded callers; a racing sibling thread can
  377. * at worst mislabel one LOG line (this channel never enforces anything).
  378. *
  379. * host_proc_fd is an O_PATH handle to /proc opened BEFORE the pid/mount
  380. * unshare: the worker later mounts a fresh /proc for the new pid namespace
  381. * into the mount namespace this process shares with it, which removes the
  382. * host-pid entries from the PATH "/proc" — but the held fd pins the
  383. * original superblock, and the notification's pid is a host-namespace pid.
  384. *
  385. * Returns the joined length, or 0 on ANY failure — the caller then skips
  386. * the event entirely (best-effort telemetry: never guess, never block). */
  387. static size_t resolve_relative(int host_proc_fd, pid_t pid,
  388. const struct seccomp_notif *req,
  389. int dirfd_arg, const char *rel, size_t rellen,
  390. char *dst, size_t dstcap) {
  391. if (host_proc_fd < 0) return 0;
  392. char link[64];
  393. /* The dirfd syscall argument is an int; the kernel exposes the raw
  394. * 64-bit register, so AT_FDCWD arrives zero-extended. Truncate. */
  395. int dirfd = dirfd_arg >= 0 ? (int)(uint32_t)req->data.args[dirfd_arg]
  396. : AT_FDCWD;
  397. int n;
  398. if (dirfd == AT_FDCWD) {
  399. n = snprintf(link, sizeof(link), "%d/cwd", (int)pid);
  400. } else {
  401. if (dirfd < 0) return 0; /* junk fd value */
  402. n = snprintf(link, sizeof(link), "%d/fd/%d", (int)pid, dirfd);
  403. }
  404. if (n <= 0 || (size_t)n >= sizeof(link)) return 0;
  405. ssize_t bl = readlinkat(host_proc_fd, link, dst, dstcap - 1);
  406. if (bl <= 0) return 0; /* pid gone, fd closed, EACCES... */
  407. if (dst[0] != '/') return 0; /* memfd:/pipe:/socket: pseudo-name */
  408. if ((size_t)bl + 1 + rellen + 1 > dstcap) return 0; /* would truncate */
  409. size_t o = (size_t)bl;
  410. dst[o++] = '/';
  411. memcpy(dst + o, rel, rellen);
  412. o += rellen;
  413. dst[o] = '\0';
  414. return o;
  415. }
  416. static void emit_event(int out, const struct observe_call *oc, int nr, pid_t pid,
  417. const char *path, size_t pathlen, const char *enc) {
  418. if (out < 0) return;
  419. char esc[OBS_LINE_CAP];
  420. json_escape_into(esc, sizeof(esc), path, pathlen);
  421. char line[OBS_LINE_CAP + 512];
  422. int n;
  423. if (enc && *enc) {
  424. n = snprintf(line, sizeof(line),
  425. "{\"nr\":%d,\"syscall\":\"%s\",\"pid\":%d,\"path\":\"%s\","
  426. "\"encodedCommand\":\"%s\"}\n",
  427. nr, oc ? oc->name : "syscall", (int)pid, esc, enc);
  428. } else {
  429. n = snprintf(line, sizeof(line),
  430. "{\"nr\":%d,\"syscall\":\"%s\",\"pid\":%d,\"path\":\"%s\"}\n",
  431. nr, oc ? oc->name : "syscall", (int)pid, esc);
  432. }
  433. /* Never wait on the consumer: the pipe is a bounded queue and this
  434. * channel is best-effort — full pipe drops the note (a short write
  435. * corrupts at most one line, which the listener already ignores). */
  436. if (n > 0) {
  437. (void)!send(out, line,
  438. (size_t)(n < (int)sizeof(line) ? n : (int)sizeof(line)-1),
  439. MSG_DONTWAIT | MSG_NOSIGNAL);
  440. }
  441. }
  442. static int connect_observe_sock(const char *path) {
  443. if (!path || !*path) return -1;
  444. int s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
  445. if (s < 0) return -1;
  446. struct sockaddr_un sa = { .sun_family = AF_UNIX };
  447. if (strlen(path) >= sizeof(sa.sun_path)) {
  448. close(s); errno = ENAMETOOLONG; return -1;
  449. }
  450. strcpy(sa.sun_path, path);
  451. if (connect(s, (struct sockaddr *)&sa, sizeof(sa)) < 0) { close(s); return -1; }
  452. /* Don't take SIGPIPE if Node drops the connection mid-run. */
  453. signal(SIGPIPE, SIG_IGN);
  454. return s;
  455. }
  456. /* Service the notify fd until the inner-init child exits. Runs in the OUTER
  457. * STUB, which never installed either seccomp filter. Always replies CONTINUE,
  458. * even when out_sock < 0, so a missing listener never wedges the workload. */
  459. static void supervise(pid_t child, int notify_fd, int out_sock,
  460. const char *enc, int host_proc_fd) {
  461. struct seccomp_notif_sizes sz;
  462. if (syscall(SYS_seccomp, SECCOMP_GET_NOTIF_SIZES, 0, &sz) < 0) {
  463. sz.seccomp_notif = sizeof(struct seccomp_notif);
  464. sz.seccomp_notif_resp = sizeof(struct seccomp_notif_resp);
  465. }
  466. struct seccomp_notif *req = calloc(1, sz.seccomp_notif);
  467. struct seccomp_notif_resp *resp = calloc(1, sz.seccomp_notif_resp);
  468. char *pbuf = malloc(OBS_PATH_MAX);
  469. char *fbuf1 = malloc(OBS_PATH_MAX * 2);
  470. char *fbuf2 = malloc(OBS_PATH_MAX * 2);
  471. if (!req || !resp || !pbuf || !fbuf1 || !fbuf2) return;
  472. int pidfd = (int)syscall(__NR_pidfd_open, child, 0);
  473. struct pollfd pfds[2];
  474. pfds[0].fd = notify_fd; pfds[0].events = POLLIN;
  475. pfds[1].fd = pidfd; pfds[1].events = POLLIN;
  476. nfds_t nfds = pidfd >= 0 ? 2 : 1;
  477. int tmo = pidfd >= 0 ? -1 : 200;
  478. int debug = getenv("SRT_OBSERVE_DEBUG") != NULL;
  479. int reported_read_error = 0;
  480. for (;;) {
  481. int pr = poll(pfds, nfds, tmo);
  482. if (pr < 0) { if (errno == EINTR) continue; break; }
  483. if (pfds[0].revents & POLLIN) {
  484. memset(req, 0, sz.seccomp_notif);
  485. if (ioctl(notify_fd, SECCOMP_IOCTL_NOTIF_RECV, req) == 0) {
  486. const struct observe_call *oc = find_observe_call(req->data.nr);
  487. /* Capture while the caller is frozen (its memory, cwd and
  488. * dirfds are stable), but EMIT only after the reply: the
  489. * workload's pause must contain no work besides this
  490. * capture — never a pipe write. */
  491. size_t flen[2] = { 0, 0 };
  492. if (oc && out_sock >= 0 &&
  493. ioctl(notify_fd, SECCOMP_IOCTL_NOTIF_ID_VALID, &req->id) == 0) {
  494. int idxs[2] = { oc->path_arg, oc->path2_arg };
  495. int dirfds[2] = { oc->dirfd_arg, oc->dirfd2_arg };
  496. for (int k = 0; k < 2; k++) {
  497. if (idxs[k] < 0) continue;
  498. char *out = k == 0 ? fbuf1 : fbuf2;
  499. ssize_t l = read_remote_cstr(req->pid,
  500. (unsigned long)req->data.args[idxs[k]],
  501. pbuf, OBS_PATH_MAX);
  502. if (l <= 0) {
  503. if (debug && !reported_read_error) {
  504. dprintf(2,
  505. "apply-seccomp: observe path read failed for pid %d: %s\n",
  506. (int)req->pid, strerror(errno));
  507. reported_read_error = 1;
  508. }
  509. continue;
  510. }
  511. if (pbuf[0] == '/') {
  512. memcpy(out, pbuf, (size_t)l);
  513. flen[k] = (size_t)l;
  514. continue;
  515. }
  516. /* Relative: resolve against the tracee's cwd or
  517. * dirfd. Unresolvable → skip (best effort). */
  518. flen[k] = resolve_relative(host_proc_fd,
  519. req->pid, req, dirfds[k],
  520. pbuf, (size_t)l, out, OBS_PATH_MAX * 2);
  521. }
  522. }
  523. memset(resp, 0, sz.seccomp_notif_resp);
  524. resp->id = req->id;
  525. resp->flags = SECCOMP_USER_NOTIF_FLAG_CONTINUE;
  526. (void)ioctl(notify_fd, SECCOMP_IOCTL_NOTIF_SEND, resp);
  527. for (int k = 0; k < 2; k++) {
  528. if (flen[k] > 0) {
  529. emit_event(out_sock, oc, req->data.nr, req->pid,
  530. k == 0 ? fbuf1 : fbuf2, flen[k], enc);
  531. }
  532. }
  533. } else if (errno != EINTR && errno != ENOENT) {
  534. break;
  535. }
  536. }
  537. /* All filtered tasks gone → notify fd reports EOF. */
  538. if (pfds[0].revents & (POLLHUP | POLLERR)) break;
  539. if (pidfd >= 0) {
  540. if (pfds[1].revents) break;
  541. } else {
  542. /* WNOWAIT: leave the zombie for the caller's waitpid. */
  543. siginfo_t si = {0};
  544. if (waitid(P_PID, (id_t)child, &si, WEXITED|WNOHANG|WNOWAIT) == 0 &&
  545. si.si_pid == child) break;
  546. }
  547. }
  548. if (pidfd >= 0) close(pidfd);
  549. free(req); free(resp); free(pbuf); free(fbuf1); free(fbuf2);
  550. }
  551. static void die(const char *msg) {
  552. perror(msg);
  553. _exit(1);
  554. }
  555. /* Clear effective, permitted and inheritable capabilities in the workload
  556. * process after the namespace/mount setup is complete. Clearing only the
  557. * ambient set is insufficient when apply-seccomp itself starts with an
  558. * effective capability set (as it does on a privileged runner): exec would
  559. * otherwise preserve those capabilities for an unprivileged file. */
  560. static void drop_all_capabilities(void) {
  561. struct __user_cap_header_struct header = {
  562. .version = _LINUX_CAPABILITY_VERSION_3,
  563. .pid = 0,
  564. };
  565. struct __user_cap_data_struct data[_LINUX_CAPABILITY_U32S_3] = {{0}};
  566. if (syscall(SYS_capset, &header, data) < 0) {
  567. die("apply-seccomp: capset(drop all)");
  568. }
  569. }
  570. static int write_file(const char *path, const char *fmt, ...) {
  571. char buf[256];
  572. va_list ap;
  573. va_start(ap, fmt);
  574. int len = vsnprintf(buf, sizeof(buf), fmt, ap);
  575. va_end(ap);
  576. if (len < 0 || (size_t)len >= sizeof(buf)) {
  577. errno = EOVERFLOW;
  578. return -1;
  579. }
  580. int fd = open(path, O_WRONLY);
  581. if (fd < 0) {
  582. return -1;
  583. }
  584. ssize_t r = write(fd, buf, (size_t)len);
  585. int saved = errno;
  586. close(fd);
  587. if (r != len) {
  588. errno = (r < 0) ? saved : EIO;
  589. return -1;
  590. }
  591. return 0;
  592. }
  593. /* PID the current process forwards signals to. Used by both the outer stub
  594. * (forwards to inner init) and the inner init (forwards to the worker).
  595. * PID 1 ignores signals it has no handler for, so the inner init MUST install
  596. * these or SIGTERM from the outside is silently dropped. */
  597. static volatile pid_t forward_target = -1;
  598. static void forward_signal(int sig) {
  599. if (forward_target > 0) {
  600. kill(forward_target, sig);
  601. }
  602. }
  603. static void install_forwarders(pid_t target) {
  604. forward_target = target;
  605. struct sigaction sa = { .sa_handler = forward_signal };
  606. sigemptyset(&sa.sa_mask);
  607. sigaction(SIGTERM, &sa, NULL);
  608. sigaction(SIGINT, &sa, NULL);
  609. sigaction(SIGHUP, &sa, NULL);
  610. sigaction(SIGQUIT, &sa, NULL);
  611. sigaction(SIGUSR1, &sa, NULL);
  612. sigaction(SIGUSR2, &sa, NULL);
  613. }
  614. /*
  615. * Wait for `main_child`, reaping any other children that exit first.
  616. * Returns as soon as `main_child` terminates — the caller then _exit()s,
  617. * which as PID 1 tears down the namespace and SIGKILLs any stragglers.
  618. * Returns an exit(3)-style status: exit code, or 128+signal.
  619. */
  620. static int reap_until(pid_t main_child) {
  621. int status = 0;
  622. for (;;) {
  623. pid_t r = waitpid(-1, &status, 0);
  624. if (r < 0) {
  625. if (errno == EINTR) {
  626. continue;
  627. }
  628. return 1; /* ECHILD without seeing main_child — shouldn't happen. */
  629. }
  630. if (r == main_child) {
  631. if (WIFEXITED(status)) {
  632. return WEXITSTATUS(status);
  633. }
  634. if (WIFSIGNALED(status)) {
  635. return 128 + WTERMSIG(status);
  636. }
  637. return 1;
  638. }
  639. /* Reaped an orphan that died before main_child; keep waiting. */
  640. }
  641. }
  642. int main(int argc, char *argv[]) {
  643. if (argc < 2) {
  644. fprintf(stderr, "Usage: %s <command> [args...]\n", argv[0]);
  645. return 1;
  646. }
  647. char **command_argv = &argv[1];
  648. _Static_assert(sizeof(unix_block_bpf) % sizeof(struct sock_filter) == 0,
  649. "BPF filter size must be a multiple of sock_filter");
  650. struct sock_fprog prog = {
  651. .len = (unsigned short)(sizeof(unix_block_bpf) / sizeof(struct sock_filter)),
  652. .filter = (struct sock_filter *)unix_block_bpf,
  653. };
  654. /* ---- Optional observation: pre-fork setup --------------------------- */
  655. const char *observe_sock = getenv("SRT_OBSERVE_SOCK");
  656. const char *encoded_cmd = getenv("SRT_ENCODED_CMD");
  657. int sp[2] = { -1, -1 };
  658. if (observe_sock && *observe_sock && SRT_AUDIT_ARCH != 0) {
  659. if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sp) < 0) {
  660. sp[0] = sp[1] = -1; /* fail open */
  661. }
  662. }
  663. /* ---- New PID + mount namespaces. Children (not us) enter the PID ns. ----
  664. *
  665. * Two paths to get CAP_SYS_ADMIN for the unshare:
  666. * (a) The caller (bwrap) kept CAP_SYS_ADMIN in this user namespace via
  667. * --cap-add. Just unshare directly.
  668. * (b) We don't have the cap. Create a nested user namespace to get it,
  669. * map uid/gid, then unshare. This also works when apply-seccomp is
  670. * run standalone outside bwrap.
  671. *
  672. * Path (a) is tried first. If the caller didn't give us the cap, the
  673. * kernel returns EPERM and we fall through to (b). Path (b) can itself
  674. * fail on hosts where unprivileged user namespaces are gated by an LSM
  675. * (Ubuntu 24.04's AppArmor restriction, for example) — the unshare
  676. * succeeds but the new namespace grants no capabilities, so the setgroups
  677. * write fails. In that case we abort: the caller must supply CAP_SYS_ADMIN.
  678. */
  679. /* Pinned handle to the CURRENT /proc: the worker's fresh /proc mount
  680. * for the new pid namespace lands in the mount namespace we are about
  681. * to unshare into (fork shares it), hiding host pids from the path
  682. * "/proc". Only used when observation is active; harmless otherwise. */
  683. int host_proc_fd = observe_sock && *observe_sock
  684. ? open("/proc", O_PATH | O_DIRECTORY | O_CLOEXEC)
  685. : -1;
  686. if (unshare(CLONE_NEWPID | CLONE_NEWNS) < 0) {
  687. if (errno != EPERM) {
  688. die("apply-seccomp: unshare(CLONE_NEWPID|CLONE_NEWNS)");
  689. }
  690. uid_t uid = geteuid();
  691. gid_t gid = getegid();
  692. /* If this binary was exec'd without read permission (e.g. installed
  693. * mode 0111), the kernel marked the process non-dumpable, which
  694. * makes /proc/self/{setgroups,uid_map,gid_map} root-owned, so the
  695. * writes below would fail with EACCES. Temporarily flip dumpable
  696. * on for the uid/gid mapping and restore it right after. While
  697. * dumpable is 1, a same-uid process can ptrace us (under yama
  698. * ptrace_scope=0) and dump the mapped pages that mode 0111 is
  699. * meant to hide; the save/restore keeps that exposure to a
  700. * few-syscall race window — the same unavoidable window runc and
  701. * systemd accept for this pattern.
  702. *
  703. * prctl failures here are ignored: they are next to impossible for
  704. * these calls, and if raising dumpable did fail the map writes
  705. * below fail with their own clearer errors. */
  706. int dumpable = prctl(PR_GET_DUMPABLE);
  707. (void)prctl(PR_SET_DUMPABLE, 1);
  708. if (unshare(CLONE_NEWUSER) < 0) {
  709. die("apply-seccomp: unshare(CLONE_NEWUSER)");
  710. }
  711. if (write_file("/proc/self/setgroups", "deny") < 0) {
  712. die("apply-seccomp: write /proc/self/setgroups "
  713. "(nested userns is capability-restricted; "
  714. "caller must provide CAP_SYS_ADMIN)");
  715. }
  716. if (write_file("/proc/self/uid_map", "%u %u 1\n", uid, uid) < 0) {
  717. die("apply-seccomp: write /proc/self/uid_map");
  718. }
  719. if (write_file("/proc/self/gid_map", "%u %u 1\n", gid, gid) < 0) {
  720. die("apply-seccomp: write /proc/self/gid_map");
  721. }
  722. /* PR_SET_DUMPABLE only accepts 0 or 1; if the saved value was
  723. * SUID_DUMP_ROOT (2) — or the read above failed — restore the more
  724. * restrictive 0. */
  725. (void)prctl(PR_SET_DUMPABLE, dumpable == 1 ? 1 : 0);
  726. if (unshare(CLONE_NEWPID | CLONE_NEWNS) < 0) {
  727. die("apply-seccomp: unshare(CLONE_NEWPID|CLONE_NEWNS) after userns");
  728. }
  729. }
  730. pid_t child = fork();
  731. if (child < 0) {
  732. die("apply-seccomp: fork");
  733. }
  734. if (child > 0) {
  735. /* Outer stub: still in bwrap's PID namespace. Forward signals,
  736. * optionally service the USER_NOTIF observation fd, then relay the
  737. * child's exit status. Never under either seccomp filter. */
  738. if (sp[1] >= 0) close(sp[1]);
  739. install_forwarders(child);
  740. if (sp[0] >= 0) {
  741. int notify_fd = recv_fd(sp[0]);
  742. close(sp[0]);
  743. if (notify_fd >= 0) {
  744. int out = connect_observe_sock(observe_sock);
  745. if (out < 0) {
  746. char buf[256];
  747. int n = snprintf(buf, sizeof(buf),
  748. "{\"observe_init_error\":\"connect %s: %s\"}\n",
  749. observe_sock, strerror(errno));
  750. (void)!write(2, buf, (size_t)n);
  751. } else if (encoded_cmd && *encoded_cmd) {
  752. char hdr[768];
  753. int n = snprintf(hdr, sizeof(hdr),
  754. "{\"encodedCommand\":\"%.700s\"}\n", encoded_cmd);
  755. if (n > 0) {
  756. (void)!send(out, hdr, (size_t)n,
  757. MSG_DONTWAIT | MSG_NOSIGNAL);
  758. }
  759. }
  760. supervise(child, notify_fd, out, encoded_cmd, host_proc_fd);
  761. if (out >= 0) close(out);
  762. close(notify_fd);
  763. }
  764. }
  765. int status;
  766. for (;;) {
  767. pid_t r = waitpid(child, &status, 0);
  768. if (r < 0 && errno == EINTR) continue;
  769. if (r < 0) die("apply-seccomp: waitpid");
  770. break;
  771. }
  772. if (WIFEXITED(status)) {
  773. _exit(WEXITSTATUS(status));
  774. }
  775. _exit(WIFSIGNALED(status) ? 128 + WTERMSIG(status) : 1);
  776. }
  777. /* Child side: drop the stub's socketpair end. */
  778. if (sp[0] >= 0) close(sp[0]);
  779. /* ================================================================
  780. * Inner init — PID 1 in the nested PID namespace.
  781. * ================================================================ */
  782. /* Block ptrace and /proc/1/mem writes against this process. */
  783. if (prctl(PR_SET_DUMPABLE, 0) < 0) {
  784. die("apply-seccomp: prctl(PR_SET_DUMPABLE)");
  785. }
  786. /* Don't let our /proc mount propagate anywhere. */
  787. if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) < 0) {
  788. die("apply-seccomp: mount(MS_PRIVATE)");
  789. }
  790. /* EPERM here means a masked /proc is underneath (unprivileged Docker)
  791. * and the kernel domination check refused the overmount. The nested
  792. * userns above is the isolation boundary; this remount only hides
  793. * outer PIDs from `ls /proc`. enableWeakerNestedSandbox targets
  794. * exactly this environment. */
  795. if (mount("proc", "/proc", "proc", MS_NOSUID | MS_NODEV | MS_NOEXEC, NULL) < 0
  796. && errno != EPERM) {
  797. die("apply-seccomp: mount(/proc)");
  798. }
  799. /* bwrap --cap-add places CAP_SYS_ADMIN in the ambient set so it survives
  800. * exec. Clear it now that the mount is done; combined with
  801. * PR_SET_NO_NEW_PRIVS, the worker's execve drops to zero capabilities. */
  802. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) < 0) {
  803. die("apply-seccomp: prctl(PR_CAP_AMBIENT_CLEAR_ALL)");
  804. }
  805. /* Fork the real workload so PID 1 can stay as a non-dumpable reaper. */
  806. pid_t worker = fork();
  807. if (worker < 0) {
  808. die("apply-seccomp: fork(worker)");
  809. }
  810. if (worker > 0) {
  811. /* Inner init: reap everything, exit with the worker's status.
  812. * When PID 1 exits the kernel tears down the whole namespace.
  813. * PID 1 drops signals without handlers, so install forwarders. */
  814. if (sp[1] >= 0) close(sp[1]);
  815. install_forwarders(worker);
  816. _exit(reap_until(worker));
  817. }
  818. /* ---- Worker (inner PID 2): apply seccomp and exec. ---- */
  819. unsetenv("SRT_OBSERVE_SOCK");
  820. unsetenv("SRT_ENCODED_CMD");
  821. drop_all_capabilities();
  822. if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
  823. die("apply-seccomp: prctl(PR_SET_NO_NEW_PRIVS)");
  824. }
  825. /* Best-effort: install the USER_NOTIF observation filter and hand its
  826. * listener fd to the outer stub over the pre-fork socketpair. Runs after
  827. * NO_NEW_PRIVS (required) and before the unix-block filter / exec so only
  828. * the workload is observed. */
  829. install_observe_filter(sp[1]);
  830. if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog) < 0) {
  831. die("apply-seccomp: prctl(PR_SET_SECCOMP)");
  832. }
  833. execvp(command_argv[0], command_argv);
  834. die("apply-seccomp: execvp");
  835. return 1;
  836. }