@amritk/nish-aarch64-linux 0.38.0 → 0.40.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/INSTALL.md +74 -129
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +455 -65
  4. package/package.json +1 -1
  5. package/runtime/core/host.d.ts +11 -0
  6. package/runtime/core/host.mjs +35 -0
  7. package/runtime/nish.d.ts +320 -33
  8. package/runtime/nish.h +84 -10
  9. package/runtime/nish.mjs +69 -6
  10. package/runtime/node.mjs +117 -0
  11. package/runtime/page-frame.d.ts +123 -0
  12. package/runtime/page-frame.mjs +736 -0
  13. package/runtime/page-game.d.ts +132 -0
  14. package/runtime/page-game.mjs +738 -0
  15. package/runtime/runtime-aes.c +97 -12
  16. package/runtime/runtime-async.c +43 -10
  17. package/runtime/runtime-bytes.c +88 -4
  18. package/runtime/runtime-checksum.c +207 -15
  19. package/runtime/runtime-net.c +64 -3
  20. package/runtime/runtime-os.c +174 -27
  21. package/runtime/runtime-region.c +94 -10
  22. package/runtime/runtime-sandbox.c +404 -17
  23. package/runtime/runtime-sha256.c +11 -4
  24. package/runtime/runtime-wasm.c +437 -0
  25. package/runtime/runtime.c +5 -0
  26. package/runtime/vite.mjs +1 -1
  27. package/scripts/build.sh +42 -8
  28. package/std/README.md +78 -91
  29. package/std/array.ts +36 -3
  30. package/std/collections.ts +51 -0
  31. package/std/compress/checksum.ts +13 -0
  32. package/std/compress/deflate.ts +0 -2
  33. package/std/crypto/hmac.ts +37 -10
  34. package/std/crypto/p256.ts +1629 -2732
  35. package/std/crypto/p384.ts +3 -1
  36. package/std/crypto/pki.ts +151 -13
  37. package/std/crypto/sha256.ts +34 -6
  38. package/std/crypto/x25519.ts +153 -64
  39. package/std/crypto/x509.ts +120 -10
  40. package/std/host/game.ts +273 -0
  41. package/std/input.ts +56 -0
  42. package/std/json-tokenizer.ts +344 -111
  43. package/std/json-typed.ts +256 -12
  44. package/std/json-value.ts +144 -3
  45. package/std/json.ts +63 -8
  46. package/std/net/fetch.ts +22 -4
  47. package/std/net/handler.ts +130 -16
  48. package/std/net/http-server.ts +3382 -0
  49. package/std/net/http1-client-codec.ts +6 -2
  50. package/std/net/http1-codec.ts +636 -162
  51. package/std/net/http1-server.ts +569 -42
  52. package/std/net/http2-cleartext.ts +526 -0
  53. package/std/net/http2-tls.ts +48 -0
  54. package/std/net/http2.ts +131 -14
  55. package/std/net/http3-server.ts +29 -3
  56. package/std/net/http3.ts +180 -7
  57. package/std/net/postgres-async.ts +1304 -86
  58. package/std/net/postgres-carrier.ts +343 -10
  59. package/std/net/postgres.ts +122 -7
  60. package/std/net/prefork.ts +195 -11
  61. package/std/net/quic-datagram.ts +30 -0
  62. package/std/net/quic-listener.ts +38 -12
  63. package/std/net/quic-packet.ts +19 -6
  64. package/std/net/quic-recovery.ts +373 -27
  65. package/std/net/quic-stream.ts +195 -37
  66. package/std/net/quic.ts +516 -22
  67. package/std/net/router.ts +407 -38
  68. package/std/net/serve.ts +1022 -110
  69. package/std/net/tls/codec.ts +110 -32
  70. package/std/net/tls/record-server.ts +37 -7
  71. package/std/net/tls/verify.ts +19 -1
  72. package/std/net/tls-tcp.ts +56 -1
  73. package/std/net/tls.ts +196 -50
  74. package/std/net/url.ts +83 -35
  75. package/std/net/websocket.ts +129 -19
  76. package/std/net/webtransport.ts +185 -1
  77. package/std/raster.ts +837 -0
  78. package/std/regex.ts +69 -47
  79. package/std/region.ts +62 -11
  80. package/std/release.ts +593 -0
  81. package/std/secret.ts +26 -59
  82. package/std/synth.ts +143 -0
  83. package/std/text.ts +233 -0
  84. package/std/threads.ts +298 -0
  85. package/std/yaml-json.ts +368 -28
  86. package/std/yaml.ts +122 -27
@@ -61,7 +61,22 @@
61
61
  * freeing them, then retires the handle as `free` does: `awaitAll` runs each
62
62
  * call that waits in a region of its own, and adopts it when the call
63
63
  * finishes, so the answer stays readable and is freed with the caller's
64
- * memory (docs/security/async.md, ASYNC-14). */
64
+ * memory (docs/security/async.md, ASYNC-14). A child region, or a region with
65
+ * children, is never a lane's, and adopting one panics: its chunks would
66
+ * outlive the tree `free` walks (ASYNC-19).
67
+ *
68
+ * **Children.** `nish_region_child_new` makes a region whose parent is the
69
+ * region entered last on this thread (`child` and `childWith`), and panics
70
+ * when none is. A slot links its parent and its children through slot indices
71
+ * (index + 1, 0 for none): a parent, its first child, and the previous and
72
+ * next sibling, four 32-bit links, so a slot is 96 bytes (80 before
73
+ * children). Making a child, and unlinking one as `free` does, are O(1);
74
+ * `free` of a parent first walks its whole subtree, once, to panic before
75
+ * freeing anything if any region in it is entered, then frees it deepest
76
+ * first -- each region's chunks and then its handle, so every copy of a
77
+ * child's handle is stale afterwards, as the parent's is -- O(1) a region. A
78
+ * child is always on its parent's thread, and the links are only read and
79
+ * written by that thread, so they take no lock. */
65
80
 
