@amritk/nish-aarch64-linux 0.38.0 → 0.39.0

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 (58) hide show
  1. package/bin/nish +0 -0
  2. package/docs/AI.md +348 -37
  3. package/package.json +1 -1
  4. package/runtime/core/host.d.ts +11 -0
  5. package/runtime/core/host.mjs +35 -0
  6. package/runtime/nish.d.ts +301 -18
  7. package/runtime/nish.h +74 -10
  8. package/runtime/nish.mjs +69 -6
  9. package/runtime/node.mjs +117 -0
  10. package/runtime/runtime-aes.c +12 -4
  11. package/runtime/runtime-async.c +43 -10
  12. package/runtime/runtime-checksum.c +207 -15
  13. package/runtime/runtime-net.c +32 -3
  14. package/runtime/runtime-os.c +174 -27
  15. package/runtime/runtime-region.c +94 -10
  16. package/runtime/runtime-sandbox.c +377 -17
  17. package/runtime/runtime-sha256.c +11 -4
  18. package/runtime/runtime-wasm.c +15 -0
  19. package/runtime/runtime.c +5 -0
  20. package/scripts/build.sh +27 -8
  21. package/std/README.md +5 -4
  22. package/std/compress/checksum.ts +13 -0
  23. package/std/compress/deflate.ts +0 -2
  24. package/std/crypto/p256.ts +247 -74
  25. package/std/crypto/p384.ts +3 -1
  26. package/std/crypto/pki.ts +35 -9
  27. package/std/crypto/x25519.ts +153 -64
  28. package/std/crypto/x509.ts +113 -10
  29. package/std/json-tokenizer.ts +20 -0
  30. package/std/json-typed.ts +217 -8
  31. package/std/net/handler.ts +130 -16
  32. package/std/net/http1-codec.ts +499 -150
  33. package/std/net/http1-server.ts +495 -22
  34. package/std/net/http2-cleartext.ts +526 -0
  35. package/std/net/http2-tls.ts +48 -0
  36. package/std/net/http2.ts +84 -0
  37. package/std/net/postgres-async.ts +1304 -86
  38. package/std/net/postgres-carrier.ts +343 -10
  39. package/std/net/postgres.ts +122 -7
  40. package/std/net/prefork.ts +195 -11
  41. package/std/net/quic-datagram.ts +30 -0
  42. package/std/net/quic-listener.ts +38 -12
  43. package/std/net/quic-packet.ts +19 -6
  44. package/std/net/quic-recovery.ts +134 -19
  45. package/std/net/quic-stream.ts +174 -36
  46. package/std/net/quic.ts +418 -18
  47. package/std/net/router.ts +39 -17
  48. package/std/net/serve.ts +162 -58
  49. package/std/net/tls/codec.ts +110 -32
  50. package/std/net/tls/record-server.ts +37 -7
  51. package/std/net/tls-tcp.ts +56 -1
  52. package/std/net/tls.ts +196 -50
  53. package/std/net/websocket.ts +55 -18
  54. package/std/net/webtransport.ts +179 -1
  55. package/std/regex.ts +69 -47
  56. package/std/region.ts +62 -11
  57. package/std/secret.ts +26 -59
  58. package/std/text.ts +233 -0
@@ -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,12 @@
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).
26
32
  *
27
33
  * What it does, in the order of the note's section 3, each step before the
28
34
  * next because each needs the one before it:
@@ -47,7 +53,9 @@
47
53
  * could not withhold, once, and runs. No environment variable, file or
48
54
  * argument is read that could widen any of it: step 1 reaches
49
55
  * `getenv("NISH_NUM_THREADS")` through `nish_cpu_online`, which can only
50
- * lower the pool's ceiling, and confines nothing. The one knob,
56
+ * lower the pool's ceiling, and confines nothing; a spawn reads `PATH` to
57
+ * find its program as `posix_spawnp` would, which can only refuse more. The
58
+ * one knob,
51
59
  * `-DNISH_SANDBOX_SIMULATE_ABI=<n>`, makes the ABI probe answer `n` in a
52
60
  * test-only build of this file; scripts/build.sh never passes it.
53
61
  *
@@ -62,10 +70,21 @@
62
70
 
63
71
  #include <errno.h>
