@linxin666/dsh-win-bash 0.4.14 → 0.4.15

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.
package/src/runtime.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * The package ships its own Git for Windows MinGit extraction under
6
6
  * runtime/win32-x64/: the tool must NEVER fall back to a bash found on PATH
7
7
  * (a host Git for Windows install, WSL, or a stray MSYS), because the whole
8
- * point of vendoring is a shell whose version and bytes are pinned. Three
8
+ * point of vendoring is a shell whose version and bytes are pinned. Four
9
9
  * invariants implement that:
10
10
  *
11
11
  * 1. the binary is addressed by absolute path, never by name,
@@ -13,6 +13,13 @@
13
13
  * packaging time before it is used at all, and
14
14
  * 3. the tree that RUNS is a published copy under the DSH home, not the tree
15
15
  * inside the package.
16
+ * 4. the copy's Windows mandatory integrity label is checked before it is
17
+ * reused or before a freshly published copy is spawned. A Low (or lower)
18
+ * label on the executable image makes Windows start a Low-integrity process
19
+ * even from a Medium runner, and that process cannot write an ordinary
20
+ * Medium workspace or temp directory. Such a tree is never used: the payload
21
+ * is published into an isolated cache root instead, and if no candidate root
22
+ * is safe the mount is refused with a specific diagnosis.
16
23
  *
17
24
  * The third invariant is why this module publishes a cache: Windows refuses to
18
25
  * rename a directory whose executable is running, and pnpm imports a package by
@@ -35,9 +42,14 @@
35
42
 
36
43
  import { createHash, randomUUID } from 'node:crypto'