66
81
  #include <stddef.h>
67
82
  #include <stdint.h>
@@ -102,7 +117,12 @@ typedef struct nish_region_slot {
102
117
  uint64_t outer; /* while entered: the handle entered before it; while free: the next free slot + 1 */
103
118
  void *root; /* what `leave` recorded, answered by `enter` */
104
119
  uint64_t entered;
120
+ uint32_t parent; /* the parent's index + 1, or 0: a region `nish_region_new` made */
121
+ uint32_t first_child; /* the newest child's index + 1, or 0 */
122
+ uint32_t prev_sibling; /* the parent's next newer child's index + 1, or 0 */
123
+ uint32_t next_sibling; /* the parent's next older child's index + 1, or 0 */
105
124
  } nish_region_slot;
125
+ _Static_assert(sizeof(nish_region_slot) == 96, "the slot size the header states");
106
126
 
107
127
  static nish_region_slot *nish_region_pages[NISH_REGION_SLOTS / NISH_REGION_PAGE];
108
128
  static uint64_t nish_region_used; /* slots ever handed out: the next never-used index */
@@ -143,6 +163,8 @@ enum {
143
163
  NISH_REGION_LEAVE,
144
164
  NISH_REGION_FULL,
145
165
  NISH_REGION_OOM,
166
+ NISH_REGION_NO_PARENT,
167
+ NISH_REGION_ADOPT_TREE,
146
168
  };
147
169
  #define NISH_REGION_MSG(text) { sizeof text - 1, text }