64
72
  #include <fcntl.h>
73
+ #include <limits.h>
74
+ #include <poll.h>
75
+ #include <pthread.h>
76
+ #include <sched.h>
77
+ #include <signal.h>
78
+ #include <spawn.h>
65
79
  #include <stddef.h>
80
+ #include <stdio.h>
81
+ #include <stdlib.h>
66
82
  #include <string.h>
83
+ #include <sys/ioctl.h>
84
+ #include <sys/stat.h>
67
85
  #include <sys/prctl.h>
68
86
  #include <sys/syscall.h>
87
+ #include <sys/wait.h>
69
88
  #include <linux/audit.h>
70
89
  #include <linux/capability.h>
71
90
  #include <linux/filter.h>
@@ -143,7 +162,9 @@ struct nish_ll_path_beneath {
143
162
  #define NISH_SB_ARCH AUDIT_ARCH_X86_64
144
163
  static const uint16_t nish_sb_always[] = {101, 310, 311, 438}; /* ptrace, process_vm_readv/writev, pidfd_getfd */
145
164
  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 */
165
+ #define NISH_SB_EXECVE 59
166
+ #define NISH_SB_EXECVEAT 322
167
+ static const uint16_t nish_sb_spawn[] = {NISH_SB_EXECVE, NISH_SB_EXECVEAT, 57, 58}; /* execve, execveat, fork, vfork */
147
168
  #define NISH_SB_CLONE 56
148
169
  static const uint16_t nish_sb_meta[] = {
149
170
  90, 91, 268, 452, /* chmod, fchmod, fchmodat, fchmodat2 */
@@ -156,7 +177,9 @@ static const uint16_t nish_sb_meta[] = {
156
177
  #define NISH_SB_ARCH AUDIT_ARCH_AARCH64
157
178
  static const uint16_t nish_sb_always[] = {117, 270, 271, 438};
158
179
  static const uint16_t nish_sb_net[] = {198, 199, 203, 200, 201, 202, 242};
159
- static const uint16_t nish_sb_spawn[] = {221, 281};
180
+ #define NISH_SB_EXECVE 221
181
+ #define NISH_SB_EXECVEAT 281
182
+ static const uint16_t nish_sb_spawn[] = {NISH_SB_EXECVE, NISH_SB_EXECVEAT};
160
183
  #define NISH_SB_CLONE 220
161
184
  static const uint16_t nish_sb_meta[] = {
162
185
  52, 53, 452, /* fchmod, fchmodat, fchmodat2 */
@@ -385,25 +408,33 @@ static int nish_sb_rows(struct sock_filter *prog, int at, const uint16_t *nrs, i
385
408
  #define NISH_SB_ARG0_LOW offsetof(struct seccomp_data, args)
386
409
  #endif
387
410
 
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. */
411
+ /* How every filter here starts, leaving the syscall number loaded. The arch
412
+ * check comes first and kills on a mismatch, so a 32-bit entry cannot step
413
+ * around the 64-bit numbers; on x86-64 the next instruction kills any number
414
+ * with bit 30 set, since an x32 call reports AUDIT_ARCH_X86_64 and would
415
+ * match none of them. */
416
+ #if defined(__x86_64__)
417
+ #define NISH_SB_X32 \
418
+ , BPF_JUMP(BPF_JMP | BPF_JSET | BPF_K, 0x40000000, 0, 1), \
419
+ BPF_STMT(BPF_RET | BPF_K, KILL)
420
+ #else
421
+ #define NISH_SB_X32
422
+ #endif
423
+ #define NISH_SB_HEAD \
424
+ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, arch)), \
425
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, NISH_SB_ARCH, 1, 0), \
426
+ BPF_STMT(BPF_RET | BPF_K, KILL), \
427
+ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)) NISH_SB_X32
428
+
429
+ /* Step 5: a denylist (open question 4), each row of the note's section 4. */
393
430
  static void nish_sb_seccomp(int32_t caps) {
394
431
  uint32_t action = SECCOMP_RET_KILL_PROCESS;
395
432
  if (syscall(SYS_seccomp, SECCOMP_GET_ACTION_AVAIL, 0, &action) != 0)
396
433
  nish_sb_fail("this kernel has no seccomp filter that kills the process");
434
+ static const struct sock_filter head[] = {NISH_SB_HEAD};
397
435
  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
436
+ int at = sizeof head / sizeof head[0];
437
+ memcpy(prog, head, sizeof head);
407
438
  at = NISH_SB_ROWS(prog, at, nish_sb_always, KILL);
408
439
  if (!(caps & CAP_BIT_NET)) at = NISH_SB_ROWS(prog, at, nish_sb_net, KILL);
409
440
  /* io_uring opens, connects and accepts sockets without those calls. */
@@ -436,8 +467,337 @@ static void nish_sb_seccomp(int32_t caps) {
436
467
  if (loaded != 0) nish_sb_fail("cannot load the seccomp filter");
437
468
  }
438
469
 
470
+ /* SBX-1: the exec allowlist must hold each granted program's interpreter (its
471
+ * ELF loader, or its `#!` line's program), because the kernel opens that file
472
+ * for execution too, and an interpreter runs whatever it is handed. The
473
+ * compiler writes an entry that is on the list only as another entry's
474
+ * interpreter with a second leading `/` (`//lib64/ld-linux-x86-64.so.2`),
475
+ * which names the same file. Each such file's identity is kept here when the
476
+ * sandbox is applied, and `nish_sb_spawn_open` refuses a spawn target that is
477
+ * one of them, by identity, so a symlink, a hardlink or any second name is
478
+ * refused as well. More marked entries than the table holds refuse every
479
+ * spawn rather than some. */
480
+ #define NISH_SB_REFUSED 16
481
+ static struct {
482
+ dev_t dev;
483
+ ino_t ino;
484
+ } nish_sb_refused[NISH_SB_REFUSED];
485
+ static int nish_sb_nrefused;
486
+
487
+ /* The file `posix_spawnp` would execute for `file`: `file` itself when it
488
+ * holds a `/`, else the first executable regular file of that name in a PATH
489
+ * directory (an empty entry is the working directory). It is opened O_PATH and
490
+ * moved to a descriptor at or above `low` that a child inherits, and `proc`
491
+ * gets its /proc/self/fd name, so the child executes the very file checked: a
492
+ * name swapped between this check and the exec reaches nothing, and a script's
493
+ * interpreter can open the script by that name. Returns the descriptor, or
494
+ * -EACCES for a kept interpreter, or -ENOENT when there is no such file. */
495
+ static int nish_sb_spawn_open(const char *file, int low, char *proc) {
496
+ const char *dir = strchr(file, '/') ? "" : getenv("PATH");
497
+ char buf[PATH_MAX];
498
+ struct stat st;
499
+ if (!dir) dir = "/bin:/usr/bin";
500
+ for (;;) {
501
+ const char *end = strchrnul(dir, ':'), *path = file;
502
+ size_t len = (size_t)(end - dir);
503
+ /* A directory too long to join with `file` holds nothing it could run. */
504
+ int fd = -1;
505
+ if (len && len + strlen(file) + 2 <= sizeof buf) {
506
+ memcpy(buf, dir, len);
507
+ buf[len] = '/';
508
+ strcpy(buf + len + 1, file);
509
+ path = buf;
510
+ }
511
+ if (!len || path == buf) fd = open(path, O_PATH | O_CLOEXEC);
512
+ if (fd >= 0 && !fstat(fd, &st) && S_ISREG(st.st_mode) && (st.st_mode & 0111)) {
513
+ int k = nish_sb_nrefused > NISH_SB_REFUSED ? -1 : nish_sb_nrefused;
514
+ while (k > 0 && (nish_sb_refused[k - 1].dev != st.st_dev || nish_sb_refused[k - 1].ino != st.st_ino)) k--;
515
+ int moved = k ? -EACCES : fcntl(fd, F_DUPFD, low);
516
+ if (moved == -1) moved = -errno;
517
+ close(fd);
518
+ if (moved >= 0) snprintf(proc, 32, "/proc/self/fd/%d", moved);
519
+ return moved;
520
+ }
521
+ if (fd >= 0) close(fd);
522
+ if (!*end) return -ENOENT;
523
+ dir = end + 1;
524
+ }
525
+ }
526
+
527
+ /* One exec per spawn (SBX-1, docs/wp37-os-sandbox.md section 2a "One exec
528
+ * per spawn"). Landlock grants EXECUTE on a kept interpreter to the whole
529
+ * process tree, since the kernel needs it to start a granted program, so a
530
+ * granted program that executes a path from its arguments (`find -exec`,
531
+ * `env`) could run the interpreter, and through it any file. Under an exec
532
+ * allowlist every spawn therefore runs on two threads of its own:
533
+ *
534
+ * - the supervisor leaves the process's descriptor table for a private copy
535
+ * (`unshare(CLONE_FILES)`), so that no other thread can close or replace
536
+ * a descriptor between the identity check and the exec, opens and checks
537
+ * the target there, and starts the spawner;
538
+ * - the spawner takes a seccomp filter that sends `execve` and `execveat`
539
+ * to a user-notification listener and calls `posix_spawn`, so the child
540
+ * inherits the filter. A filter cannot be removed, which is why it is a
541
+ * thread that ends with the spawn and not the calling thread.
542
+ *
543
+ * Both threads run with every signal blocked, and the child is started with
544
+ * the calling thread's mask (`POSIX_SPAWN_SETSIGMASK`): a handler run on
545
+ * either would write its wake pipe by number, and in the private table that
546
+ * number can be the listener or the spawn's own pipe.
547
+ *
548
+ * The supervisor answers the first notification, the child's own exec, with
549
+ * "continue" and closes the listener; the kernel then answers every later
550
+ * exec in that child's subtree ENOSYS, for good. The same filter refuses a
551
+ * second listener (EBUSY): the kernel lets the newest filter's "continue"
552
+ * stand for all of them, so a granted program with a listener of its own
553
+ * would answer its children's execs itself.
554
+ *
555
+ * The listener, the pipe and the target live in the private table only, and
556
+ * go with it when both threads end. Where the filter cannot be installed
557
+ * (EINVAL before Linux 5.0, EBUSY beneath a launcher's own listener) the
558
+ * spawn is refused in both modes; where "continue" is not known (before
559
+ * 5.5) the supervisor fails the child's exec instead, which refuses it too. */
560
+ #define NISH_SB_NEW_LISTENER 8u /* SECCOMP_FILTER_FLAG_NEW_LISTENER */
561
+ #define NISH_SB_USER_NOTIF 0x7fc00000u /* SECCOMP_RET_USER_NOTIF */
562
+ /* struct seccomp_notif and seccomp_notif_resp, spelled here like Landlock's
563
+ * numbers: headers older than Linux 5.0 lack them. */
564
+ struct nish_sb_notif {
565
+ uint64_t id;
566
+ uint32_t pid, flags;
567
+ struct seccomp_data data;
568
+ };
569
+ struct nish_sb_notif_resp {
570
+ uint64_t id;
571
+ int64_t val;
572
+ int32_t error;
573
+ uint32_t flags; /* 1 is SECCOMP_USER_NOTIF_FLAG_CONTINUE */
574
+ };
575
+ #define NISH_SB_NOTIF_RECV _IOWR('!', 0, struct nish_sb_notif)
576
+ #define NISH_SB_NOTIF_SEND _IOWR('!', 1, struct nish_sb_notif_resp)
577
+
578
+ extern char **environ;
579
+
580
+ struct nish_sb_job {
581
+ const char *file;
582
+ const int *dup; /* the `n` descriptors the actions read, or null */
583
+ int n;
584
+ int low;
585
+ const posix_spawn_file_actions_t *actions;
586
+ char **argv;
587
+ char proc[32];
588
+ int pipe[2]; /* the spawner's two answers: its listener, then its child */
589
+ sigset_t mask; /* the calling thread's, which the child starts with */
590
+ int32_t result;
591
+ };
592
+
593
+ /* `fd` moved to a close-on-exec descriptor at or above `low`, or -1 with
594
+ * errno. No descriptor this file makes for a spawn stays below `low`, where
595
+ * the child's file actions and this process's 0, 1 and 2 are. */
596
+ static int nish_sb_lift(int fd, int low) {
597
+ int moved = fcntl(fd, F_DUPFD_CLOEXEC, low), e = errno;
598
+ close(fd);
599
+ errno = e;
600
+ return moved;
601
+ }
602
+
603
+ static void nish_sb_refuse_spawn(int e) {
604
+ char buf[24];
605
+ nish_sb_say("cannot hold a spawned program to one exec, so the spawn is refused", 0, nish_sb_errno_name(e, buf));
606
+ }
607
+
608
+ /* The answers are written through the pipe rather than left in the job, so
609
+ * that the supervisor wakes for the second whether or not the child ever
610
+ * reached its exec: a child that dies in a redirect notifies nobody. */
611
+ static void *nish_sb_spawner(void *arg) {
612
+ struct nish_sb_job *job = arg;
613
+ static const struct sock_filter prog[] = {
614
+ NISH_SB_HEAD,
615
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, NISH_SB_EXECVE, 6, 0),
616
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, NISH_SB_EXECVEAT, 5, 0),
617
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_seccomp, 0, 3),
618
+ /* `seccomp`'s flags are its second argument. */
619
+ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, NISH_SB_ARG0_LOW + 8),
620
+ BPF_JUMP(BPF_JMP | BPF_JSET | BPF_K, NISH_SB_NEW_LISTENER, 0, 1),
621
+ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | EBUSY),
622
+ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
623
+ BPF_STMT(BPF_RET | BPF_K, NISH_SB_USER_NOTIF),
624
+ };
625
+ struct sock_fprog fprog = {sizeof prog / sizeof prog[0], (struct sock_filter *)prog};
626
+ int32_t said = (int32_t)syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, NISH_SB_NEW_LISTENER, &fprog);
627
+ /* The kernel gave the listener the lowest free number, which may be one
628
+ * the child's actions write, or this process's closed stderr. */
629
+ if (said >= 0) said = nish_sb_lift(said, job->low);
630
+ if (said < 0) said = -errno;
631
+ (void)!write(job->pipe[1], &said, sizeof said);
632
+ if (said < 0) return 0;
633
+ pid_t pid;
634
+ /* This thread blocks every signal, and a child starts with its parent's
635
+ * mask unless it is given one: the caller's. */
636
+ posix_spawnattr_t attr;
637
+ int failed = posix_spawnattr_init(&attr);
638
+ if (!failed) {
639
+ posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGMASK);
640
+ posix_spawnattr_setsigmask(&attr, &job->mask);
641
+ failed = posix_spawn(&pid, job->proc, job->actions, &attr, job->argv, environ);
642
+ posix_spawnattr_destroy(&attr);
643
+ }
644
+ said = failed ? -failed : (int32_t)pid;
645
+ (void)!write(job->pipe[1], &said, sizeof said);
646
+ return 0;
647
+ }
648
+
649
+ /* The spawner's next answer. An interrupted read is restarted: giving up
650
+ * there would lose a child that is already running. */
651
+ static int32_t nish_sb_answer(int fd) {
652
+ int32_t said;
653
+ ssize_t n;
654
+ while ((n = read(fd, &said, sizeof said)) < 0 && errno == EINTR) {}
655
+ return n == sizeof said ? said : -EIO;
656
+ }
657
+
658
+ /* The supervisor's answer to one notification. The test-only
659
+ * `-DNISH_SANDBOX_SIMULATE_NO_CONTINUE=<n>` makes the "continue" answer fail
660
+ * as it does before Linux 5.5, and for 2 the error answer after it as well;
661
+ * `scripts/build.sh` never passes it. */
662
+ static int nish_sb_reply(int listener, struct nish_sb_notif_resp *go) {
663
+ #ifdef NISH_SANDBOX_SIMULATE_NO_CONTINUE
664
+ if (go->flags || NISH_SANDBOX_SIMULATE_NO_CONTINUE > 1) {
665
+ errno = EINVAL;
666
+ return -1;
667
+ }
668
+ #endif
669
+ return ioctl(listener, NISH_SB_NOTIF_SEND, go);
670
+ }
671
+
672
+ static void *nish_sb_supervisor(void *arg) {
673
+ struct nish_sb_job *job = arg;
674
+ pthread_t spawner;
675
+ int made[2];
676
+ if (unshare(CLONE_FILES)) {
677
+ nish_sb_refuse_spawn(errno);
678
+ return 0;
679
+ }
680
+ /* The actions name their sources by number, and this table is now nobody
681
+ * else's. A source that is open here is the caller's, so no descriptor made
682
+ * below can take its number; one that is not would name whatever was made
683
+ * there, so the spawn is refused before anything is. */
684
+ for (int k = 0; job->dup && k < job->n; k++) {
685
+ if (fcntl(job->dup[k], F_GETFD) < 0) {
686
+ job->result = -EBADF;
687
+ return 0;
688
+ }
689
+ }
690
+ if (pipe2(made, O_CLOEXEC)) {
691
+ nish_sb_refuse_spawn(errno);
692
+ return 0;
693
+ }
694
+ /* Both ends are moved before either is tested, so that the line below is
695
+ * never written to an end still sitting on descriptor 2. */
696
+ job->pipe[0] = nish_sb_lift(made[0], job->low);
697
+ job->pipe[1] = nish_sb_lift(made[1], job->low);
698
+ if (job->pipe[0] < 0 || job->pipe[1] < 0) {
699
+ nish_sb_refuse_spawn(EMFILE);
700
+ return 0;
701
+ }
702
+ int fd = nish_sb_spawn_open(job->file, job->low, job->proc);
703
+ if (fd < 0) {
704
+ job->result = fd;
705
+ return 0;
706
+ }
707
+ int failed = pthread_create(&spawner, 0, nish_sb_spawner, job);
708
+ if (failed) {
709
+ nish_sb_refuse_spawn(failed);
710
+ return 0;
711
+ }
712
+ int32_t listener = nish_sb_answer(job->pipe[0]);
713
+ if (listener < 0) {
714
+ nish_sb_refuse_spawn(-listener);
715
+ job->result = listener;
716
+ } else {
717
+ struct pollfd fds[2] = {{listener, POLLIN, 0}, {job->pipe[0], POLLIN, 0}};
718
+ struct nish_sb_notif_resp go = {0, 0, 0, 1};
719
+ pid_t killed = 0;
720
+ /* Until the spawner answers: a child that never reaches its exec notifies
721
+ * nobody, and one whose exec a signal restarted notifies again. */
722
+ for (;;) {
723
+ struct nish_sb_notif exec;
724
+ while (poll(fds, 2, -1) < 0) {}
725
+ if (!(fds[0].revents & POLLIN)) break;
726
+ memset(&exec, 0, sizeof exec);
727
+ /* The child holds the listener too until its exec commits, so closing
728
+ * this copy releases nothing: a notification that is neither answered
729
+ * nor gone (ENOENT: the child was killed, or its exec restarted) would
730
+ * leave the child in its exec and the spawner in its `vfork` for good.
731
+ * Each one is therefore read again, answered, or its child killed. */
732
+ if (ioctl(listener, NISH_SB_NOTIF_RECV, &exec)) continue;
733
+ go.id = exec.id;
734
+ if (!nish_sb_reply(listener, &go)) break;
735
+ if (errno == ENOENT) continue;
736
+ /* "Continue" is not known here (EINVAL before Linux 5.5), and failing
737
+ * the exec needs no such flag. */
738
+ nish_sb_refuse_spawn(errno);
739
+ go.flags = 0;
740
+ go.error = -ENOSYS;
741
+ if (!nish_sb_reply(listener, &go)) break;
742
+ if (errno == ENOENT) continue;
743
+ killed = (pid_t)exec.pid;
744
+ kill(killed, SIGKILL);
745
+ break;
746
+ }
747
+ /* From here every exec in the child's subtree is ENOSYS. */
748
+ close(listener);
749
+ job->result = nish_sb_answer(job->pipe[0]);
750
+ /* `posix_spawn` reports a child killed before its exec as started. */
751
+ if (killed && job->result > 0) {
752
+ while (waitpid(job->result, 0, 0) < 0 && errno == EINTR) {}
753
+ job->result = -ECHILD;
754
+ }
755
+ }
756
+ pthread_join(spawner, 0);
757
+ return 0;
758
+ }
759
+
760
+ /* `nish_spawn_start`'s spawn under an exec allowlist: the child's pid, or a
761
+ * negative errno. `actions` is its `posix_spawn_file_actions_t`, whose `dup2`
762
+ * actions read the `n` descriptors of `dup` (null for none) and write `base`
763
+ * onward; the actions write nothing above `base + n + 2`. */
764
+ static int32_t nish_sb_spawn_once(const char *file, const int *dup, int base, int n, const void *actions, char **argv) {
765
+ struct nish_sb_job job = {
766
+ .file = file, .dup = dup, .n = n, .low = base + n + 3, .actions = actions, .argv = argv, .result = -EAGAIN};
767
+ pthread_t supervisor;
768
+ sigset_t all;
769
+ /* Both threads start with every signal blocked, so the program's handlers
770
+ * never run on them: a handler names its descriptors by number
771
+ * (`signalFd`'s pipe), and in the private table that number is nothing, or
772
+ * one of this spawn's own. A signal sent to the process is delivered to a
773
+ * thread that takes it. */
774
+ sigfillset(&all);
775
+ pthread_sigmask(SIG_SETMASK, &all, &job.mask);
776
+ int failed = pthread_create(&supervisor, 0, nish_sb_supervisor, &job);
777
+ pthread_sigmask(SIG_SETMASK, &job.mask, 0);
778
+ if (failed) {
779
+ nish_sb_refuse_spawn(failed);
780
+ return -EAGAIN;
781
+ }
782
+ pthread_join(supervisor, 0);
783
+ return job.result;
784
+ }
785
+
786
+ static void nish_sb_keep_interpreters(const char *paths) {
787
+ struct stat st;
788
+ if (paths) nish_spawn_sandboxed = nish_sb_spawn_once;
789
+ for (; paths && *paths; paths += strlen(paths) + 1) {
790
+ /* An entry gone since the build has no identity to keep, and Landlock
791
+ * grants it nothing to execute either. */
792
+ if (paths[1] != '/' || stat(paths, &st)) continue;
793
+ int n = nish_sb_nrefused++;
794
+ if (n < NISH_SB_REFUSED) nish_sb_refused[n].dev = st.st_dev, nish_sb_refused[n].ino = st.st_ino;
795
+ }
796
+ }
797
+
439
798
  void nish_sandbox(int32_t caps, int32_t mode, const char *read_dirs, const char *write_dirs, const char *exec_paths) {
440
799
  nish_cpu_prime();
800
+ nish_sb_keep_interpreters(exec_paths);
441
801
  if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) nish_sb_fail("cannot set no_new_privs");
