@dailephd/my-centcom 0.2.0 → 0.3.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 (175) hide show
  1. package/README.md +10 -5
  2. package/apps/daemon/dist/artifacts/returnSnapshots.d.ts +12 -0
  3. package/apps/daemon/dist/artifacts/returnSnapshots.js +41 -0
  4. package/apps/daemon/dist/bootstrap/app.d.ts +21 -0
  5. package/apps/daemon/dist/bootstrap/app.js +27 -0
  6. package/apps/daemon/dist/bootstrap/installLayout.d.ts +81 -0
  7. package/apps/daemon/dist/bootstrap/installLayout.js +164 -0
  8. package/apps/daemon/dist/bootstrap/main.d.ts +14 -0
  9. package/apps/daemon/dist/bootstrap/main.js +141 -0
  10. package/apps/daemon/dist/bootstrap/operatorConsole.d.ts +75 -0
  11. package/apps/daemon/dist/bootstrap/operatorConsole.js +293 -0
  12. package/apps/daemon/dist/bootstrap/privateDataRoot.d.ts +38 -0
  13. package/apps/daemon/dist/bootstrap/privateDataRoot.js +204 -0
  14. package/apps/daemon/dist/bootstrap/secureMain.d.ts +118 -0
  15. package/apps/daemon/dist/bootstrap/secureMain.js +403 -0
  16. package/apps/daemon/dist/bootstrap/setup.d.ts +93 -0
  17. package/apps/daemon/dist/bootstrap/setup.js +738 -0
  18. package/apps/daemon/dist/context/changeProposal.d.ts +97 -0
  19. package/apps/daemon/dist/context/changeProposal.js +259 -0
  20. package/apps/daemon/dist/context/gitEvidence.d.ts +88 -0
  21. package/apps/daemon/dist/context/gitEvidence.js +332 -0
  22. package/apps/daemon/dist/context/gitObservation.d.ts +30 -0
  23. package/apps/daemon/dist/context/gitObservation.js +113 -0
  24. package/apps/daemon/dist/context/projectReadIssuer.d.ts +68 -0
  25. package/apps/daemon/dist/context/projectReadIssuer.js +158 -0
  26. package/apps/daemon/dist/context/projectReadService.d.ts +153 -0
  27. package/apps/daemon/dist/context/projectReadService.js +652 -0
  28. package/apps/daemon/dist/context/projectViewService.d.ts +85 -0
  29. package/apps/daemon/dist/context/projectViewService.js +332 -0
  30. package/apps/daemon/dist/context/proposalRecorder.d.ts +11 -0
  31. package/apps/daemon/dist/context/proposalRecorder.js +19 -0
  32. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.d.ts +40 -0
  33. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.js +73 -0
  34. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.d.ts +49 -0
  35. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.js +70 -0
  36. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.d.ts +16 -0
  37. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.js +115 -0
  38. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.d.ts +153 -0
  39. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.js +505 -0
  40. package/apps/daemon/dist/plugins/registry/operationCatalog.d.ts +23 -0
  41. package/apps/daemon/dist/plugins/registry/operationCatalog.js +41 -0
  42. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.d.ts +14 -0
  43. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.js +29 -0
  44. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.d.ts +151 -0
  45. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.js +579 -0
  46. package/apps/daemon/dist/projects/codingAuthority.d.ts +102 -0
  47. package/apps/daemon/dist/projects/codingAuthority.js +244 -0
  48. package/apps/daemon/dist/projects/fixtureAuthorization.d.ts +54 -0
  49. package/apps/daemon/dist/projects/fixtureAuthorization.js +172 -0
  50. package/apps/daemon/dist/projects/pairedAuthority.d.ts +158 -0
  51. package/apps/daemon/dist/projects/pairedAuthority.js +273 -0
  52. package/apps/daemon/dist/projects/trustedCliConsent.d.ts +47 -0
  53. package/apps/daemon/dist/projects/trustedCliConsent.js +84 -0
  54. package/apps/daemon/dist/runs/changeApplier.d.ts +59 -0
  55. package/apps/daemon/dist/runs/changeApplier.js +319 -0
  56. package/apps/daemon/dist/runs/codingWorkflowService.d.ts +283 -0
  57. package/apps/daemon/dist/runs/codingWorkflowService.js +785 -0
  58. package/apps/daemon/dist/runs/durableIntentCoordinator.d.ts +72 -0
  59. package/apps/daemon/dist/runs/durableIntentCoordinator.js +160 -0
  60. package/apps/daemon/dist/runs/inMemoryCoordinator.d.ts +55 -0
  61. package/apps/daemon/dist/runs/inMemoryCoordinator.js +375 -0
  62. package/apps/daemon/dist/runs/runExecutor.d.ts +154 -0
  63. package/apps/daemon/dist/runs/runExecutor.js +295 -0
  64. package/apps/daemon/dist/runs/workflowService.d.ts +185 -0
  65. package/apps/daemon/dist/runs/workflowService.js +300 -0
  66. package/apps/daemon/dist/runtime/boundedProcessHost.d.ts +111 -0
  67. package/apps/daemon/dist/runtime/boundedProcessHost.js +752 -0
  68. package/apps/daemon/dist/runtime/evidenceRedaction.d.ts +30 -0
  69. package/apps/daemon/dist/runtime/evidenceRedaction.js +79 -0
  70. package/apps/daemon/dist/runtime/executionDiagnostics.d.ts +134 -0
  71. package/apps/daemon/dist/runtime/executionDiagnostics.js +213 -0
  72. package/apps/daemon/dist/runtime/modelExecutionPolicy.d.ts +22 -0
  73. package/apps/daemon/dist/runtime/modelExecutionPolicy.js +19 -0
  74. package/apps/daemon/dist/runtime/mxcExecution.d.ts +12 -0
  75. package/apps/daemon/dist/runtime/mxcExecution.js +163 -0
  76. package/apps/daemon/dist/runtime/mxcIntegrity.d.ts +24 -0
  77. package/apps/daemon/dist/runtime/mxcIntegrity.js +81 -0
  78. package/apps/daemon/dist/runtime/mxcWorker.d.ts +2 -0
  79. package/apps/daemon/dist/runtime/mxcWorker.js +45 -0
  80. package/apps/daemon/dist/runtime/provisionedExecution.d.ts +150 -0
  81. package/apps/daemon/dist/runtime/provisionedExecution.js +653 -0
  82. package/apps/daemon/dist/runtime/testExecution.d.ts +76 -0
  83. package/apps/daemon/dist/runtime/testExecution.js +106 -0
  84. package/apps/daemon/dist/runtime/testProfiles.d.ts +10 -0
  85. package/apps/daemon/dist/runtime/testProfiles.js +4 -0
  86. package/apps/daemon/dist/runtime/trustedAgentStaging.d.ts +89 -0
  87. package/apps/daemon/dist/runtime/trustedAgentStaging.js +262 -0
  88. package/apps/daemon/dist/runtime/trustedCaBundle.d.ts +77 -0
  89. package/apps/daemon/dist/runtime/trustedCaBundle.js +125 -0
  90. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.d.ts +166 -0
  91. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.js +521 -0
  92. package/apps/daemon/dist/storage/diagnosticLog.d.ts +63 -0
  93. package/apps/daemon/dist/storage/diagnosticLog.js +136 -0
  94. package/apps/daemon/dist/storage/executionTelemetry.d.ts +63 -0
  95. package/apps/daemon/dist/storage/executionTelemetry.js +247 -0
  96. package/apps/daemon/dist/storage/protectedSecrets.d.ts +39 -0
  97. package/apps/daemon/dist/storage/protectedSecrets.js +106 -0
  98. package/apps/daemon/dist/storage/sqliteLedger.d.ts +786 -0
  99. package/apps/daemon/dist/storage/sqliteLedger.js +1303 -0
  100. package/apps/daemon/dist/transports/http/dispatch.d.ts +43 -0
  101. package/apps/daemon/dist/transports/http/dispatch.js +405 -0
  102. package/apps/daemon/dist/transports/http/secureRoutes.d.ts +40 -0
  103. package/apps/daemon/dist/transports/http/secureRoutes.js +332 -0
  104. package/apps/daemon/dist/transports/http/workflowRoutes.d.ts +41 -0
  105. package/apps/daemon/dist/transports/http/workflowRoutes.js +473 -0
  106. package/apps/daemon/dist/transports/mcp/localProjectReadServer.d.ts +182 -0
  107. package/apps/daemon/dist/transports/mcp/localProjectReadServer.js +221 -0
  108. package/apps/daemon/dist/transports/native/nativeHost.d.ts +24 -0
  109. package/apps/daemon/dist/transports/native/nativeHost.js +344 -0
  110. package/apps/daemon/package.json +24 -0
  111. package/apps/daemon/src/runtime/benign/referenceEcho.mjs +27 -0
  112. package/apps/daemon/src/runtime/windows/buildSupervisor.mjs +87 -0
  113. package/apps/daemon/src/runtime/windows/supervisorMain.cs +676 -0
  114. package/apps/extension/manifest.secure.json +25 -0
  115. package/apps/extension/scripts/build.mjs +173 -0
  116. package/apps/extension/src/background/secureWorker.ts +1595 -0
  117. package/apps/extension/src/background/serviceWorker.ts +892 -0
  118. package/apps/extension/src/content/captureSelection.ts +64 -0
  119. package/apps/extension/src/content/secureInsert.ts +207 -0
  120. package/apps/extension/src/probe/index.html +41 -0
  121. package/apps/extension/src/probe/main.ts +201 -0
  122. package/apps/extension/src/sidepanel/index.html +203 -0
  123. package/apps/extension/src/sidepanel/main.ts +903 -0
  124. package/package.json +19 -3
  125. package/packages/contracts/dist/artifacts.d.ts +66 -0
  126. package/packages/contracts/dist/artifacts.js +64 -0
  127. package/packages/contracts/dist/automation.d.ts +540 -0
  128. package/packages/contracts/dist/automation.js +191 -0
  129. package/packages/contracts/dist/browser.d.ts +251 -0
  130. package/packages/contracts/dist/browser.js +131 -0
  131. package/packages/contracts/dist/context.d.ts +71 -0
  132. package/packages/contracts/dist/context.js +73 -0
  133. package/packages/contracts/dist/diagnostics.d.ts +99 -0
  134. package/packages/contracts/dist/diagnostics.js +284 -0
  135. package/packages/contracts/dist/effects.d.ts +42 -0
  136. package/packages/contracts/dist/effects.js +42 -0
  137. package/packages/contracts/dist/errors.d.ts +75 -0
  138. package/packages/contracts/dist/errors.js +70 -0
  139. package/packages/contracts/dist/events.d.ts +50 -0
  140. package/packages/contracts/dist/events.js +34 -0
  141. package/packages/contracts/dist/executionDiagnostics.d.ts +212 -0
  142. package/packages/contracts/dist/executionDiagnostics.js +101 -0
  143. package/packages/contracts/dist/identity.d.ts +54 -0
  144. package/packages/contracts/dist/identity.js +40 -0
  145. package/packages/contracts/dist/index.d.ts +20 -0
  146. package/packages/contracts/dist/index.js +20 -0
  147. package/packages/contracts/dist/invocation.d.ts +90 -0
  148. package/packages/contracts/dist/invocation.js +77 -0
  149. package/packages/contracts/dist/lifecycle.d.ts +130 -0
  150. package/packages/contracts/dist/lifecycle.js +135 -0
  151. package/packages/contracts/dist/plugin.d.ts +214 -0
  152. package/packages/contracts/dist/plugin.js +117 -0
  153. package/packages/contracts/dist/projectRead.d.ts +205 -0
  154. package/packages/contracts/dist/projectRead.js +162 -0
  155. package/packages/contracts/dist/secure.d.ts +128 -0
  156. package/packages/contracts/dist/secure.js +99 -0
  157. package/packages/contracts/package.json +32 -0
  158. package/packages/contracts/src/artifacts.ts +83 -0
  159. package/packages/contracts/src/automation.ts +238 -0
  160. package/packages/contracts/src/browser.ts +164 -0
  161. package/packages/contracts/src/context.ts +91 -0
  162. package/packages/contracts/src/diagnostics.ts +318 -0
  163. package/packages/contracts/src/effects.ts +49 -0
  164. package/packages/contracts/src/errors.ts +83 -0
  165. package/packages/contracts/src/events.ts +46 -0
  166. package/packages/contracts/src/executionDiagnostics.ts +116 -0
  167. package/packages/contracts/src/identity.ts +68 -0
  168. package/packages/contracts/src/index.ts +20 -0
  169. package/packages/contracts/src/invocation.ts +96 -0
  170. package/packages/contracts/src/lifecycle.ts +169 -0
  171. package/packages/contracts/src/plugin.ts +174 -0
  172. package/packages/contracts/src/projectRead.ts +179 -0
  173. package/packages/contracts/src/secure.ts +136 -0
  174. package/provenance.json +179 -9
  175. package/source.zip +0 -0