148
170
  static const struct { uint64_t len; char data[72]; } nish_region_messages[] = {
@@ -154,6 +176,8 @@ static const struct { uint64_t len; char data[72]; } nish_region_messages[] = {
154
176
  NISH_REGION_MSG("nish: leave of a region that is not the one entered last"),
155
177
  NISH_REGION_MSG("nish: more than 16777216 live regions"),
156
178
  NISH_REGION_MSG("nish: out of memory"),
179
+ NISH_REGION_MSG("nish: a child region made with no region entered"),
180
+ NISH_REGION_MSG("nish: adopt of a region with a parent or children"),
157
181
  };
158
182
  static NISH_COLD void nish_region_die(int why) {
159
183
  nish_panic((const nish_str *)&nish_region_messages[why]);
@@ -173,6 +197,12 @@ static nish_region_slot *nish_region_slot_of(uint64_t r) {
173
197
  return s;
174
198
  }
175
199
 
200
+ /* The slot whose index + 1 is `link`, which is not 0. */
201
+ static nish_region_slot *nish_region_at(uint32_t link) {
202
+ uint64_t index = (uint64_t)link - 1;
203
+ return &nish_region_pages[index / NISH_REGION_PAGE][index % NISH_REGION_PAGE];
204
+ }
205
+
176
206
  /* Swap the slot's arena and chunk size with the thread's: `enter` and `leave`
177
207
  both, and `free` around its `nish_free_arena`. */
178
208
  static void nish_region_swap(nish_region_slot *s) {
@@ -219,12 +249,30 @@ uint64_t nish_region_new(void) {
219
249
  }
220
250
  s->chunk = 8;
221
251
  s->outer = 0;
252
+ s->parent = 0;
253
+ s->first_child = 0;
254
+ s->prev_sibling = 0;
255
+ s->next_sibling = 0;
222
256
  __atomic_store_n(&s->thread, me, __ATOMIC_RELAXED);
223
257
  uint64_t r = s->gen << NISH_REGION_SLOT_BITS | index;
224
258
  nish_region_unlock();
225
259
  return r;
226
260
  }
227
261
 
262
+ uint64_t nish_region_child_new(void) {
263
+ uint64_t p = nish_region_current;
264
+ if (!p) nish_region_die(NISH_REGION_NO_PARENT);
265
+ nish_region_slot *parent = nish_region_slot_of(p);
266
+ uint64_t r = nish_region_new();
267
+ nish_region_slot *s = nish_region_slot_of(r);
268
+ uint32_t link = (uint32_t)(r & (NISH_REGION_SLOTS - 1)) + 1;
269
+ s->parent = (uint32_t)(p & (NISH_REGION_SLOTS - 1)) + 1;
270
+ s->next_sibling = parent->first_child;
271
+ if (parent->first_child) nish_region_at(parent->first_child)->prev_sibling = link;
272
+ parent->first_child = link;
273
+ return r;
274
+ }
275
+
228
276
  void *nish_region_enter(uint64_t r) {
229
277
  nish_region_slot *s = nish_region_slot_of(r);
230
278
  if (s->entered) nish_region_die(NISH_REGION_ENTERED);
@@ -247,9 +295,8 @@ void nish_region_leave(uint64_t r, void *root) {
247
295
  /* Give the slot back: its generation moves on, so every copy of `r` is
248
296
  stale, and the slot joins the free list unless that generation is the last.
249
297
  The slot's arena is already empty. */
250
- static void nish_region_retire(nish_region_slot *s, uint64_t r) {
298
+ static void nish_region_retire(nish_region_slot *s, uint64_t index) {
251
299
  s->root = 0;
252
- uint64_t index = r & (NISH_REGION_SLOTS - 1);
253
300
  nish_region_lock();
254
301
  __atomic_store_n(&s->thread, 0, __ATOMIC_RELAXED);
255
302
  uint64_t gen = s->gen + 1;
@@ -261,13 +308,49 @@ static void nish_region_retire(nish_region_slot *s, uint64_t r) {
261
308
  nish_region_unlock();
262
309
  }
263
310
 
311
+ /* Take the slot out of its parent's child list. */
312
+ static void nish_region_unlink(nish_region_slot *s) {
313
+ if (!s->parent) return;
314
+ if (s->prev_sibling) nish_region_at(s->prev_sibling)->next_sibling = s->next_sibling;
315
+ else nish_region_at(s->parent)->first_child = s->next_sibling;
316
+ if (s->next_sibling) nish_region_at(s->next_sibling)->prev_sibling = s->prev_sibling;
317
+ s->parent = 0;
318
+ s->prev_sibling = 0;
319
+ s->next_sibling = 0;
320
+ }
321
+
322
+ /* The region after `s` in a walk of the subtree under `top` that visits a
323
+ region before its children (first child, else next sibling, else the next
324
+ sibling of the nearest ancestor below `top` that has one), or 0 at the end. */
325
+ static nish_region_slot *nish_region_next_in(nish_region_slot *s, nish_region_slot *top) {
326
+ if (s->first_child) return nish_region_at(s->first_child);
327
+ while (s != top) {
328
+ if (s->next_sibling) return nish_region_at(s->next_sibling);
329
+ s = nish_region_at(s->parent);
330
+ }
331
+ return 0;
332
+ }
333
+
264
334
  void nish_region_free(uint64_t r) {
265
- nish_region_slot *s = nish_region_slot_of(r);
266
- if (s->entered) nish_region_die(NISH_REGION_FREE_ENTERED);
267
- nish_region_swap(s);
268
- nish_free_arena();
269
- nish_region_swap(s);
270
- nish_region_retire(s, r);
335
+ nish_region_slot *top = nish_region_slot_of(r);
336
+ /* Nothing is freed unless nothing in the tree is entered. */
337
+ for (nish_region_slot *s = top; s; s = nish_region_next_in(s, top))
338
+ if (s->entered) nish_region_die(NISH_REGION_FREE_ENTERED);
339
+ nish_region_unlink(top);
340
+ nish_region_slot *s = top;
341
+ for (;;) {
342
+ while (s->first_child) s = nish_region_at(s->first_child);
343
+ /* A leaf: free it, then go on from its parent, which may now be one. */
344
+ nish_region_slot *up = s == top ? 0 : nish_region_at(s->parent);
345
+ uint64_t index = s == top ? (r & (NISH_REGION_SLOTS - 1)) : (uint64_t)up->first_child - 1;
346
+ nish_region_unlink(s);
347
+ nish_region_swap(s);
348
+ nish_free_arena();
349
+ nish_region_swap(s);
350
+ nish_region_retire(s, index);
351
+ if (!up) return;
352
+ s = up;
353
+ }
271
354
  }
272
355
 
273
356
  /* An `awaitAll` lane's region, once the lane has finished: its chunks go on
@@ -290,6 +373,7 @@ void nish_region_free(uint64_t r) {
290
373
  void nish_region_adopt(uint64_t r) {
291
374
  nish_region_slot *s = nish_region_slot_of(r);
292
375
  if (s->entered) nish_region_die(NISH_REGION_FREE_ENTERED);
376
+ if (s->parent || s->first_child) nish_region_die(NISH_REGION_ADOPT_TREE);
293
377
  nish_chunk_link *head = s->arena.chunks;
294
378
  if (head && s->arena.off == 0) {
295
379
  /* The lane rewound its newest chunk to empty: a release to the mark it
@@ -317,5 +401,5 @@ void nish_region_adopt(uint64_t r) {
317
401
  }
318
402
  }
319
403
  s->arena = (struct nish_arena){ 0 };
320
- nish_region_retire(s, r);
404
+ nish_region_retire(s, r & (NISH_REGION_SLOTS - 1));
321
405
  }
@@ -23,6 +23,14 @@
23
23
  * `exec_paths` is the programs a dependency's `process.spawn=<program>`
24
24
  * grants name (WP40 §2a), and their interpreters, in the same shape: with
25
25
  * it, `EXECUTE` leaves the rule on `/` and each program gets a rule of its own.
26
+ * An interpreter the grants do not name themselves is written `//<path>`, the
27
+ * same file to the kernel, and is kept out of a spawn's reach (SBX-1): its
28
+ * identity is recorded before step 2, and `nish_spawn_sandboxed`, which
29
+ * runtime-os.c's spawn calls once it is set, refuses a target that is that
30
+ * file, has the child execute a descriptor of any other, and holds that
31
+ * child's whole subtree to the one exec ("One exec per spawn" below). A
32
+ * program granted `process.spawn=exec:<program>` is written `///<path>`, and
33
+ * its identity is recorded too: its child is spared the one exec.
26
34
  *
27
35
  * What it does, in the order of the note's section 3, each step before the
28
36
  * next because each needs the one before it:
@@ -47,7 +55,9 @@
47
55
  * could not withhold, once, and runs. No environment variable, file or
48
56
  * argument is read that could widen any of it: step 1 reaches
49
57
  * `getenv("NISH_NUM_THREADS")` through `nish_cpu_online`, which can only
50
- * lower the pool's ceiling, and confines nothing. The one knob,
58
+ * lower the pool's ceiling, and confines nothing; a spawn reads `PATH` to
59
+ * find its program as `posix_spawnp` would, which can only refuse more. The
60
+ * one knob,
51
61
  * `-DNISH_SANDBOX_SIMULATE_ABI=<n>`, makes the ABI probe answer `n` in a
52
62
  * test-only build of this file; scripts/build.sh never passes it.
53
63
  *
@@ -62,10 +72,21 @@
62
72
 
63
73
  #include <errno.h>
64
74
  #include <fcntl.h>
75
+ #include <limits.h>
76
+ #include <poll.h>
77
+ #include <pthread.h>
78
+ #include <sched.h>
79
+ #include <signal.h>
80
+ #include <spawn.h>
65
81
  #include <stddef.h>
82
+ #include <stdio.h>
83
+ #include <stdlib.h>
66
84
  #include <string.h>
85
+ #include <sys/ioctl.h>
86
+ #include <sys/stat.h>
67
87
  #include <sys/prctl.h>
68
88
  #include <sys/syscall.h>
89
+ #include <sys/wait.h>
69
90
  #include <linux/audit.h>
70
91
  #include <linux/capability.h>
71
92
  #include <linux/filter.h>
@@ -143,7 +164,9 @@ struct nish_ll_path_beneath {
143
164
  #define NISH_SB_ARCH AUDIT_ARCH_X86_64
144
165
  static const uint16_t nish_sb_always[] = {101, 310, 311, 438}; /* ptrace, process_vm_readv/writev, pidfd_getfd */
145
166
  static const uint16_t nish_sb_net[] = {41, 53, 42, 49, 50, 43, 288}; /* socket ... accept4 */
146
- static const uint16_t nish_sb_spawn[] = {59, 322, 57, 58}; /* execve, execveat, fork, vfork */
167
+ #define NISH_SB_EXECVE 59
168
+ #define NISH_SB_EXECVEAT 322
169
+ static const uint16_t nish_sb_spawn[] = {NISH_SB_EXECVE, NISH_SB_EXECVEAT, 57, 58}; /* execve, execveat, fork, vfork */
147
170
  #define NISH_SB_CLONE 56
148
171
  static const uint16_t nish_sb_meta[] = {
149
172
  90, 91, 268, 452, /* chmod, fchmod, fchmodat, fchmodat2 */
@@ -156,7 +179,9 @@ static const uint16_t nish_sb_meta[] = {
156
179
  #define NISH_SB_ARCH AUDIT_ARCH_AARCH64
157
180
  static const uint16_t nish_sb_always[] = {117, 270, 271, 438};
158
181
  static const uint16_t nish_sb_net[] = {198, 199, 203, 200, 201, 202, 242};
159
- static const uint16_t nish_sb_spawn[] = {221, 281};
182
+ #define NISH_SB_EXECVE 221
183
+ #define NISH_SB_EXECVEAT 281
184
+ static const uint16_t nish_sb_spawn[] = {NISH_SB_EXECVE, NISH_SB_EXECVEAT};
160
185
  #define NISH_SB_CLONE 220
161
186
  static const uint16_t nish_sb_meta[] = {
162
187
  52, 53, 452, /* fchmod, fchmodat, fchmodat2 */
@@ -385,25 +410,33 @@ static int nish_sb_rows(struct sock_filter *prog, int at, const uint16_t *nrs, i
385
410
  #define NISH_SB_ARG0_LOW offsetof(struct seccomp_data, args)
386
411
  #endif
387
412
 
388
- /* Step 5: a denylist (open question 4), each row of the note's section 4.
389
- * The arch check comes first and kills on a mismatch, so a 32-bit entry
390
- * cannot step around the 64-bit numbers; on x86-64 the next instruction
391
- * kills any number with bit 30 set, since an x32 call reports
392
- * AUDIT_ARCH_X86_64 and would match none of them. */
413
+ /* How every filter here starts, leaving the syscall number loaded. The arch
414
+ * check comes first and kills on a mismatch, so a 32-bit entry cannot step
415
+ * around the 64-bit numbers; on x86-64 the next instruction kills any number
416
+ * with bit 30 set, since an x32 call reports AUDIT_ARCH_X86_64 and would
417
+ * match none of them. */
418
+ #if defined(__x86_64__)
419
+ #define NISH_SB_X32 \
420
+ , BPF_JUMP(BPF_JMP | BPF_JSET | BPF_K, 0x40000000, 0, 1), \
421
+ BPF_STMT(BPF_RET | BPF_K, KILL)
422
+ #else
423
+ #define NISH_SB_X32
424
+ #endif
425
+ #define NISH_SB_HEAD \
426
+ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, arch)), \
427
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, NISH_SB_ARCH, 1, 0), \
428
+ BPF_STMT(BPF_RET | BPF_K, KILL), \
429
+ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)) NISH_SB_X32
430
+
431
+ /* Step 5: a denylist (open question 4), each row of the note's section 4. */
393
432
  static void nish_sb_seccomp(int32_t caps) {
394
433
  uint32_t action = SECCOMP_RET_KILL_PROCESS;
395
434
  if (syscall(SYS_seccomp, SECCOMP_GET_ACTION_AVAIL, 0, &action) != 0)
396
435
  nish_sb_fail("this kernel has no seccomp filter that kills the process");
436
+ static const struct sock_filter head[] = {NISH_SB_HEAD};
397
437
  struct sock_filter prog[96];
398
- int at = 0;
399
- prog[at++] = (struct sock_filter)BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, arch));
400
- prog[at++] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, NISH_SB_ARCH, 1, 0);
401
- prog[at++] = (struct sock_filter)BPF_STMT(BPF_RET | BPF_K, KILL);
402
- prog[at++] = (struct sock_filter)BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr));
403
- #if defined(__x86_64__)
404
- prog[at++] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JSET | BPF_K, 0x40000000, 0, 1);
405
- prog[at++] = (struct sock_filter)BPF_STMT(BPF_RET | BPF_K, KILL);
406
- #endif
438
+ int at = sizeof head / sizeof head[0];
439
+ memcpy(prog, head, sizeof head);
407
440
  at = NISH_SB_ROWS(prog, at, nish_sb_always, KILL);