442
802
  nish_sb_drop_capabilities();
443
803
  nish_sb_landlock(caps, mode, read_dirs, write_dirs, exec_paths);
@@ -17,8 +17,9 @@
17
17
  * `target("+sha2")`. A machine without them, or a process with
18
18
  * `NISH_SHA256=soft`, runs the Nish code in std/crypto/sha256.ts instead: the
19
19
  * compiler keeps that code and branches on `nish_sha256_hw` at each call. Every
20
- * other target, wasm32 included, compiles `nish_sha256_hw` to `return 0` and
21
- * the kernel to a trap nothing reaches, so a link that names it still resolves.
20
+ * other target, wasm32 included, and a toolchain without the intrinsic headers
21
+ * compile `nish_sha256_hw` to `return 0` and the kernel to a trap nothing
22
+ * reaches, so a link that names it still resolves.
22
23
  *
23
24
  * The kernel checks the guard `sha256Compress` runs its body under and returns
24
25
  * 0 without touching anything when it fails, so the caller runs the Nish
@@ -46,11 +47,17 @@
46
47
 
47
48
  #include "nish.h"
48
49
 
49
- #if defined(__x86_64__)
50
+ #if defined(__has_include)
51
+ #define NISH_SHA256_HAS(h) __has_include(h)
52
+ #else
53
+ #define NISH_SHA256_HAS(h) 0
54
+ #endif
55
+
56
+ #if defined(__x86_64__) && NISH_SHA256_HAS(<cpuid.h>) && NISH_SHA256_HAS(<immintrin.h>)
50
57
  #include <cpuid.h>
51
58
  #include <immintrin.h>
52
59
  #define NISH_SHA256_X86 1
53
- #elif defined(__aarch64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
60
+ #elif defined(__aarch64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ && NISH_SHA256_HAS(<arm_neon.h>)
54
61
  #include <arm_neon.h>
55
62
  #define NISH_SHA256_ARM 1
56
63
  #endif