@@ -0,0 +1,676 @@
1
+ // C06 Windows Job-supervised launch helper (SW-046, B03-F). C# 5 (in-box csc.exe); Windows only.
2
+ //
3
+ // One helper process owns exactly ONE launch and ONE unnamed Job Object. It is not a service, not a broker and not a
4
+ // sandbox: it listens on no port, has no shell, no PATH search and no way to run anything but the single pinned
5
+ // executable named in the single launch request it accepts on stdin. It never sees a bearer token or an approval proof.
6
+ //
7
+ // What it does, in order: reads one strictly validated launch request; opens the pinned executable with
8
+ // FileShare.Read (so writers, renamers and deleters are refused while the handle is held) and compares its SHA-256 with
9
+ // the trusted digest; creates an unnamed Job with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE and no breakaway flag; creates the
10
+ // target CREATE_SUSPENDED with an explicit environment and an explicit inheritable-handle list; re-hashes the file the
11
+ // OS actually mapped (QueryFullProcessImageName follows renames); assigns the suspended process to the Job and confirms
12
+ // IsProcessInJob; resumes it (the previous suspend count must be exactly 1); relays stdout/stderr as bounded frames;
13
+ // on cancel, owner loss or root exit terminates the Job and positively verifies every member by PID AND creation time.
14
+ //
15
+ // Optional fixed execution identity (SW-050): when the trusted owner asked for RESTRICTED_LOW_INTEGRITY the target is created with a
16
+ // restricted PRIMARY token derived from the caller's own token (DISABLE_MAX_PRIVILEGE, a fixed restricting-SID set, a corrected default
17
+ // DACL, Low integrity). The token is verified after creation and the CHILD's actual token is verified again before it can run; any
18
+ // mismatch aborts the suspended child. There is no fallback to the caller token.
19
+ // Optional bounded stdin (SW-052): request tag 7 carries the approved prompt bytes (UTF-8, 1..32768 bytes, no NUL) and tag 8 their SHA-256; the
20
+ // helper re-hashes them before any process exists. The target's stdin is a PRIVATE anonymous pipe with a small default buffer (real backpressure)
21
+ // written ONCE by a helper thread after the target is resumed and then closed (EOF). The bytes never appear in argv, the environment, any output
22
+ // frame or any file, and they are a different channel from the control frames. The 'N' frame reports only status and byte counts.
23
+ // What it does NOT prove: atomic image identity (the owner reaches this helper by path), filesystem write confinement,
24
+ // private-database isolation, or behavior/safety of the target. A Job Object restricts none of those.
25
+ //
26
+ // Wire format (both directions): 'M' 'C' version(1) type(1) length(u32 little endian) payload. length <= 65536.
27
+ // in : 'L' launch (once, first) payload = fields [tag u8][len u32][utf8] tags 1 exe, 2 sha256, 3 cwd, 4 arg*, 5 env*, 6 identity (optional), 7 stdin bytes + 8 stdin sha256 (optional, together)
28
+ // 'C' cancel (payload empty)
29
+ // out: 'H' held, 'I' identity (restricted mode only), 'S' started, 'N' stdin report (stdin mode only), 'O' stdout bytes, 'E' stderr bytes, 'X' root exit, 'T' tree report, 'F' failure, 'Z' end
30
+ // Text payloads are key=value lines. Raw handles, pointers, environment values and paths are never emitted.
31
+ using System;
32
+ using System.Collections.Generic;
33
+ using System.IO;
34
+ using System.Runtime.InteropServices;
35
+ using System.Security.Cryptography;
36
+ using System.Text;
37
+ using System.Text.RegularExpressions;
38
+ using System.Threading;
39
+
40
+ namespace MyCentcom.Supervisor
41
+ {
42
+ internal sealed class Fail : Exception
43
+ {
44
+ public readonly string Code; public readonly int Win32;
45
+ public Fail(string code, int win32) : base(code) { Code = code; Win32 = win32; }
46
+ }
47
+
48
+ internal static class W
49
+ {
50
+ [StructLayout(LayoutKind.Sequential)] public struct STARTUPINFO { public int cb; public IntPtr lpReserved, lpDesktop, lpTitle; public int dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags; public short wShowWindow, cbReserved2; public IntPtr lpReserved2, hStdInput, hStdOutput, hStdError; }
51
+ [StructLayout(LayoutKind.Sequential)] public struct STARTUPINFOEX { public STARTUPINFO si; public IntPtr attrs; }
52
+ [StructLayout(LayoutKind.Sequential)] public struct PROCESS_INFORMATION { public IntPtr hProcess, hThread; public int pid, tid; }
53
+ [StructLayout(LayoutKind.Sequential)] public struct SECURITY_ATTRIBUTES { public int nLength; public IntPtr lpSecurityDescriptor; public int bInheritHandle; }
54
+ [StructLayout(LayoutKind.Sequential)] public struct IO_COUNTERS { public ulong a, b, c, d, e, f; }
55
+ [StructLayout(LayoutKind.Sequential)] public struct BASIC_LIMIT { public long PerProcessUserTimeLimit, PerJobUserTimeLimit; public uint LimitFlags; public UIntPtr MinWS, MaxWS; public uint ActiveProcessLimit; public UIntPtr Affinity; public uint PriorityClass, SchedulingClass; }
56
+ [StructLayout(LayoutKind.Sequential)] public struct EXT_LIMIT { public BASIC_LIMIT Basic; public IO_COUNTERS Io; public UIntPtr ProcMem, JobMem, PeakProc, PeakJob; }
57
+ [StructLayout(LayoutKind.Sequential)] public struct ACCOUNTING { public long a, b, c, d; public uint PageFaults, TotalProcesses, ActiveProcesses, TotalTerminated; }
58
+ [StructLayout(LayoutKind.Sequential)] public struct FILETIME { public uint lo, hi; }
59
+
60
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool CreateProcessW(string app, StringBuilder cmd, IntPtr pa, IntPtr ta, bool inherit, uint flags, IntPtr env, string cwd, ref STARTUPINFOEX si, out PROCESS_INFORMATION pi);
61
+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool CreateProcessAsUserW(IntPtr tok, string app, StringBuilder cmd, IntPtr pa, IntPtr ta, bool inherit, uint flags, IntPtr env, string cwd, ref STARTUPINFOEX si, out PROCESS_INFORMATION pi);
62
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool InitializeProcThreadAttributeList(IntPtr list, int count, int flags, ref IntPtr size);
63
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool UpdateProcThreadAttribute(IntPtr list, uint flags, IntPtr attr, IntPtr value, IntPtr size, IntPtr prev, IntPtr ret);
64
+ [DllImport("kernel32.dll")] public static extern void DeleteProcThreadAttributeList(IntPtr list);
65
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr CreateJobObjectW(IntPtr sa, string name);
66
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool SetInformationJobObject(IntPtr job, int cls, ref EXT_LIMIT info, int len);
67
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool AssignProcessToJobObject(IntPtr job, IntPtr proc);
68
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool IsProcessInJob(IntPtr proc, IntPtr job, out bool r);
69
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool QueryInformationJobObject(IntPtr job, int cls, ref ACCOUNTING info, int len, IntPtr ret);
70
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool QueryInformationJobObject(IntPtr job, int cls, IntPtr buf, int len, IntPtr ret);
71
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool TerminateJobObject(IntPtr job, uint code);
72
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern int ResumeThread(IntPtr th);
73
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern uint WaitForSingleObject(IntPtr h, uint ms);
74
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool GetExitCodeProcess(IntPtr h, out uint code);
75
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool TerminateProcess(IntPtr h, uint code);
76
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool CloseHandle(IntPtr h);
77
+ [DllImport("kernel32.dll")] public static extern IntPtr GetCurrentProcess();
78
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr OpenProcess(uint acc, bool inh, int pid);
79
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool GetProcessTimes(IntPtr h, out FILETIME c, out FILETIME e, out FILETIME k, out FILETIME u);
80
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool CreatePipe(out IntPtr r, out IntPtr w, ref SECURITY_ATTRIBUTES sa, uint size);
81
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool SetHandleInformation(IntPtr h, uint mask, uint flags);
82
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool WriteFile(IntPtr h, byte[] buf, uint n, out uint written, IntPtr ov);
83
+ [DllImport("kernel32.dll", SetLastError = true)] public static extern bool ReadFile(IntPtr h, byte[] buf, uint n, out uint read, IntPtr ov);
84
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern IntPtr CreateFileW(string name, uint acc, uint share, ref SECURITY_ATTRIBUTES sa, uint disp, uint fl, IntPtr tmpl);
85
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool QueryFullProcessImageNameW(IntPtr h, int flags, StringBuilder name, ref int size);
86
+ }
87
+
88
+ internal static class Program
89
+ {
90
+ const int MaxStdin = 32768, MaxFrame = 65536, MaxControlFrames = 1024, Chunk = 16384, MaxArgs = 64, MaxArgvBytes = 16384, MaxEnv = 8, MaxPath = 1024, MaxEnvValue = 2048;
91
+ const uint CREATE_SUSPENDED = 0x4, CREATE_UNICODE_ENVIRONMENT = 0x400, EXTENDED_STARTUPINFO_PRESENT = 0x80000, CREATE_NO_WINDOW = 0x08000000;
92
+ const uint STILL_ACTIVE = 259, WAIT_TIMEOUT = 0x102;
93
+ static readonly UTF8Encoding Strict = new UTF8Encoding(false, true);
94
+ static Stream outStream;
95
+ static readonly object outLock = new object();
96
+ static readonly object stateLock = new object();
97
+ static readonly object termLock = new object();
98
+ static IntPtr job = IntPtr.Zero, hProc = IntPtr.Zero, hThread = IntPtr.Zero;
99
+ static bool cancelFlag, ownerGone, protocolViolation, running, cancelEffective;
100
+ static string cancelReason = "";
101
+ static TermResult term;
102
+ static string stdinStatus = "none"; static uint stdinWritten, stdinErr; static bool stdinEof;
103
+ #if TESTHOOKS
104
+ static string injectHook = "";
105
+ static IntPtr Hook(string name, IntPtr real) { return injectHook == name ? new IntPtr(-1) : real; }
106
+ #else
107
+ static IntPtr Hook(string name, IntPtr real) { return real; }
108
+ #endif
109
+
110
+ sealed class TermResult { public uint Total, Snapshot, ActiveAfter; public bool AllGone; public long WaitMs; public string Reason; }
111
+
112
+ // ---------- framing ----------
113
+ static void Send(byte type, byte[] payload, int off, int len)
114
+ {
115
+ lock (outLock)
116
+ {
117
+ try
118
+ {
119
+ byte[] h = new byte[8]; h[0] = (byte)'M'; h[1] = (byte)'C'; h[2] = 1; h[3] = type;
120
+ h[4] = (byte)(len & 255); h[5] = (byte)((len >> 8) & 255); h[6] = (byte)((len >> 16) & 255); h[7] = (byte)((len >> 24) & 255);
121
+ outStream.Write(h, 0, 8); if (len > 0) outStream.Write(payload, off, len); outStream.Flush();
122
+ }
123
+ catch (IOException) { OwnerLost("stdout-closed"); }
124
+ }
125
+ }
126
+ static void SendText(byte type, string text) { byte[] b = Encoding.UTF8.GetBytes(text); Send(type, b, 0, b.Length); }
127
+
128
+ static bool ReadExact(Stream s, byte[] buf, int n, bool allowCleanEof)
129
+ {
130
+ int got = 0;
131
+ while (got < n) { int r = s.Read(buf, got, n - got); if (r <= 0) { if (got == 0 && allowCleanEof) return false; throw new Fail("FRAME_TRUNCATED", 0); } got += r; }
132
+ return true;
133
+ }
134
+ // returns false on clean EOF at a frame boundary
135
+ static bool ReadFrame(Stream s, out byte type, out byte[] payload)
136
+ {
137
+ type = 0; payload = null; byte[] h = new byte[8];
138
+ if (!ReadExact(s, h, 8, true)) return false;
139
+ if (h[0] != (byte)'M' || h[1] != (byte)'C') throw new Fail("BAD_MAGIC", 0);
140
+ if (h[2] != 1) throw new Fail("BAD_VERSION", 0);
141
+ long len = (long)h[4] | ((long)h[5] << 8) | ((long)h[6] << 16) | ((long)h[7] << 24);
142
+ if (len < 0 || len > MaxFrame) throw new Fail("FRAME_TOO_LARGE", 0);
143
+ type = h[3]; payload = new byte[len]; if (len > 0) ReadExact(s, payload, (int)len, false);
144
+ return true;
145
+ }
146
+
147
+ // ---------- request ----------
148
+ sealed class Request { public byte[] Stdin; public string StdinSha; public bool Restricted; public string Exe, Sha, Cwd; public List<string> Args = new List<string>(); public List<string[]> Env = new List<string[]>(); }
149
+
150
+ static string Clean(byte[] b, int max)
151
+ {
152
+ string s;
153
+ try { s = Strict.GetString(b); } catch (ArgumentException) { throw new Fail("REQUEST_INVALID", 0); }
154
+ if (s.Length > max) throw new Fail("REQUEST_INVALID", 0);
155
+ foreach (char c in s) if (c < 0x20 || (c >= 0x7f && c <= 0x9f)) throw new Fail("REQUEST_INVALID", 0);
156
+ return s;
157
+ }
158
+ static string AbsPath(string p)
159
+ {
160
+ // Drive-letter form only; no '/', no ':' after the drive (alternate data streams), no wildcard or reserved characters.
161
+ if (p.Length == 0 || !Regex.IsMatch(p, @"^[A-Za-z]:\\[^<>:""/|?*]*$")) throw new Fail("REQUEST_INVALID", 0);
162
+ foreach (string part in p.Split('\\')) if (part == "." || part == "..") throw new Fail("REQUEST_INVALID", 0);
163
+ return p;
164
+ }
165
+ static Request Parse(byte[] p)
166
+ {
167
+ Request r = new Request(); int i = 0, argBytes = 0;
168
+ while (i < p.Length)
169
+ {
170
+ if (p.Length - i < 5) throw new Fail("REQUEST_INVALID", 0);
171
+ byte tag = p[i]; long len = (long)p[i + 1] | ((long)p[i + 2] << 8) | ((long)p[i + 3] << 16) | ((long)p[i + 4] << 24); i += 5;
172
+ if (len < 0 || len > p.Length - i) throw new Fail("REQUEST_INVALID", 0);
173
+ byte[] v = new byte[len]; Buffer.BlockCopy(p, i, v, 0, (int)len); i += (int)len;
174
+ switch (tag)
175
+ {
176
+ case 1: if (r.Exe != null) throw new Fail("REQUEST_INVALID", 0); r.Exe = AbsPath(Clean(v, MaxPath)); break;
177
+ case 2: if (r.Sha != null) throw new Fail("REQUEST_INVALID", 0); r.Sha = Clean(v, 64); if (!Regex.IsMatch(r.Sha, "^[0-9a-fA-F]{64}$")) throw new Fail("REQUEST_INVALID", 0); break;
178
+ case 3: if (r.Cwd != null) throw new Fail("REQUEST_INVALID", 0); r.Cwd = AbsPath(Clean(v, MaxPath)); break;
179
+ case 4:
180
+ if (r.Args.Count >= MaxArgs) throw new Fail("REQUEST_INVALID", 0);
181
+ string a = Clean(v, MaxArgvBytes); argBytes += Encoding.UTF8.GetByteCount(a) + 1; if (argBytes > MaxArgvBytes) throw new Fail("REQUEST_INVALID", 0);
182
+ r.Args.Add(a); break;
183
+ case 5:
184
+ if (r.Env.Count >= MaxEnv) throw new Fail("REQUEST_INVALID", 0);
185
+ string kv = Clean(v, MaxEnvValue + 64); int eq = kv.IndexOf('=');
186
+ if (eq < 1 || !Regex.IsMatch(kv.Substring(0, eq), "^[A-Za-z_][A-Za-z0-9_]*$") || kv.Length - eq - 1 > MaxEnvValue || kv.Length - eq - 1 < 1) throw new Fail("REQUEST_INVALID", 0);
187
+ foreach (string[] e in r.Env) if (string.Equals(e[0], kv.Substring(0, eq), StringComparison.OrdinalIgnoreCase)) throw new Fail("REQUEST_INVALID", 0);
188
+ r.Env.Add(new string[] { kv.Substring(0, eq), kv.Substring(eq + 1) }); break;
189
+ case 7:
190
+ if (r.Stdin != null || v.Length < 1 || v.Length > MaxStdin) throw new Fail("REQUEST_INVALID", 0);
191
+ try { if (Strict.GetString(v).IndexOf('\u0000') >= 0) throw new Fail("REQUEST_INVALID", 0); } catch (ArgumentException) { throw new Fail("REQUEST_INVALID", 0); }
192
+ r.Stdin = v; break;
193
+ case 8:
194
+ if (r.StdinSha != null) throw new Fail("REQUEST_INVALID", 0);
195
+ r.StdinSha = Clean(v, 64); if (!Regex.IsMatch(r.StdinSha, "^[0-9a-fA-F]{64}$")) throw new Fail("REQUEST_INVALID", 0); break;
196
+ case 6:
197
+ if (r.Restricted) throw new Fail("REQUEST_INVALID", 0);
198
+ if (Clean(v, 64) != "RESTRICTED_LOW_INTEGRITY") throw new Fail("REQUEST_INVALID", 0);
199
+ r.Restricted = true; break;
200
+ #if TESTHOOKS
201
+ case 9: injectHook = Clean(v, 64); break;
202
+ #endif
203
+ default: throw new Fail("REQUEST_INVALID", 0);
204
+ }
205
+ }
206
+ if (r.Exe == null || r.Sha == null || r.Cwd == null) throw new Fail("REQUEST_INVALID", 0);
207
+ if ((r.Stdin == null) != (r.StdinSha == null)) throw new Fail("REQUEST_INVALID", 0);
208
+ if (r.Stdin != null)
209
+ {
210
+ using (SHA256 sha = SHA256.Create()) if (!string.Equals(Hex(sha.ComputeHash(r.Stdin)), r.StdinSha, StringComparison.OrdinalIgnoreCase)) throw new Fail("STDIN_DIGEST_MISMATCH", 0);
211
+ }
212
+ return r;
213
+ }
214
+
215
+ // ---------- helpers ----------
216
+ static void AppendArg(StringBuilder sb, string a)
217
+ {
218
+ if (a.Length > 0 && a.IndexOfAny(new char[] { ' ', '\t', '"' }) < 0) { sb.Append(a); return; }
219
+ sb.Append('"'); int bs = 0;
220
+ foreach (char c in a)
221
+ {
222
+ if (c == '\\') bs++;
223
+ else if (c == '"') { sb.Append('\\', bs * 2 + 1); sb.Append('"'); bs = 0; }
224
+ else { sb.Append('\\', bs); bs = 0; sb.Append(c); }
225
+ }
226
+ sb.Append('\\', bs * 2); sb.Append('"');
227
+ }
228
+ static string Hex(byte[] b) { StringBuilder sb = new StringBuilder(); foreach (byte x in b) sb.Append(x.ToString("x2")); return sb.ToString(); }
229
+ static string HashStream(Stream s) { using (SHA256 sha = SHA256.Create()) return Hex(sha.ComputeHash(s)); }
230
+ static ulong CreateTime(int pid, out bool ok)
231
+ {
232
+ ok = false; IntPtr h = W.OpenProcess(0x1000, false, pid); if (h == IntPtr.Zero) return 0;
233
+ W.FILETIME c, e, k, u; bool r = W.GetProcessTimes(h, out c, out e, out k, out u); W.CloseHandle(h); ok = r;
234
+ return r ? (((ulong)c.hi << 32) | c.lo) : 0;
235
+ }
236
+ static bool Alive(int pid, ulong ft)
237
+ {
238
+ IntPtr h = W.OpenProcess(0x1000, false, pid); if (h == IntPtr.Zero) return false;
239
+ W.FILETIME c, e, k, u; bool ok = W.GetProcessTimes(h, out c, out e, out k, out u); uint code; bool g = W.GetExitCodeProcess(h, out code); W.CloseHandle(h);
240
+ return ok && g && code == STILL_ACTIVE && ((((ulong)c.hi << 32) | c.lo) == ft);
241
+ }
242
+ static List<int> JobPids()
243
+ {
244
+ int len = 8 + 8 * 512; IntPtr buf = Marshal.AllocHGlobal(len); List<int> l = new List<int>();
245
+ if (W.QueryInformationJobObject(job, 3, buf, len, IntPtr.Zero)) { int n = Marshal.ReadInt32(buf, 4); for (int i = 0; i < n; i++) l.Add((int)Marshal.ReadInt64(buf, 8 + i * 8)); }
246
+ Marshal.FreeHGlobal(buf); return l;
247
+ }
248
+ static W.ACCOUNTING Accounting() { W.ACCOUNTING a = new W.ACCOUNTING(); if (!W.QueryInformationJobObject(job, 1, ref a, Marshal.SizeOf(a), IntPtr.Zero)) { a.ActiveProcesses = 0xFFFFFFFF; a.TotalProcesses = 0xFFFFFFFF; } return a; }
249
+
250
+ // Snapshot every Job member with PID + creation time, terminate the Job, then poll until every one is gone.
251
+ static TermResult Terminate(string why)
252
+ {
253
+ lock (termLock)
254
+ {
255
+ if (term != null) return term;
256
+ TermResult r = new TermResult(); r.Reason = why;
257
+ List<KeyValuePair<int, ulong>> ids = new List<KeyValuePair<int, ulong>>();
258
+ foreach (int pid in JobPids()) { bool ok; ulong ft = CreateTime(pid, out ok); if (ok) ids.Add(new KeyValuePair<int, ulong>(pid, ft)); }
259
+ W.ACCOUNTING a = Accounting(); r.Total = a.TotalProcesses; r.Snapshot = (uint)ids.Count;
260
+ bool killed = W.TerminateJobObject(job, 1);
261
+ System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew(); bool gone = false;
262
+ while (sw.ElapsedMilliseconds < 5000)
263
+ {
264
+ gone = true; foreach (KeyValuePair<int, ulong> kv in ids) if (Alive(kv.Key, kv.Value)) { gone = false; break; }
265
+ if (gone && Accounting().ActiveProcesses == 0) break; gone = false; Thread.Sleep(20);
266
+ }
267
+ r.ActiveAfter = Accounting().ActiveProcesses; r.WaitMs = sw.ElapsedMilliseconds;
268
+ r.AllGone = killed && gone && r.ActiveAfter == 0;
269
+ term = r; return r;
270
+ }
271
+ }
272
+ static void OwnerLost(string why)
273
+ {
274
+ lock (stateLock) { ownerGone = true; cancelFlag = true; if (cancelReason.Length == 0) cancelReason = why; }
275
+ if (running && job != IntPtr.Zero) Terminate(why);
276
+ }
277
+
278
+ static void Reader(object o)
279
+ {
280
+ object[] st = (object[])o; IntPtr h = (IntPtr)st[0]; byte type = (byte)st[1]; byte[] buf = new byte[Chunk]; uint n;
281
+ while (W.ReadFile(h, buf, (uint)buf.Length, out n, IntPtr.Zero) && n > 0) Send(type, buf, 0, (int)n); // blocking write = backpressure
282
+ }
283
+
284
+ // Writes the approved bytes once to the private stdin pipe, then closes it (EOF). Blocks under backpressure; a dead reader ends it.
285
+ static void StdinWriter(object o)
286
+ {
287
+ object[] st = (object[])o; IntPtr h = (IntPtr)st[0]; byte[] data = (byte[])st[1]; uint total = 0; string status = "delivered"; uint err = 0;
288
+ while (total < (uint)data.Length)
289
+ {
290
+ byte[] buf = data; uint n; byte[] chunk = new byte[Math.Min(data.Length - (int)total, 1024)]; Buffer.BlockCopy(data, (int)total, chunk, 0, chunk.Length); buf = chunk;
291
+ if (!W.WriteFile(h, buf, (uint)chunk.Length, out n, IntPtr.Zero)) { err = (uint)Marshal.GetLastWin32Error(); status = (err == 109 || err == 232) ? "early_exit" : "error"; break; }
292
+ if (n == 0) { status = "error"; break; }
293
+ total += n;
294
+ }
295
+ bool closed = W.CloseHandle(h);
296
+ if (status == "delivered" && !closed) status = "error";
297
+ lock (stateLock) { stdinStatus = status; stdinWritten = total; stdinErr = err; stdinEof = closed && status == "delivered"; }
298
+ }
299
+
300
+ static void Control(object o)
301
+ {
302
+ Stream sin = (Stream)o; int count = 0;
303
+ try
304
+ {
305
+ for (;;)
306
+ {
307
+ byte t; byte[] p;
308
+ if (!ReadFrame(sin, out t, out p)) { OwnerLost("owner-eof"); return; }
309
+ if (++count > MaxControlFrames) throw new Fail("TOO_MANY_FRAMES", 0);
310
+ if (t != (byte)'C' || p.Length != 0) throw new Fail("UNKNOWN_FRAME", 0);
311
+ bool doKill;
312
+ lock (stateLock) { cancelFlag = true; if (cancelReason.Length == 0) cancelReason = "cancel"; doKill = running; }
313
+ if (doKill) { if (W.WaitForSingleObject(hProc, 0) == WAIT_TIMEOUT) cancelEffective = true; Terminate("cancel"); }
314
+ }
315
+ }
316
+ catch (Fail) { lock (stateLock) { protocolViolation = true; } OwnerLost("protocol-violation"); }
317
+ catch (IOException) { OwnerLost("owner-io"); }
318
+ }
319
+
320
+ static int FailOut(string code, int win32)
321
+ {
322
+ SendText((byte)'F', "code=" + code + "\nwin32=" + win32 + "\n"); SendText((byte)'Z', "ok=0\n"); return 1;
323
+ }
324
+
325
+ // ---------- main ----------
326
+ static int Main(string[] args)
327
+ {
328
+ #if TESTHOOKS
329
+ if (args.Length > 0) return TestModes.Run(args);
330
+ #endif
331
+ if (args.Length != 0) return 2;
332
+ outStream = Console.OpenStandardOutput(); Stream sin = Console.OpenStandardInput();
333
+ Request req;
334
+ try
335
+ {
336
+ byte t; byte[] p;
337
+ if (!ReadFrame(sin, out t, out p) || t != (byte)'L') return FailOut("PROTOCOL_ERROR", 0);
338
+ req = Parse(p);
339
+ }
340
+ catch (Fail f) { return FailOut(f.Code, f.Win32); }
341
+ Thread ctl = new Thread(Control); ctl.IsBackground = true; ctl.Start(sin);
342
+ int rc;
343
+ try { rc = Launch(req); }
344
+ catch (Fail f)
345
+ {
346
+ CleanupFailedLaunch();
347
+ rc = FailOut(f.Code, f.Win32);
348
+ }
349
+ if (job != IntPtr.Zero) W.CloseHandle(job);
350
+ Environment.Exit(rc); return rc;
351
+ }
352
+
353
+ static void CleanupFailedLaunch()
354
+ {
355
+ if (hProc != IntPtr.Zero && !running)
356
+ {
357
+ W.TerminateProcess(hProc, 1);
358
+ if (W.WaitForSingleObject(hProc, 3000) != 0) SendText((byte)'F', "code=CLEANUP_UNCONFIRMED\nwin32=0\n");
359
+ }
360
+ }
361
+
362
+ static int Launch(Request req)
363
+ {
364
+ FileStream hold = null;
365
+ try { hold = new FileStream(req.Exe, FileMode.Open, FileAccess.Read, FileShare.Read); }
366
+ catch (Exception) { throw new Fail("EXECUTABLE_UNREADABLE", Marshal.GetLastWin32Error()); }
367
+ using (hold)
368
+ {
369
+ if (!string.Equals(HashStream(hold), req.Sha, StringComparison.OrdinalIgnoreCase)) throw new Fail("EXECUTABLE_DIGEST_MISMATCH", 0);
370
+ SendText((byte)'H', "digestPrecheck=1\nshareMode=read-only\n");
371
+ #if TESTHOOKS
372
+ if (injectHook.StartsWith("pause-after-hold:")) Thread.Sleep(int.Parse(injectHook.Substring(17)));
373
+ #endif
374
+ IntPtr invalid = new IntPtr(-1);
375
+ job = W.CreateJobObjectW(IntPtr.Zero, null);
376
+ if (job == IntPtr.Zero) throw new Fail("JOB_CREATE_FAILED", Marshal.GetLastWin32Error());
377
+ W.EXT_LIMIT li = new W.EXT_LIMIT(); li.Basic.LimitFlags = 0x2000; // KILL_ON_JOB_CLOSE only; no BREAKAWAY_OK / SILENT_BREAKAWAY_OK
378
+ #if TESTHOOKS
379
+ IntPtr setTarget = Hook("job-set-invalid", job);
380
+ #else
381
+ IntPtr setTarget = job;
382
+ #endif
383
+ if (!W.SetInformationJobObject(setTarget, 9, ref li, Marshal.SizeOf(li))) throw new Fail("JOB_LIMIT_FAILED", Marshal.GetLastWin32Error());
384
+
385
+ W.SECURITY_ATTRIBUTES sa = new W.SECURITY_ATTRIBUTES(); sa.nLength = Marshal.SizeOf(sa); sa.bInheritHandle = 1;
386
+ IntPtr outR, outW, errR, errW;
387
+ if (!W.CreatePipe(out outR, out outW, ref sa, 0)) throw new Fail("PIPE_FAILED", Marshal.GetLastWin32Error());
388
+ if (!W.CreatePipe(out errR, out errW, ref sa, 0)) throw new Fail("PIPE_FAILED", Marshal.GetLastWin32Error());
389
+ W.SetHandleInformation(outR, 1, 0); W.SetHandleInformation(errR, 1, 0);
390
+ IntPtr nul = W.CreateFileW("NUL", 0x80000000, 3, ref sa, 3, 0x80, IntPtr.Zero);
391
+ if (nul == invalid) throw new Fail("NUL_FAILED", Marshal.GetLastWin32Error());
392
+ IntPtr inR = IntPtr.Zero, inW = IntPtr.Zero;
393
+ if (req.Stdin != null)
394
+ {
395
+ // Private stdin pipe, DEFAULT (small) buffer so a reader that stops reading really applies backpressure. The write end is not inheritable.
396
+ if (!W.CreatePipe(out inR, out inW, ref sa, 0)) throw new Fail("PIPE_FAILED", Marshal.GetLastWin32Error());
397
+ W.SetHandleInformation(inW, 1, 0);
398
+ }
399
+ IntPtr stdinHandle = inR != IntPtr.Zero ? inR : nul;
400
+
401
+ W.STARTUPINFOEX six = new W.STARTUPINFOEX(); six.si.cb = Marshal.SizeOf(typeof(W.STARTUPINFOEX));
402
+ six.si.dwFlags = 0x100; six.si.hStdInput = stdinHandle; six.si.hStdOutput = outW; six.si.hStdError = errW;
403
+ IntPtr sz = IntPtr.Zero; W.InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref sz);
404
+ IntPtr al = Marshal.AllocHGlobal(sz);
405
+ if (!W.InitializeProcThreadAttributeList(al, 1, 0, ref sz)) throw new Fail("ATTR_FAILED", Marshal.GetLastWin32Error());
406
+ IntPtr hl = Marshal.AllocHGlobal(24); Marshal.WriteIntPtr(hl, 0, stdinHandle); Marshal.WriteIntPtr(hl, 8, outW); Marshal.WriteIntPtr(hl, 16, errW);
407
+ if (!W.UpdateProcThreadAttribute(al, 0, (IntPtr)0x00020002, hl, (IntPtr)24, IntPtr.Zero, IntPtr.Zero)) throw new Fail("ATTR_FAILED", Marshal.GetLastWin32Error());
408
+ six.attrs = al;
409
+
410
+ StringBuilder cmd = new StringBuilder(); AppendArg(cmd, req.Exe); foreach (string a in req.Args) { cmd.Append(' '); AppendArg(cmd, a); }
411
+ req.Env.Sort(delegate (string[] x, string[] y) { return string.Compare(x[0], y[0], StringComparison.OrdinalIgnoreCase); });
412
+ StringBuilder env = new StringBuilder(); foreach (string[] e in req.Env) { env.Append(e[0]); env.Append('='); env.Append(e[1]); env.Append('\0'); } env.Append('\0');
413
+ IntPtr envp = Marshal.StringToHGlobalUni(env.ToString());
414
+
415
+ IntPtr rtok = IntPtr.Zero;
416
+ if (req.Restricted)
417
+ {
418
+ #if TESTHOOKS
419
+ rtok = Ident.CreateVerified(injectHook);
420
+ #else
421
+ rtok = Ident.CreateVerified("");
422
+ #endif
423
+ }
424
+ W.PROCESS_INFORMATION pi;
425
+ uint cflags = CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT | EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW;
426
+ bool ok = rtok == IntPtr.Zero
427
+ ? W.CreateProcessW(req.Exe, cmd, IntPtr.Zero, IntPtr.Zero, true, cflags, envp, req.Cwd, ref six, out pi)
428
+ : W.CreateProcessAsUserW(rtok, req.Exe, cmd, IntPtr.Zero, IntPtr.Zero, true, cflags, envp, req.Cwd, ref six, out pi);
429
+ int le = Marshal.GetLastWin32Error();
430
+ if (rtok != IntPtr.Zero) W.CloseHandle(rtok);
431
+ W.CloseHandle(outW); W.CloseHandle(errW); W.CloseHandle(nul); if (inR != IntPtr.Zero) W.CloseHandle(inR); W.DeleteProcThreadAttributeList(al);
432
+ if (!ok) throw new Fail("CREATE_PROCESS_FAILED", le);
433
+ hProc = pi.hProcess; hThread = pi.hThread;
434
+ if (req.Restricted)
435
+ {
436
+ // The CHILD's own primary token, read while it is still suspended, must be the verified restricted Low-integrity token.
437
+ IntPtr ct; if (!Ident.OpenToken(hProc, out ct)) throw new Fail("TOKEN_VERIFY_FAILED", Marshal.GetLastWin32Error());
438
+ try { Ident.Verify(ct); } finally { W.CloseHandle(ct); }
439
+ SendText((byte)'I', "identity=RESTRICTED_LOW_INTEGRITY\ntokenType=primary\nrestrictingSids=5\nintegrity=low\nprivileges=1\nchildTokenVerified=1\n");
440
+ }
441
+
442
+ // The file the OS actually mapped must still be the pinned bytes (the reported path follows renames).
443
+ StringBuilder img = new StringBuilder(1024); int isz = img.Capacity;
444
+ if (!W.QueryFullProcessImageNameW(hProc, 0, img, ref isz)) throw new Fail("IMAGE_QUERY_FAILED", Marshal.GetLastWin32Error());
445
+ if (!string.Equals(img.ToString(), req.Exe, StringComparison.OrdinalIgnoreCase)) throw new Fail("IMAGE_PATH_CHANGED", 0);
446
+ string mapped;
447
+ try { using (FileStream f2 = new FileStream(img.ToString(), FileMode.Open, FileAccess.Read, FileShare.Read)) mapped = HashStream(f2); }
448
+ catch (Exception) { throw new Fail("IMAGE_UNREADABLE", 0); }
449
+ if (!string.Equals(mapped, req.Sha, StringComparison.OrdinalIgnoreCase)) throw new Fail("IMAGE_DIGEST_MISMATCH", 0);
450
+
451
+ #if TESTHOOKS
452
+ IntPtr assignTarget = Hook("assign-invalid-job", job);
453
+ #else
454
+ IntPtr assignTarget = job;
455
+ #endif
456
+ if (!W.AssignProcessToJobObject(assignTarget, hProc)) throw new Fail("ASSIGN_FAILED", Marshal.GetLastWin32Error());
457
+ bool inJob; if (!W.IsProcessInJob(hProc, job, out inJob)) throw new Fail("JOB_MEMBERSHIP_UNCONFIRMED", Marshal.GetLastWin32Error());
458
+ if (!inJob) throw new Fail("JOB_MEMBERSHIP_UNCONFIRMED", 0);
459
+ uint activeBefore = Accounting().ActiveProcesses;
460
+
461
+ bool abortCancel; int prev;
462
+ lock (stateLock)
463
+ {
464
+ abortCancel = cancelFlag;
465
+ if (abortCancel) prev = 0;
466
+ else
467
+ {
468
+ #if TESTHOOKS
469
+ prev = W.ResumeThread(Hook("resume-invalid-thread", hThread));
470
+ #else
471
+ prev = W.ResumeThread(hThread);
472
+ #endif
473
+ if (prev == 1) running = true;
474
+ }
475
+ }
476
+ if (abortCancel) throw new Fail("CANCELLED_BEFORE_RESUME", 0);
477
+ if (prev == -1) throw new Fail("RESUME_FAILED", Marshal.GetLastWin32Error());
478
+ if (prev != 1) { Terminate("resume-anomaly"); throw new Fail("RESUME_UNEXPECTED_COUNT", prev); }
479
+
480
+ bool tok; ulong ft = CreateTime(pi.pid, out tok);
481
+ SendText((byte)'S', "pid=" + pi.pid + "\ncreateTime=" + ft + "\nassignedBeforeResume=1\ninJobConfirmed=1\nresumePrevCount=1\nactiveBeforeResume=" + activeBefore + "\nimageVerified=1\ndigestPrecheck=1\n");
482
+
483
+ Thread to = new Thread(Reader); Thread te = new Thread(Reader);
484
+ to.Start(new object[] { outR, (byte)'O' }); te.Start(new object[] { errR, (byte)'E' });
485
+ Thread tw = null;
486
+ if (req.Stdin != null) { tw = new Thread(StdinWriter); tw.Start(new object[] { inW, req.Stdin }); }
487
+
488
+ W.WaitForSingleObject(hProc, 0xFFFFFFFF);
489
+ uint code; W.GetExitCodeProcess(hProc, out code);
490
+ TermResult tr = Terminate(cancelReason.Length > 0 ? cancelReason : "root-exit"); // also removes any descendants still running
491
+ bool j1 = to.Join(5000), j2 = te.Join(5000);
492
+ if (tw != null)
493
+ {
494
+ bool jw = tw.Join(5000); string st; uint wr, er; bool eof; lock (stateLock) { st = stdinStatus; wr = stdinWritten; er = stdinErr; eof = stdinEof; }
495
+ if (!jw) { st = "error"; eof = false; }
496
+ SendText((byte)'N', "status=" + st + "\nbytesExpected=" + req.Stdin.Length + "\nbytesWritten=" + wr + "\nwin32=" + er + "\neofClosed=" + (eof ? 1 : 0) + "\n");
497
+ }
498
+ bool cancelled, owner, proto; lock (stateLock) { cancelled = cancelEffective; owner = ownerGone; proto = protocolViolation; }
499
+ SendText((byte)'X', "exitCode=" + code + "\ncancelled=" + (cancelled ? 1 : 0) + "\nownerGone=" + (owner ? 1 : 0) + "\nprotocolViolation=" + (proto ? 1 : 0) + "\nreadersJoined=" + ((j1 && j2) ? 1 : 0) + "\n");
500
+ SendText((byte)'T', "total=" + tr.Total + "\nsnapshot=" + tr.Snapshot + "\nallGone=" + (tr.AllGone ? 1 : 0) + "\nactiveAfter=" + tr.ActiveAfter + "\nwaitMs=" + tr.WaitMs + "\nreason=" + tr.Reason + "\n");
501
+ SendText((byte)'Z', "ok=1\n");
502
+ return 0;
503
+ }
504
+ }
505
+ }
506
+
507
+ // Fixed restricted-identity policy (SW-050). Nothing here is configurable by a request beyond selecting this one named identity.
508
+ internal static class Ident
509
+ {
510
+ static readonly string[] RestrictingSids = { "S-1-5-12", "S-1-5-32-545", "S-1-1-0", "S-1-5-11", "S-1-5-4" }; // RESTRICTED, Users, Everyone, Authenticated Users, Interactive
511
+ const string LowIntegrity = "S-1-16-4096";
512
+ const int SeChangeNotifyLuid = 23;
513
+ [DllImport("advapi32.dll", SetLastError = true)] static extern bool OpenProcessToken(IntPtr p, uint acc, out IntPtr tok);
514
+ [DllImport("advapi32.dll", SetLastError = true)] static extern bool CreateRestrictedToken(IntPtr existing, uint flags, uint nDis, IntPtr dis, uint nPriv, IntPtr priv, uint nRes, IntPtr res, out IntPtr nt);
515
+ [DllImport("advapi32.dll", SetLastError = true)] static extern bool GetTokenInformation(IntPtr t, int cls, IntPtr buf, int len, out int ret);
516
+ [DllImport("advapi32.dll", SetLastError = true)] static extern bool SetTokenInformation(IntPtr t, int cls, IntPtr buf, int len);
517
+ [DllImport("advapi32.dll", SetLastError = true)] static extern bool IsTokenRestricted(IntPtr t);
518
+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern bool ConvertStringSidToSidW(string s, out IntPtr sid);
519
+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern bool ConvertSidToStringSidW(IntPtr sid, out IntPtr s);
520
+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern bool ConvertStringSecurityDescriptorToSecurityDescriptorW(string s, uint rev, out IntPtr sd, out uint size);
521
+ [DllImport("advapi32.dll", SetLastError = true)] static extern bool GetSecurityDescriptorDacl(IntPtr sd, out bool present, out IntPtr acl, out bool defaulted);
522
+ [DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr p);
523
+ [DllImport("kernel32.dll")] static extern IntPtr GetCurrentProcess();
524
+
525
+ internal static bool OpenToken(IntPtr proc, out IntPtr tok) { return OpenProcessToken(proc, 0x8, out tok); }
526
+ static IntPtr Info(IntPtr tok, int cls) { int need; GetTokenInformation(tok, cls, IntPtr.Zero, 0, out need); if (need == 0) return IntPtr.Zero; IntPtr b = Marshal.AllocHGlobal(need); return GetTokenInformation(tok, cls, b, need, out need) ? b : IntPtr.Zero; }
527
+ static string SidText(IntPtr sid) { IntPtr p; if (!ConvertSidToStringSidW(sid, out p)) return "?"; string r = Marshal.PtrToStringUni(p); LocalFree(p); return r; }
528
+ static IntPtr SidOf(string s) { IntPtr sid; if (!ConvertStringSidToSidW(s, out sid)) throw new Fail("TOKEN_CREATE_FAILED", Marshal.GetLastWin32Error()); return sid; }
529
+
530
+ // Builds the token: restricted primary token from the CALLER's token, privileges removed, default DACL corrected, Low integrity; verified.
531
+ internal static IntPtr CreateVerified(string hook)
532
+ {
533
+ IntPtr self;
534
+ if (!OpenProcessToken(GetCurrentProcess(), 0x2 | 0x8 | 0x1 | 0x80, out self)) throw new Fail("TOKEN_CREATE_FAILED", Marshal.GetLastWin32Error()); // DUPLICATE|QUERY|ASSIGN_PRIMARY|ADJUST_DEFAULT
535
+ IntPtr userBuf = Info(self, 1); if (userBuf == IntPtr.Zero) throw new Fail("TOKEN_CREATE_FAILED", Marshal.GetLastWin32Error());
536
+ string user = SidText(Marshal.ReadIntPtr(userBuf));
537
+ IntPtr res = Marshal.AllocHGlobal(16 * RestrictingSids.Length);
538
+ for (int i = 0; i < RestrictingSids.Length; i++) { Marshal.WriteIntPtr(res, i * 16, SidOf(RestrictingSids[i])); Marshal.WriteInt32(res, i * 16 + 8, 0); Marshal.WriteInt32(res, i * 16 + 12, 0); }
539
+ IntPtr tok;
540
+ IntPtr source = self;
541
+ #if TESTHOOKS
542
+ if (hook == "token-create-fail") source = new IntPtr(-1);
543
+ #endif
544
+ if (!CreateRestrictedToken(source, 0x1, 0, IntPtr.Zero, 0, IntPtr.Zero, (uint)RestrictingSids.Length, res, out tok)) throw new Fail("TOKEN_CREATE_FAILED", Marshal.GetLastWin32Error()); // DISABLE_MAX_PRIVILEGE
545
+
546
+ System.Text.StringBuilder sddl = new System.Text.StringBuilder("D:");
547
+ foreach (string sid in RestrictingSids) sddl.Append("(A;;GA;;;" + sid + ")");
548
+ sddl.Append("(A;;GA;;;" + user + ")(A;;GA;;;S-1-5-18)");
549
+ IntPtr sd; uint sdSize;
550
+ if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.ToString(), 1, out sd, out sdSize)) throw new Fail("TOKEN_DACL_FAILED", Marshal.GetLastWin32Error());
551
+ bool present, defaulted; IntPtr acl; GetSecurityDescriptorDacl(sd, out present, out acl, out defaulted);
552
+ IntPtr daclBuf = Marshal.AllocHGlobal(8); Marshal.WriteIntPtr(daclBuf, acl);
553
+ IntPtr daclTarget = tok;
554
+ #if TESTHOOKS
555
+ if (hook == "token-dacl-fail") daclTarget = new IntPtr(-1);
556
+ #endif
557
+ if (!SetTokenInformation(daclTarget, 6, daclBuf, 8)) throw new Fail("TOKEN_DACL_FAILED", Marshal.GetLastWin32Error());
558
+
559
+ IntPtr lowSid = SidOf(LowIntegrity);
560
+ IntPtr label = Marshal.AllocHGlobal(16); Marshal.WriteIntPtr(label, 0, lowSid); Marshal.WriteInt32(label, 8, 0x20); Marshal.WriteInt32(label, 12, 0); // SE_GROUP_INTEGRITY
561
+ IntPtr ilTarget = tok;
562
+ #if TESTHOOKS
563
+ if (hook == "token-il-fail") ilTarget = new IntPtr(-1);
564
+ #endif
565
+ bool skipIl = false;
566
+ #if TESTHOOKS
567
+ skipIl = hook == "token-il-skip";
568
+ #endif
569
+ if (!skipIl && !SetTokenInformation(ilTarget, 25, label, 16)) throw new Fail("TOKEN_INTEGRITY_FAILED", Marshal.GetLastWin32Error());
570
+ Verify(tok); // never trust a token only because creation succeeded
571
+ return tok;
572
+ }
573
+
574
+ // Fail-closed verification of the exact expected policy. Throws TOKEN_VERIFY_FAILED with a small detail number.
575
+ internal static void Verify(IntPtr tok)
576
+ {
577
+ IntPtr b = Info(tok, 8); if (b == IntPtr.Zero || Marshal.ReadInt32(b) != 1) throw new Fail("TOKEN_VERIFY_FAILED", 1); // primary token
578
+ if (!IsTokenRestricted(tok)) throw new Fail("TOKEN_VERIFY_FAILED", 2);
579
+ b = Info(tok, 11); if (b == IntPtr.Zero || Marshal.ReadInt32(b) != RestrictingSids.Length) throw new Fail("TOKEN_VERIFY_FAILED", 3); // exactly the restricting SIDs
580
+ System.Collections.Generic.List<string> got = new System.Collections.Generic.List<string>();
581
+ for (int i = 0; i < RestrictingSids.Length; i++) got.Add(SidText(Marshal.ReadIntPtr(b, 8 + i * 16)));
582
+ foreach (string want in RestrictingSids) if (!got.Contains(want)) throw new Fail("TOKEN_VERIFY_FAILED", 4);
583
+ b = Info(tok, 25); if (b == IntPtr.Zero || SidText(Marshal.ReadIntPtr(b, 0)) != LowIntegrity) throw new Fail("TOKEN_VERIFY_FAILED", 5); // Low integrity
584
+ b = Info(tok, 3); if (b == IntPtr.Zero || Marshal.ReadInt32(b) != 1 || Marshal.ReadInt32(b, 4) != SeChangeNotifyLuid || Marshal.ReadInt32(b, 8) != 0) throw new Fail("TOKEN_VERIFY_FAILED", 6); // only SeChangeNotify
585
+ b = Info(tok, 20); if (b == IntPtr.Zero || Marshal.ReadInt32(b) != 0) throw new Fail("TOKEN_VERIFY_FAILED", 7); // not elevated
586
+ b = Info(tok, 29); if (b == IntPtr.Zero || Marshal.ReadInt32(b) != 0) throw new Fail("TOKEN_VERIFY_FAILED", 8); // not AppContainer
587
+ }
588
+ }
589
+
590
+ #if TESTHOOKS
591
+ // TEST-ONLY native fixture modes. Compiled only into the separate test-hooks build; the production build has none.
592
+ internal static class TestModes
593
+ {
594
+ public static int Run(string[] a)
595
+ {
596
+ switch (a[0])
597
+ {
598
+ case "breakaway": // breakaway <dir>
599
+ {
600
+ bool inJob; W.IsProcessInJob(W.GetCurrentProcess(), IntPtr.Zero, out inJob);
601
+ W.STARTUPINFOEX si = new W.STARTUPINFOEX(); si.si.cb = Marshal.SizeOf(typeof(W.STARTUPINFOEX)); W.PROCESS_INFORMATION pi;
602
+ string self = System.Reflection.Assembly.GetExecutingAssembly().Location;
603
+ bool ok = W.CreateProcessW(self, new StringBuilder("\"" + self + "\" sleep 3000"), IntPtr.Zero, IntPtr.Zero, false, 0x01000000 | 0x8, IntPtr.Zero, null, ref si, out pi);
604
+ int le = Marshal.GetLastWin32Error();
605
+ File.WriteAllText(Path.Combine(a[1], "breakaway.txt"), "inJob=" + inJob + " breakaway=" + (ok ? "SUCCEEDED" : "FAILED win32=" + le));
606
+ return 0;
607
+ }
608
+ case "pidtoken": return TokenTools.PidToken(a);
609
+ case "probe-escape": return TokenTools.Escape(a);
610
+ case "sleep": Thread.Sleep(int.Parse(a[1])); return 0;
611
+ case "handles": // handles <dir>: census of handle types visible to this process
612
+ {
613
+ SortedDictionary<string, int> counts = new SortedDictionary<string, int>();
614
+ for (int h = 4; h < 20000; h += 4)
615
+ {
616
+ uint fl; if (!GetHandleInformation(new IntPtr(h), out fl)) continue;
617
+ int need; IntPtr buf = Marshal.AllocHGlobal(1024); string tn = "?";
618
+ if (NtQueryObject(new IntPtr(h), 2, buf, 1024, out need) == 0) { int len = Marshal.ReadInt16(buf, 0); IntPtr sp = Marshal.ReadIntPtr(buf, 8); if (sp != IntPtr.Zero && len > 0) tn = Marshal.PtrToStringUni(sp, len / 2); }
619
+ Marshal.FreeHGlobal(buf); int c; counts.TryGetValue(tn, out c); counts[tn] = c + 1;
620
+ }
621
+ StringBuilder sb = new StringBuilder(); foreach (KeyValuePair<string, int> kv in counts) sb.Append(kv.Key + "=" + kv.Value + ";");
622
+ File.WriteAllText(Path.Combine(a[1], "handles.txt"), sb.ToString()); return 0;
623
+ }
624
+ }
625
+ return 2;
626
+ }
627
+ [DllImport("kernel32.dll", SetLastError = true)] static extern bool GetHandleInformation(IntPtr h, out uint flags);
628
+ [DllImport("ntdll.dll")] static extern int NtQueryObject(IntPtr h, int cls, IntPtr buf, int len, out int ret);
629
+ }
630
+
631
+ internal static class TokenTools
632
+ {
633
+ [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr OpenProcess(uint a, bool i, int p);
634
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
635
+ [DllImport("kernel32.dll")] static extern IntPtr GetCurrentProcess();
636
+ [DllImport("advapi32.dll", SetLastError = true)] static extern bool OpenProcessToken(IntPtr p, uint acc, out IntPtr tok);
637
+ [DllImport("advapi32.dll", SetLastError = true)] static extern bool GetTokenInformation(IntPtr t, int cls, IntPtr buf, int len, out int ret);
638
+ [DllImport("advapi32.dll", SetLastError = true)] static extern bool IsTokenRestricted(IntPtr t);
639
+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern bool ConvertSidToStringSidW(IntPtr sid, out IntPtr s);
640
+ [DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr p);
641
+ static IntPtr Info(IntPtr tok, int cls) { int need; GetTokenInformation(tok, cls, IntPtr.Zero, 0, out need); if (need == 0) return IntPtr.Zero; IntPtr b = Marshal.AllocHGlobal(need); return GetTokenInformation(tok, cls, b, need, out need) ? b : IntPtr.Zero; }
642
+ static string SidText(IntPtr sid) { IntPtr p; if (!ConvertSidToStringSidW(sid, out p)) return "?"; string r = Marshal.PtrToStringUni(p); LocalFree(p); return r; }
643
+ static string Describe(IntPtr tok)
644
+ {
645
+ StringBuilder sb = new StringBuilder(); sb.Append("restricted=" + IsTokenRestricted(tok));
646
+ IntPtr b = Info(tok, 11); sb.Append(" restrictingSids=" + (b == IntPtr.Zero ? 0 : Marshal.ReadInt32(b)));
647
+ b = Info(tok, 25); sb.Append(" integrity=" + (b == IntPtr.Zero ? "?" : SidText(Marshal.ReadIntPtr(b, 0))));
648
+ b = Info(tok, 20); sb.Append(" elevated=" + (b == IntPtr.Zero ? "?" : Marshal.ReadInt32(b).ToString()));
649
+ b = Info(tok, 3); sb.Append(" privileges=" + (b == IntPtr.Zero ? -1 : Marshal.ReadInt32(b)));
650
+ b = Info(tok, 8); sb.Append(" type=" + (b == IntPtr.Zero ? "?" : (Marshal.ReadInt32(b) == 1 ? "primary" : "impersonation")));
651
+ return sb.ToString();
652
+ }
653
+ public static int PidToken(string[] a)
654
+ {
655
+ int pid = int.Parse(a[1]); IntPtr h = OpenProcess(0x1000, false, pid);
656
+ if (h == IntPtr.Zero) { Console.WriteLine("pid=" + pid + " OPEN_FAILED win32=" + Marshal.GetLastWin32Error()); return 1; }
657
+ IntPtr tok; if (!OpenProcessToken(h, 0x8, out tok)) { Console.WriteLine("pid=" + pid + " TOKEN_OPEN_FAILED win32=" + Marshal.GetLastWin32Error()); CloseHandle(h); return 1; }
658
+ Console.WriteLine("pid=" + pid + " " + Describe(tok)); CloseHandle(tok); CloseHandle(h); return 0;
659
+ }
660
+ // probe-escape <outfile> <pid...>: attempts to OPEN (never modify) other processes and their tokens from THIS process.
661
+ public static int Escape(string[] a)
662
+ {
663
+ StringBuilder sb = new StringBuilder(); IntPtr self; OpenProcessToken(GetCurrentProcess(), 0x8, out self); sb.AppendLine("self " + Describe(self));
664
+ string[] names = { "PROCESS_TERMINATE", "PROCESS_VM_WRITE|VM_OPERATION", "PROCESS_CREATE_THREAD", "PROCESS_QUERY_LIMITED_INFORMATION" }; uint[] masks = { 0x1, 0x20 | 0x8, 0x2, 0x1000 };
665
+ for (int k = 2; k < a.Length; k++)
666
+ {
667
+ int pid = int.Parse(a[k]);
668
+ for (int i = 0; i < masks.Length; i++) { IntPtr h = OpenProcess(masks[i], false, pid); sb.AppendLine("pid=" + pid + " open " + names[i] + " => " + (h == IntPtr.Zero ? "DENIED win32=" + Marshal.GetLastWin32Error() : "OPENED")); if (h != IntPtr.Zero) CloseHandle(h); }
669
+ IntPtr q = OpenProcess(0x1000, false, pid);
670
+ if (q != IntPtr.Zero) { IntPtr t; bool ok = OpenProcessToken(q, 0x2 | 0x8, out t); sb.AppendLine("pid=" + pid + " OpenProcessToken(DUPLICATE|QUERY) => " + (ok ? "OPENED" : "DENIED win32=" + Marshal.GetLastWin32Error())); if (ok) CloseHandle(t); CloseHandle(q); }
671
+ }
672
+ File.WriteAllText(a[1], sb.ToString()); return 0;
673
+ }
674
+ }
675
+ #endif
676
+ }