408
441
  if (!(caps & CAP_BIT_NET)) at = NISH_SB_ROWS(prog, at, nish_sb_net, KILL);
409
442
  /* io_uring opens, connects and accepts sockets without those calls. */
@@ -436,8 +469,362 @@ static void nish_sb_seccomp(int32_t caps) {
436
469
  if (loaded != 0) nish_sb_fail("cannot load the seccomp filter");
437
470
  }
438
471
 
472
+ /* SBX-1: the exec allowlist must hold each granted program's interpreter (its
473
+ * ELF loader, or its `#!` line's program), because the kernel opens that file
474
+ * for execution too, and an interpreter runs whatever it is handed. The
475
+ * compiler writes an entry that is on the list only as another entry's
476
+ * interpreter with a second leading `/` (`//lib64/ld-linux-x86-64.so.2`),
477
+ * which names the same file. Each such file's identity is kept here when the
478
+ * sandbox is applied, and `nish_sb_spawn_open` refuses a spawn target that is
479
+ * one of them, by identity, so a symlink, a hardlink or any second name is
480
+ * refused as well.
481
+ *
482
+ * A program granted `process.spawn=exec:<program>` is written with a third
483
+ * leading `/` (`///usr/bin/git`), which names the same file too, and its
484
+ * identity is kept in the same table: such a target is started without the
485
+ * one-exec filter ("One exec per spawn" below), so its subtree may execute
486
+ * whatever the allowlist holds. A file kept both ways is refused. More marked
487
+ * entries than the table holds refuse every spawn rather than some. */
488
+ #define NISH_SB_MARKED 16
489
+ static struct {
490
+ dev_t dev;
491
+ ino_t ino;
492
+ int exec; /* 1 for an `exec:` grant, 0 for a kept interpreter */
493
+ } nish_sb_marked[NISH_SB_MARKED];
494
+ static int nish_sb_nmarked;
495
+
496
+ /* The file `posix_spawnp` would execute for `file`: `file` itself when it
497
+ * holds a `/`, else the first executable regular file of that name in a PATH
498
+ * directory (an empty entry is the working directory). It is opened O_PATH and
499
+ * moved to a descriptor at or above `low` that a child inherits, and `proc`
500
+ * gets its /proc/self/fd name, so the child executes the very file checked: a
501
+ * name swapped between this check and the exec reaches nothing, and a script's
502
+ * interpreter can open the script by that name. Returns the descriptor, or
503
+ * -EACCES for a kept interpreter, or -ENOENT when there is no such file;
504
+ * `*unheld` is set when the file is an `exec:` grant's program. */
505
+ static int nish_sb_spawn_open(const char *file, int low, char *proc, int *unheld) {
506
+ const char *dir = strchr(file, '/') ? "" : getenv("PATH");
507
+ char buf[PATH_MAX];
508
+ struct stat st;
509
+ if (!dir) dir = "/bin:/usr/bin";
510
+ for (;;) {
511
+ const char *end = strchrnul(dir, ':'), *path = file;
512
+ size_t len = (size_t)(end - dir);
513
+ /* A directory too long to join with `file` holds nothing it could run. */
514
+ int fd = -1;
515
+ if (len && len + strlen(file) + 2 <= sizeof buf) {
516
+ memcpy(buf, dir, len);
517
+ buf[len] = '/';
518
+ strcpy(buf + len + 1, file);
519
+ path = buf;
520
+ }
521
+ if (!len || path == buf) fd = open(path, O_PATH | O_CLOEXEC);
522
+ if (fd >= 0 && !fstat(fd, &st) && S_ISREG(st.st_mode) && (st.st_mode & 0111)) {
523
+ int k = nish_sb_nmarked > NISH_SB_MARKED ? -1 : nish_sb_nmarked, held = k < 0;
524
+ while (k-- > 0)
525
+ if (nish_sb_marked[k].dev == st.st_dev && nish_sb_marked[k].ino == st.st_ino) {
526
+ if (nish_sb_marked[k].exec) *unheld = 1;
527
+ else held = 1;
528
+ }
529
+ int moved = held ? -EACCES : fcntl(fd, F_DUPFD, low);
530
+ if (moved == -1) moved = -errno;
531
+ close(fd);
532
+ if (moved >= 0) snprintf(proc, 32, "/proc/self/fd/%d", moved);
533
+ return moved;
534
+ }
535
+ if (fd >= 0) close(fd);
536
+ if (!*end) return -ENOENT;
537
+ dir = end + 1;
538
+ }
539
+ }
540
+
541
+ /* One exec per spawn (SBX-1, docs/wp37-os-sandbox.md section 2a "One exec
542
+ * per spawn"). Landlock grants EXECUTE on a kept interpreter to the whole
543
+ * process tree, since the kernel needs it to start a granted program, so a
544
+ * granted program that executes a path from its arguments (`find -exec`,
545
+ * `env`) could run the interpreter, and through it any file. Under an exec
546
+ * allowlist every spawn therefore runs on two threads of its own:
547
+ *
548
+ * - the supervisor leaves the process's descriptor table for a private copy
549
+ * (`unshare(CLONE_FILES)`), so that no other thread can close or replace
550
+ * a descriptor between the identity check and the exec, opens and checks
551
+ * the target there, and starts the spawner;
552
+ * - the spawner takes a seccomp filter that sends `execve` and `execveat`
553
+ * to a user-notification listener and calls `posix_spawn`, so the child
554
+ * inherits the filter. A filter cannot be removed, which is why it is a
555
+ * thread that ends with the spawn and not the calling thread.
556
+ *
557
+ * Both threads run with every signal blocked, and the child is started with
558
+ * the calling thread's mask (`POSIX_SPAWN_SETSIGMASK`): a handler run on
559
+ * either would write its wake pipe by number, and in the private table that
560
+ * number can be the listener or the spawn's own pipe.
561
+ *
562
+ * The supervisor answers the first notification, the child's own exec, with
563
+ * "continue" and closes the listener; the kernel then answers every later
564
+ * exec in that child's subtree ENOSYS, for good. The same filter refuses a
565
+ * second listener (EBUSY): the kernel lets the newest filter's "continue"
566
+ * stand for all of them, so a granted program with a listener of its own
567
+ * would answer its children's execs itself.
568
+ *
569
+ * The listener, the pipe and the target live in the private table only, and
570
+ * go with it when both threads end. Where the filter cannot be installed
571
+ * (EINVAL before Linux 5.0, EBUSY beneath a launcher's own listener) the
572
+ * spawn is refused in both modes; where "continue" is not known (before
573
+ * 5.5) the supervisor fails the child's exec instead, which refuses it too. */
574
+ #define NISH_SB_NEW_LISTENER 8u /* SECCOMP_FILTER_FLAG_NEW_LISTENER */
575
+ #define NISH_SB_USER_NOTIF 0x7fc00000u /* SECCOMP_RET_USER_NOTIF */
576
+ /* struct seccomp_notif and seccomp_notif_resp, spelled here like Landlock's
577
+ * numbers: headers older than Linux 5.0 lack them. */
578
+ struct nish_sb_notif {
579
+ uint64_t id;
580
+ uint32_t pid, flags;
581
+ struct seccomp_data data;
582
+ };
583
+ struct nish_sb_notif_resp {
584
+ uint64_t id;
585
+ int64_t val;
586
+ int32_t error;
587
+ uint32_t flags; /* 1 is SECCOMP_USER_NOTIF_FLAG_CONTINUE */
588
+ };
589
+ #define NISH_SB_NOTIF_RECV _IOWR('!', 0, struct nish_sb_notif)
590
+ #define NISH_SB_NOTIF_SEND _IOWR('!', 1, struct nish_sb_notif_resp)
591
+
592
+ extern char **environ;
593
+
594
+ struct nish_sb_job {
595
+ const char *file;
596
+ const int *dup; /* the `n` descriptors the actions read, or null */
597
+ int n;
598
+ int low;
599
+ const posix_spawn_file_actions_t *actions;
600
+ char **argv;
601
+ char proc[32];
602
+ int unheld; /* the target is an `exec:` grant's program: no filter */
603
+ int pipe[2]; /* the spawner's two answers: its listener, then its child */
604
+ sigset_t mask; /* the calling thread's, which the child starts with */
605
+ int32_t result;
606
+ };
607
+
608
+ /* `fd` moved to a close-on-exec descriptor at or above `low`, or -1 with
609
+ * errno. No descriptor this file makes for a spawn stays below `low`, where
610
+ * the child's file actions and this process's 0, 1 and 2 are. */
611
+ static int nish_sb_lift(int fd, int low) {
612
+ int moved = fcntl(fd, F_DUPFD_CLOEXEC, low), e = errno;
613
+ close(fd);
614
+ errno = e;
615
+ return moved;
616
+ }
617
+
618
+ /* `posix_spawn` of the checked target, its child started with the caller's
619
+ * mask: the pid, or a negative errno. This thread blocks every signal, and a
620
+ * child starts with its parent's mask unless it is given one. */
621
+ static int32_t nish_sb_start(struct nish_sb_job *job) {
622
+ pid_t pid;
623
+ posix_spawnattr_t attr;
624
+ int failed = posix_spawnattr_init(&attr);
625
+ if (!failed) {
626
+ posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGMASK);
627
+ posix_spawnattr_setsigmask(&attr, &job->mask);
628
+ failed = posix_spawn(&pid, job->proc, job->actions, &attr, job->argv, environ);
629
+ posix_spawnattr_destroy(&attr);
630
+ }
631
+ return failed ? -failed : (int32_t)pid;
632
+ }
633
+
634
+ static void nish_sb_refuse_spawn(int e) {
635
+ char buf[24];
636
+ nish_sb_say("cannot hold a spawned program to one exec, so the spawn is refused", 0, nish_sb_errno_name(e, buf));
637
+ }
638
+
639
+ /* The answers are written through the pipe rather than left in the job, so
640
+ * that the supervisor wakes for the second whether or not the child ever
641
+ * reached its exec: a child that dies in a redirect notifies nobody. */
642
+ static void *nish_sb_spawner(void *arg) {
643
+ struct nish_sb_job *job = arg;
644
+ static const struct sock_filter prog[] = {
645
+ NISH_SB_HEAD,
646
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, NISH_SB_EXECVE, 6, 0),
647
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, NISH_SB_EXECVEAT, 5, 0),
648
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_seccomp, 0, 3),
649
+ /* `seccomp`'s flags are its second argument. */
650
+ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, NISH_SB_ARG0_LOW + 8),
651
+ BPF_JUMP(BPF_JMP | BPF_JSET | BPF_K, NISH_SB_NEW_LISTENER, 0, 1),
652
+ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | EBUSY),
653
+ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
654
+ BPF_STMT(BPF_RET | BPF_K, NISH_SB_USER_NOTIF),
655
+ };
656
+ struct sock_fprog fprog = {sizeof prog / sizeof prog[0], (struct sock_filter *)prog};
657
+ int32_t said = (int32_t)syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, NISH_SB_NEW_LISTENER, &fprog);
658
+ /* The kernel gave the listener the lowest free number, which may be one
659
+ * the child's actions write, or this process's closed stderr. */
660
+ if (said >= 0) said = nish_sb_lift(said, job->low);
661
+ if (said < 0) said = -errno;
662
+ (void)!write(job->pipe[1], &said, sizeof said);
663
+ if (said < 0) return 0;
664
+ said = nish_sb_start(job);
665
+ (void)!write(job->pipe[1], &said, sizeof said);
666
+ return 0;
667
+ }
668
+
669
+ /* The spawner's next answer. An interrupted read is restarted: giving up
670
+ * there would lose a child that is already running. */
671
+ static int32_t nish_sb_answer(int fd) {
672
+ int32_t said;
673
+ ssize_t n;
674
+ while ((n = read(fd, &said, sizeof said)) < 0 && errno == EINTR) {}
675
+ return n == sizeof said ? said : -EIO;
676
+ }
677
+
678
+ /* The supervisor's answer to one notification. The test-only
679
+ * `-DNISH_SANDBOX_SIMULATE_NO_CONTINUE=<n>` makes the "continue" answer fail
680
+ * as it does before Linux 5.5, and for 2 the error answer after it as well;
681
+ * `scripts/build.sh` never passes it. */
682
+ static int nish_sb_reply(int listener, struct nish_sb_notif_resp *go) {
683
+ #ifdef NISH_SANDBOX_SIMULATE_NO_CONTINUE
684
+ if (go->flags || NISH_SANDBOX_SIMULATE_NO_CONTINUE > 1) {
685
+ errno = EINVAL;
686
+ return -1;
687
+ }
688
+ #endif
689
+ return ioctl(listener, NISH_SB_NOTIF_SEND, go);
690
+ }
691
+
692
+ static void *nish_sb_supervisor(void *arg) {
693
+ struct nish_sb_job *job = arg;
694
+ pthread_t spawner;
695
+ int made[2];
696
+ if (unshare(CLONE_FILES)) {
697
+ nish_sb_refuse_spawn(errno);
698
+ return 0;
699
+ }
700
+ /* The actions name their sources by number, and this table is now nobody
701
+ * else's. A source that is open here is the caller's, so no descriptor made
702
+ * below can take its number; one that is not would name whatever was made
703
+ * there, so the spawn is refused before anything is. */
704
+ for (int k = 0; job->dup && k < job->n; k++) {
705
+ if (fcntl(job->dup[k], F_GETFD) < 0) {
706
+ job->result = -EBADF;
707
+ return 0;
708
+ }
709
+ }
710
+ if (pipe2(made, O_CLOEXEC)) {
711
+ nish_sb_refuse_spawn(errno);
712
+ return 0;
713
+ }
714
+ /* Both ends are moved before either is tested, so that the line below is
715
+ * never written to an end still sitting on descriptor 2. */
716
+ job->pipe[0] = nish_sb_lift(made[0], job->low);
717
+ job->pipe[1] = nish_sb_lift(made[1], job->low);
718
+ if (job->pipe[0] < 0 || job->pipe[1] < 0) {
719
+ nish_sb_refuse_spawn(EMFILE);
720
+ return 0;
721
+ }
722
+ int fd = nish_sb_spawn_open(job->file, job->low, job->proc, &job->unheld);
723
+ if (fd < 0) {
724
+ job->result = fd;
725
+ return 0;
726
+ }
727
+ /* An `exec:` grant's program keeps its subtree's reach of the allowlist:
728
+ * it starts from this private table like any other, without the filter. */
729
+ if (job->unheld) {
730
+ job->result = nish_sb_start(job);
731
+ return 0;
732
+ }
733
+ int failed = pthread_create(&spawner, 0, nish_sb_spawner, job);
734
+ if (failed) {
735
+ nish_sb_refuse_spawn(failed);
736
+ return 0;
737
+ }
738
+ int32_t listener = nish_sb_answer(job->pipe[0]);
739
+ if (listener < 0) {
740
+ nish_sb_refuse_spawn(-listener);
741
+ job->result = listener;
742
+ } else {
743
+ struct pollfd fds[2] = {{listener, POLLIN, 0}, {job->pipe[0], POLLIN, 0}};
744
+ struct nish_sb_notif_resp go = {0, 0, 0, 1};
745
+ pid_t killed = 0;
746
+ /* Until the spawner answers: a child that never reaches its exec notifies
747
+ * nobody, and one whose exec a signal restarted notifies again. */
748
+ for (;;) {
749
+ struct nish_sb_notif exec;
750
+ while (poll(fds, 2, -1) < 0) {}
751
+ if (!(fds[0].revents & POLLIN)) break;
752
+ memset(&exec, 0, sizeof exec);
753
+ /* The child holds the listener too until its exec commits, so closing
754
+ * this copy releases nothing: a notification that is neither answered
755
+ * nor gone (ENOENT: the child was killed, or its exec restarted) would
756
+ * leave the child in its exec and the spawner in its `vfork` for good.
757
+ * Each one is therefore read again, answered, or its child killed. */
758
+ if (ioctl(listener, NISH_SB_NOTIF_RECV, &exec)) continue;
759
+ go.id = exec.id;
760
+ if (!nish_sb_reply(listener, &go)) break;
761
+ if (errno == ENOENT) continue;
762
+ /* "Continue" is not known here (EINVAL before Linux 5.5), and failing
763
+ * the exec needs no such flag. */
764
+ nish_sb_refuse_spawn(errno);
765
+ go.flags = 0;
766
+ go.error = -ENOSYS;
767
+ if (!nish_sb_reply(listener, &go)) break;
768
+ if (errno == ENOENT) continue;
769
+ killed = (pid_t)exec.pid;
770
+ kill(killed, SIGKILL);
771
+ break;
772
+ }
773
+ /* From here every exec in the child's subtree is ENOSYS. */
774
+ close(listener);
775
+ job->result = nish_sb_answer(job->pipe[0]);
776
+ /* `posix_spawn` reports a child killed before its exec as started. */
777
+ if (killed && job->result > 0) {
778
+ while (waitpid(job->result, 0, 0) < 0 && errno == EINTR) {}
779
+ job->result = -ECHILD;
780
+ }
781
+ }
782
+ pthread_join(spawner, 0);
783
+ return 0;
784
+ }
785
+
786
+ /* `nish_spawn_start`'s spawn under an exec allowlist: the child's pid, or a
787
+ * negative errno. `actions` is its `posix_spawn_file_actions_t`, whose `dup2`
788
+ * actions read the `n` descriptors of `dup` (null for none) and write `base`
789
+ * onward; the actions write nothing above `base + n + 2`. */
790
+ static int32_t nish_sb_spawn_once(const char *file, const int *dup, int base, int n, const void *actions, char **argv) {
791
+ struct nish_sb_job job = {
792
+ .file = file, .dup = dup, .n = n, .low = base + n + 3, .actions = actions, .argv = argv, .result = -EAGAIN};
793
+ pthread_t supervisor;
794
+ sigset_t all;
795
+ /* Both threads start with every signal blocked, so the program's handlers
796
+ * never run on them: a handler names its descriptors by number
797
+ * (`signalFd`'s pipe), and in the private table that number is nothing, or
798
+ * one of this spawn's own. A signal sent to the process is delivered to a
799
+ * thread that takes it. */
800
+ sigfillset(&all);
801
+ pthread_sigmask(SIG_SETMASK, &all, &job.mask);
802
+ int failed = pthread_create(&supervisor, 0, nish_sb_supervisor, &job);
803
+ pthread_sigmask(SIG_SETMASK, &job.mask, 0);
804
+ if (failed) {
805
+ nish_sb_refuse_spawn(failed);
806
+ return -EAGAIN;
807
+ }
808
+ pthread_join(supervisor, 0);
809
+ return job.result;
810
+ }
811
+
812
+ static void nish_sb_keep_marks(const char *paths) {
813
+ struct stat st;
814
+ if (paths) nish_spawn_sandboxed = nish_sb_spawn_once;
815
+ for (; paths && *paths; paths += strlen(paths) + 1) {
816
+ /* An entry gone since the build has no identity to keep, and Landlock
817
+ * grants it nothing to execute either. */
818
+ if (paths[1] != '/' || stat(paths, &st)) continue;
819
+ int n = nish_sb_nmarked++;
820
+ if (n < NISH_SB_MARKED)
821
+ nish_sb_marked[n].dev = st.st_dev, nish_sb_marked[n].ino = st.st_ino, nish_sb_marked[n].exec = paths[2] == '/';
822
+ }
823
+ }
824
+
439
825
  void nish_sandbox(int32_t caps, int32_t mode, const char *read_dirs, const char *write_dirs, const char *exec_paths) {
440
826
  nish_cpu_prime();
827
+ nish_sb_keep_marks(exec_paths);
441
828
  if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) nish_sb_fail("cannot set no_new_privs");
442
829
  nish_sb_drop_capabilities();
443
830
  nish_sb_landlock(caps, mode, read_dirs, write_dirs, exec_paths);