37
44
  import { cpSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs'
45
+ import { homedir } from 'node:os'
38
46
  import { dirname, join, resolve } from 'node:path'
39
47
  import { fileURLToPath } from 'node:url'
40
48
  import { resolveDshHome } from './dsh-home.ts'
49
+ import {
50
+ existingAncestors, readMandatoryLabel,
51
+ type IntegrityLabel, type LabelReader,
52
+ } from './integrity.ts'
41
53
 
42
54
  /** Directory holding the shipped payload, relative to the package root. */
43
55
  export const RUNTIME_DIR = 'runtime/win32-x64'
@@ -61,6 +73,20 @@ export const RUNTIME_ARCH = 'x64'
61
73
  */
62
74
  export const CACHE_DIR_PARTS = ['win-bash', 'runtime'] as const
63
75
 
76
+ /**
77
+ * Directory parts of the isolated fallback cache, used only when the preferred
78
+ * cache root carries a Low mandatory integrity label. It lives outside the DSH
79
+ * data tree, which a workspace sandbox can label Low with an inheritable ACE.
80
+ */
81
+ export const ISOLATED_CACHE_DIR_PARTS = ['dsh-win-bash', 'runtime'] as const
82
+
83
+ /**
84
+ * Optional environment override for the isolated cache root's parent. An
85
+ * operator whose local app data is itself labelled Low can point this at a
86
+ * directory they have verified is Medium; it is not needed on a normal host.
87
+ */
88
+ export const RUNTIME_ROOT_ENV = 'DSH_WIN_BASH_RUNTIME_HOME'
89
+
64
90
  /**
65
91
  * Name prefix of the staging directory one cache copy is built in. The rest of
66
92
  * the name is the payload key, this process's id and a random suffix, so a
@@ -119,6 +145,32 @@ export function cacheRoot(env: NodeJS.ProcessEnv = process.env): string {
119
145
  return join(resolveDshHome(env), ...CACHE_DIR_PARTS)
120
146
  }
121
147
 
148
+ /**
149
+ * Absolute root of the isolated fallback payload cache.
150
+ *
151
+ * The DSH home is a data tree a workspace sandbox may have labelled Low with
152
+ * an inheritable ACE. A copy published below it then inherits that label and
153
+ * starts a Low-integrity bash, which cannot write a Medium workspace or temp
154
+ * directory. This root deliberately lives OUTSIDE the DSH home, under the
155
+ * per-user application-data (or cache) directory instead.
156
+ *
157
+ * It still follows the probe-isolation convention: the final path component is
158
+ * derived from the DSH home, so an isolated `DSH_HOME` gets its own isolated
159
+ * cache too. Operators whose application-data tree is itself labelled Low can
160
+ * point {@link RUNTIME_ROOT_ENV} at a directory they have verified.
161
+ * @param env - environment to read the override, app-data root and DSH home from.
162
+ * @returns the directory the fallback payload copies are published under.
163
+ */
164
+ export function isolatedCacheRoot(env: NodeJS.ProcessEnv = process.env): string {
165
+ const override = env[RUNTIME_ROOT_ENV]?.trim()
166
+ if (override !== undefined && override !== '') return resolve(override)
167
+ const base = env.LOCALAPPDATA
168
+ ?? (process.platform === 'win32'
169
+ ? join(homedir(), 'AppData', 'Local')
170
+ : (env.XDG_CACHE_HOME ?? join(homedir(), '.cache')))
171
+ return join(base, ...ISOLATED_CACHE_DIR_PARTS, sha256(resolveDshHome(env)).slice(0, 12))
172
+ }
173
+
122
174
  /** One manifest row: a payload-relative path and its digest. */
123
175
  export interface ChecksumEntry {
124
176
  /** Payload-relative path, using forward slashes. */
@@ -237,6 +289,7 @@ export interface RuntimeRejection {
237
289
  | 'missing-binary'
238
290
  | 'checksum-mismatch'
239
291
  | 'manifest-unreadable'
292
+ | 'unsafe-integrity'
240
293
  /** One-sentence, operator-facing explanation. */
241
294
  readonly message: string
242
295
  }
@@ -359,8 +412,12 @@ export interface PrepareRuntimeOptions {
359
412
  readonly packageRoot?: string
360
413
  /** Cache root to publish into; the DSH home's own by default. */
361
414
  readonly cacheRoot?: string
362
- /** Environment the default cache root resolves from; process.env by default. */
415
+ /** Isolated fallback root; the per-user app-data cache by default. */
416
+ readonly isolatedCacheRoot?: string
417
+ /** Environment the default roots resolve from; process.env by default. */
363
418
  readonly env?: NodeJS.ProcessEnv
419
+ /** Mandatory-integrity-label reader; the Windows icacls reader by default. */
420
+ readonly readLabel?: LabelReader
364
421
  /** Operator-facing notes; a copy that could not be published is reported here. */
365
422
  readonly warn?: (message: string) => void
366
423
  /** The copy itself; a real recursive copy by default. */
@@ -392,10 +449,11 @@ function removeStaging(staging: string): void {
392
449
  *
393
450
  * The copy's own manifest must reproduce the expected key before any byte is
394
451
  * executed, so a directory whose manifest was rewritten alongside its files is
395
- * a miss rather than a match.
452
+ * a miss rather than a match. This is a BYTE check only: it says nothing about
453
+ * the security descriptor, which is why callers also run {@link cacheSafe}.
396
454
  * @param root - the candidate payload root.
397
455
  * @param key - the key the shipped manifest produced.
398
- * @returns whether that directory can be spawned from.
456
+ * @returns whether that directory's bytes can be spawned from.
399
457
  */
400
458
  function cacheReady(root: string, key: string): boolean {
401
459
  try {
@@ -408,6 +466,32 @@ function cacheReady(root: string, key: string): boolean {
408
466
  }
409
467
  }
410
468
 
469
+ /**
470
+ * Whether a published tree's mandatory integrity label is safe to spawn from.
471
+ *
472
+ * Both the directory and the executable itself are inspected: the Windows
473
+ * sandbox applies an inheritable Low ACE to the directory, and the image then
474
+ * carries an inherited Low ACE. Before a directory exists, the closest existing
475
+ * ancestor is what decides the label a newly created file inherits.
476
+ *
477
+ * `unknown` is not treated as safe. A descriptor we cannot read cannot be
478
+ * claimed as verified, so the caller moves on to another candidate root rather
479
+ * than silently running from an unverified image.
480
+ * @param root - the candidate payload root.
481
+ * @param readLabel - the label reader (injectable seam).
482
+ * @returns the label verdict for that tree.
483
+ */
484
+ function cacheSafe(root: string, readLabel: LabelReader): IntegrityLabel {
485
+ // Every existing ancestor matters: an inheritable Low ACE on the DSH home
486
+ // can be propagated onto existing children after the cache was published.
487
+ const verdicts = existingAncestors(root).map(target => readLabel(target))
488
+ const bash = bashIn(root)
489
+ if (existsSync(bash)) verdicts.push(readLabel(bash))
490
+ if (verdicts.includes('low-or-untrusted')) return 'low-or-untrusted'
491
+ if (verdicts.includes('unknown')) return 'unknown'
492
+ return 'medium-or-higher'
493
+ }
494
+
411
495
  /**
412
496
  * Publish one payload copy under its key.
413
497
  *
@@ -441,21 +525,45 @@ function publishPayload(source: string, target: string, key: string, copy: CopyT
441
525
  }
442
526
  }
443
527
 
528
+ /**
529
+ * Why one candidate cache root could not serve the payload.
530
+ *
531
+ * A Low verdict is a security fact, not a write failure: the tree must not be
532
+ * reused or spawned from at all. The other reasons keep the existing honest
533
+ * fallback to the verified packaged tree.
534
+ */
535
+ interface CacheDiagnosis {
536
+ /** Operator-facing explanation. */
537
+ readonly message: string
538
+ /** Whether a Low/Untrusted mandatory label was actually observed. */
539
+ readonly low: boolean
540
+ }
541
+
444
542
  /**
445
543
  * Resolve the shell one host runs, publishing the payload outside the package.
446
544
  *
447
- * The verification order is the whole point: the shipped manifest identifies
448
- * the payload, a published copy of that identity is reused when it verifies,
449
- * and otherwise the packaged tree is verified first and only then copied. What
450
- * gets spawned is therefore always a tree whose bytes match the shipped
451
- * manifest, and it lives under the DSH home where an update or uninstall of
452
- * this package cannot be blocked by a running shell.
545
+ * Two independent proofs gate every tree that can be spawned: the shipped
546
+ * SHA256 manifest proves its BYTES, and a mandatory-integrity-label check
547
+ * proves its SECURITY DESCRIPTOR cannot downgrade a Medium runner to a Low
548
+ * process. A label check runs before a published copy is reused, before a new
549
+ * copy is published, and again after publication (the decisive check is on the
550
+ * bash.exe that will actually be spawned). A tree carrying Low or Untrusted is
551
+ * never reused and never spawned from, so a hash match alone can no longer keep
552
+ * a broken cache alive across restarts and updates.
553
+ *
554
+ * Candidate roots are tried in order. The DSH home cache keeps the #1996 fix;
555
+ * when its data tree is labelled Low, the payload is published into an isolated
556
+ * per-user application-data root instead, still OUTSIDE the package. An old Low
557
+ * cache under the DSH home is therefore migrated by abandonment, not by a
558
+ * one-off repair of one payload-key directory.
453
559
  *
454
- * A cache that cannot be written is not a reason to withhold the tool: the
455
- * verified packaged tree runs instead and the caller is told, through
456
- * {@link PrepareRuntimeOptions.warn}, that updates will need this host stopped.
457
- * A payload that fails its manifest is still a refusal — running unverified
458
- * bytes is the outcome the manifest exists to prevent, cache or no cache.
560
+ * When no candidate can be written or verified, the verified packaged tree runs
561
+ * instead and the caller is told, through {@link PrepareRuntimeOptions.warn},
562
+ * that updates will need this host stopped. But if a Low label was observed and
563
+ * even the packaged image is not proven clean, the mount is REFUSED with
564
+ * `unsafe-integrity` rather than silently executing a shell that cannot write
565
+ * the session's workspace. A payload that fails its manifest is always a
566
+ * refusal, cache or no cache.
459
567
  * @param options - host facts, roots, and the seams tests drive.
460
568
  * @returns the shell paths to run, or the rejection reason.
461
569
  */
@@ -465,8 +573,28 @@ export function prepareRuntime(options: PrepareRuntimeOptions = {}): RuntimeRead
465
573
  if (refused !== undefined) return refused
466
574
  const packageRoot = options.packageRoot ?? PACKAGE_ROOT
467
575
  const source = runtimeRoot(packageRoot)
468
- const cacheDir = options.cacheRoot ?? cacheRoot(options.env)
469
576
  const warn = options.warn ?? ((): void => {})
577
+ // One mount inspects the same ancestors several times (before reuse, before
578
+ // publication, after publication). Memoize within this call: a descriptor
579
+ // cannot change underneath us, and icacls is a process per query.
580
+ const rawLabel = options.readLabel ?? readMandatoryLabel
581
+ const labels = new Map<string, IntegrityLabel>()
582
+ const readLabel: LabelReader = (target: string): IntegrityLabel => {
583
+ const hit = labels.get(target)
584
+ if (hit !== undefined) return hit
585
+ const verdict = rawLabel(target)
586
+ labels.set(target, verdict)
587
+ return verdict
588
+ }
589
+ const copy = options.copy ?? copyTree
590
+
591
+ // A caller that names cacheRoot explicitly (tests, probe instances) owns the
592
+ // candidate set: it must also name isolatedCacheRoot to get a second one.
593
+ // Only the real default path adds the isolated fallback automatically.
594
+ const roots = [options.cacheRoot ?? cacheRoot(options.env)]
595
+ const isolated = options.isolatedCacheRoot
596
+ ?? (options.cacheRoot === undefined ? isolatedCacheRoot(options.env) : undefined)
597
+ if (isolated !== undefined && !roots.includes(isolated)) roots.push(isolated)
470
598
 
471
599
  let key: string
472
600
  try {
@@ -478,25 +606,86 @@ export function prepareRuntime(options: PrepareRuntimeOptions = {}): RuntimeRead
478
606
  }
479
607
  }
480
608
 
481
- const published = join(cacheDir, key)
482
- if (cacheReady(published, key)) return readyFrom(published, 'cache')
609
+ const diagnoses: CacheDiagnosis[] = []
610
+ let shipped: RuntimeReady | RuntimeRejection | undefined
611
+ const verifiedPackage = (): RuntimeReady | RuntimeRejection => {
612
+ shipped ??= resolveRuntime(host, packageRoot)
613
+ return shipped
614
+ }
483
615
 
484
- const shipped = resolveRuntime(host, packageRoot)
485
- if ('code' in shipped) return shipped
616
+ for (const cacheDir of roots) {
617
+ const published = join(cacheDir, key)
618
+
619
+ // Before reuse AND before publication: never touch a Low-labelled tree.
620
+ const before = cacheSafe(published, readLabel)
621
+ if (before === 'low-or-untrusted') {
622
+ diagnoses.push({
623
+ low: true,
624
+ message: 'the cache root ' + cacheDir + ' carries a Low or Untrusted mandatory integrity label',
625
+ })
626
+ continue
627
+ }
628
+ if (before === 'unknown') {
629
+ diagnoses.push({
630
+ low: false,
631
+ message: 'the mandatory integrity label of ' + cacheDir + ' could not be read',
632
+ })
633
+ continue
634
+ }
486
635
 
487
- try {
488
- publishPayload(source, published, key, options.copy ?? copyTree)
489
- } catch (error) {
490
- warn('the verified payload could not be published to ' + published + ' (' + describe(error)
491
- + '), so this host runs the shell from ' + source + '; while it runs, updating or uninstalling'
492
- + ' this package can fail with ERR_PNPM_EPERM')
493
- return shipped
636
+ if (cacheReady(published, key)) return readyFrom(published, 'cache')
637
+
638
+ const packaged = verifiedPackage()
639
+ if ('code' in packaged) return packaged
640
+ try {
641
+ publishPayload(source, published, key, copy)
642
+ } catch (error) {
643
+ diagnoses.push({
644
+ low: false,
645
+ message: 'the verified payload could not be published to ' + published + ' (' + describe(error) + ')',
646
+ })
647
+ continue
648
+ }
649
+ if (!cacheReady(published, key)) {
650
+ diagnoses.push({
651
+ low: false,
652
+ message: 'the payload copy at ' + published + ' did not verify against the shipped manifest',
653
+ })
654
+ continue
655
+ }
656
+
657
+ // After publication: the label a freshly created bash.exe INHERITED is the
658
+ // decisive fact. A tree that turned Low here is never returned to a caller.
659
+ const after = cacheSafe(published, readLabel)
660
+ if (after !== 'medium-or-higher') {
661
+ diagnoses.push({
662
+ low: after === 'low-or-untrusted',
663
+ message: after === 'low-or-untrusted'
664
+ ? 'the newly published bash.exe at ' + bashIn(published) + ' inherited a Low or Untrusted mandatory integrity label'
665
+ : 'the mandatory integrity label of the newly published bash.exe at ' + bashIn(published) + ' could not be read',
666
+ })
667
+ continue
668
+ }
669
+ return readyFrom(published, 'cache')
494
670
  }
495
- if (!cacheReady(published, key)) {
496
- warn('the payload copy at ' + published + ' did not verify against the shipped manifest, so this host'
497
- + ' runs the shell from ' + source + '; while it runs, updating or uninstalling this package can fail'
498
- + ' with ERR_PNPM_EPERM')
499
- return shipped
671
+
672
+ const packaged = verifiedPackage()
673
+ if ('code' in packaged) return packaged
674
+ const reasons = diagnoses.map(entry => entry.message).join('; ')
675
+ const sawLow = diagnoses.some(entry => entry.low)
676
+ const packagedLabel = readLabel(bashPath(packageRoot))
677
+ if (sawLow && packagedLabel === 'low-or-untrusted') {
678
+ return {
679
+ code: 'unsafe-integrity',
680
+ message: 'every runtime cache root is unsafe to spawn from and the packaged payload is not proven clean: '
681
+ + reasons + '. A Low-labelled bash.exe would start a Low-integrity process on this Medium host, which '
682
+ + 'cannot write an ordinary workspace or temp directory, so win_bash refuses to mount instead of '
683
+ + 'silently running a broken shell. Use the host pwsh tool, or point ' + RUNTIME_ROOT_ENV
684
+ + ' at a directory you have verified has no Low Mandatory Level label. Do not lower the '
685
+ + 'workspace integrity level or change the global sandbox policy to work around this.',
686
+ }
500
687
  }
501
- return readyFrom(published, 'cache')
688
+ warn(reasons + ', so this host runs the shell from ' + source + '; while it runs, updating or '
689
+ + 'uninstalling this package can fail with ERR_PNPM_EPERM')
690
+ return packaged
502
691
  }