using System.ComponentModel; using System.Diagnostics; using System.IO.Pipes; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.AccessControl; using System.Security.Principal; using System.Text; using Microsoft.Win32.SafeHandles; namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess; /// /// Starts a ScriptWorker under a restricted token for Scripting:Worker:Identity (lmxopcua#780 design §6, owner /// decision §14 #5; see for why a restricted token and not a logon). The launch: /// /// derives a primary token from the host's with DISABLE_MAX_PRIVILEGE and the restricting SIDs /// () — no password, no SeAssignPrimaryTokenPrivilege /// (a restricted copy of the caller's own token does not need it); /// sets the token's default DACL, and the token object's own DACL, to the host account, SYSTEM, the worker /// identity and RESTRICTED, so the worker can open its own token and process, the worker's /// process object stays openable by the host (kill, exit code, the Job Object) and objects the worker creates are /// reachable by both; /// creates the process suspended with CreateProcessAsUserW, inheriting exactly its stdout and /// stderr pipe ends (PROC_THREAD_ATTRIBUTE_HANDLE_LIST), with the allow-listed environment block; /// assigns it to the worker's Job Object before its first instruction runs, then resumes it. /// /// [SupportedOSPlatform("windows")] internal static class RestrictedWorkerLauncher { /// A started worker: its process, its job and the two stdio readers. internal sealed class Launched : IDisposable { private readonly AnonymousPipeServerStream _stdout; private readonly AnonymousPipeServerStream _stderr; internal Launched(Process process, WindowsJobObject job, AnonymousPipeServerStream stdout, AnonymousPipeServerStream stderr) { Process = process; Job = job; _stdout = stdout; _stderr = stderr; } /// The worker process (opened by pid while the creation handle was still held, so it cannot be a reused pid). public Process Process { get; } /// The worker's Job Object (kill on close). public WindowsJobObject Job { get; } /// Closes the stdio readers (the process and job are owned by the caller). public void Dispose() { _stdout.Dispose(); _stderr.Dispose(); } } /// Starts under a restricted token for . /// What to run: file name, argument list, working directory and the final environment. /// The worker identity's SID string. /// The Job Object's per-process commit limit. /// Receives each stdout line. /// Receives each stderr line. /// The started worker. public static Launched Start(ProcessStartInfo psi, string workerSid, long processMemoryLimitBytes, Action onStdout, Action onStderr) { ArgumentNullException.ThrowIfNull(psi); GrantSessionObjects(workerSid); using var token = CreateWorkerToken(workerSid); var stdout = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable); var stderr = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable); WindowsJobObject? job = null; PROCESS_INFORMATION pi = default; var attributeList = IntPtr.Zero; var handleList = IntPtr.Zero; var environment = IntPtr.Zero; try { var inherit = new[] { stdout.ClientSafePipeHandle.DangerousGetHandle(), stderr.ClientSafePipeHandle.DangerousGetHandle() }; handleList = Marshal.AllocHGlobal(IntPtr.Size * inherit.Length); Marshal.Copy(inherit, 0, handleList, inherit.Length); var size = IntPtr.Zero; InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref size); attributeList = Marshal.AllocHGlobal(size); if (!InitializeProcThreadAttributeList(attributeList, 1, 0, ref size)) throw new Win32Exception(Marshal.GetLastWin32Error(), "InitializeProcThreadAttributeList failed"); if (!UpdateProcThreadAttribute(attributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handleList, (IntPtr)(IntPtr.Size * inherit.Length), IntPtr.Zero, IntPtr.Zero)) throw new Win32Exception(Marshal.GetLastWin32Error(), "UpdateProcThreadAttribute(HANDLE_LIST) failed"); var si = new STARTUPINFOEX { StartupInfo = new STARTUPINFO { cb = Marshal.SizeOf(), dwFlags = STARTF_USESTDHANDLES, hStdInput = IntPtr.Zero, hStdOutput = inherit[0], hStdError = inherit[1], }, lpAttributeList = attributeList, }; var commandLine = new StringBuilder(WindowsProcessText.BuildCommandLine(psi.FileName, psi.ArgumentList)); environment = Marshal.StringToHGlobalUni(WindowsProcessText.BuildEnvironmentBlock(psi.Environment)); const uint flags = CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT; if (!CreateProcessAsUserW(token, psi.FileName, commandLine, IntPtr.Zero, IntPtr.Zero, bInheritHandles: true, flags, environment, string.IsNullOrEmpty(psi.WorkingDirectory) ? null : psi.WorkingDirectory, ref si, out pi)) throw new Win32Exception(Marshal.GetLastWin32Error(), $"CreateProcessAsUser for '{psi.FileName}' failed"); // The child owns its ends now. stdout.DisposeLocalCopyOfClientHandle(); stderr.DisposeLocalCopyOfClientHandle(); // Into the job before it runs a single instruction: the kill-on-close and process-count limits hold from birth. job = WindowsJobObject.Assign(pi.hProcess, processMemoryLimitBytes); // Opened while the creation handle is still held, so the pid cannot have been reused; .Handle caches a handle // the Process object uses from here on (the token's default DACL grants the host account). var process = Process.GetProcessById(pi.dwProcessId); _ = process.Handle; process.EnableRaisingEvents = true; if (ResumeThread(pi.hThread) == uint.MaxValue) { var error = Marshal.GetLastWin32Error(); process.Dispose(); throw new Win32Exception(error, "ResumeThread failed"); } Pump(stdout, onStdout); Pump(stderr, onStderr); return new Launched(process, job, stdout, stderr); } catch { if (pi.hProcess != IntPtr.Zero) TerminateProcess(pi.hProcess, 1); job?.Dispose(); stdout.Dispose(); stderr.Dispose(); throw; } finally { if (pi.hThread != IntPtr.Zero) CloseHandle(pi.hThread); if (pi.hProcess != IntPtr.Zero) CloseHandle(pi.hProcess); if (attributeList != IntPtr.Zero) { DeleteProcThreadAttributeList(attributeList); Marshal.FreeHGlobal(attributeList); } if (handleList != IntPtr.Zero) Marshal.FreeHGlobal(handleList); if (environment != IntPtr.Zero) Marshal.FreeHGlobal(environment); } } /// /// The worker's primary token: the host's, with every privilege but SeChangeNotifyPrivilege removed, the /// restricting SIDs of , and a default DACL of host account + SYSTEM + worker identity. /// /// The worker identity's SID string. /// The token (owned by the caller). internal static SafeAccessTokenHandle CreateWorkerToken(string workerSid) { if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_ADJUST_DEFAULT | READ_CONTROL | WRITE_DAC, out var processToken)) throw new Win32Exception(Marshal.GetLastWin32Error(), "OpenProcessToken failed"); using (processToken) { // Not the logon SID: the host's own process DACL grants it PROCESS_VM_READ (measured on windev), so a worker // holding it could read the host's memory. var restricting = ScriptWorkerIdentity.RestrictingSids(workerSid).Select(s => new SecurityIdentifier(s)).ToArray(); var pinned = new List(); var entries = IntPtr.Zero; try { var entrySize = Marshal.SizeOf(); entries = Marshal.AllocHGlobal(entrySize * restricting.Length); for (var i = 0; i < restricting.Length; i++) { var bytes = new byte[restricting[i].BinaryLength]; restricting[i].GetBinaryForm(bytes, 0); var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); pinned.Add(handle); Marshal.StructureToPtr(new SID_AND_ATTRIBUTES { Sid = handle.AddrOfPinnedObject(), Attributes = 0 }, entries + (i * entrySize), fDeleteOld: false); } if (!CreateRestrictedToken(processToken, DISABLE_MAX_PRIVILEGE, 0, IntPtr.Zero, 0, IntPtr.Zero, (uint)restricting.Length, entries, out var restricted)) throw new Win32Exception(Marshal.GetLastWin32Error(), "CreateRestrictedToken failed"); try { SetDefaultDacl(restricted, new SecurityIdentifier(workerSid)); return restricted; } catch { restricted.Dispose(); throw; } } finally { foreach (var handle in pinned) handle.Free(); if (entries != IntPtr.Zero) Marshal.FreeHGlobal(entries); } } } private static readonly object SessionGrantLock = new(); private static readonly HashSet SessionGranted = new(StringComparer.Ordinal); /// /// Adds the worker identity to the DACL of the host's window station and desktop (once per process and identity). /// USER32's DllMain connects the process to them, and the runtime imports USER32, so a worker whose restricting SIDs /// have no access there fails to load coreclr.dll (ERROR_DLL_INIT_FAILED, measured on windev). The /// logon SID, which those objects normally grant, is deliberately NOT a restricting SID (the host's process DACL /// gives it PROCESS_VM_READ). The grant is to the identity only and lives on the session's kernel objects: /// it ends with the host's session and changes nothing persistent. /// /// The worker identity's SID string. internal static void GrantSessionObjects(string workerSid) { lock (SessionGrantLock) { if (!SessionGranted.Add(workerSid)) return; try { var sid = new SecurityIdentifier(workerSid); AddAllowAce(GetProcessWindowStation(), sid, WindowStationRights); AddAllowAce(GetThreadDesktop(GetCurrentThreadId()), sid, DesktopRights); } catch { SessionGranted.Remove(workerSid); throw; } } } /// The rights the worker identity gets on the window station: enumerate, read attributes, global atoms. internal const int WindowStationRights = 0x0001 | 0x0002 | 0x0020 | 0x0100 | 0x00020000; /// The rights the worker identity gets on the desktop: read objects, create windows (USER32 init), enumerate. internal const int DesktopRights = 0x0001 | 0x0002 | 0x0040 | 0x00020000; private static void AddAllowAce(IntPtr handle, SecurityIdentifier sid, int mask) { if (handle == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error(), "no window station / desktop handle"); var error = GetSecurityInfoRaw(handle, SE_WINDOW_OBJECT, DACL_SECURITY_INFORMATION, IntPtr.Zero, IntPtr.Zero, out var daclPtr, IntPtr.Zero, out var sd); if (error != 0) throw new Win32Exception((int)error, "GetSecurityInfo(window object) failed"); try { RawAcl acl; if (daclPtr == IntPtr.Zero) return; // a NULL DACL already admits everyone var size = Marshal.ReadInt16(daclPtr + 2); var bytes = new byte[size]; Marshal.Copy(daclPtr, bytes, 0, size); acl = new RawAcl(bytes, 0); foreach (var ace in acl.OfType()) if (ace.SecurityIdentifier == sid && ace.AceQualifier == AceQualifier.AccessAllowed && (ace.AccessMask & mask) == mask) return; acl.InsertAce(acl.Count, new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, mask, sid, false, null)); var updated = new byte[acl.BinaryLength]; acl.GetBinaryForm(updated, 0); var pinned = GCHandle.Alloc(updated, GCHandleType.Pinned); try { error = SetSecurityInfoRaw(handle, SE_WINDOW_OBJECT, DACL_SECURITY_INFORMATION, IntPtr.Zero, IntPtr.Zero, pinned.AddrOfPinnedObject(), IntPtr.Zero); if (error != 0) throw new Win32Exception((int)error, "SetSecurityInfo(window object) failed"); } finally { pinned.Free(); } } finally { LocalFree(sd); } } /// The SDDL of the default DACL a worker token carries (tests). /// The host account. /// The worker identity. /// The raw ACL. internal static RawAcl DefaultDacl(SecurityIdentifier hostUser, SecurityIdentifier worker) { var acl = new RawAcl(GenericAcl.AclRevision, 3); var system = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null); var restricted = new SecurityIdentifier(ScriptWorkerIdentity.RestrictedSid); foreach (var sid in new[] { hostUser, system, worker, restricted }.Distinct()) acl.InsertAce(acl.Count, new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, GENERIC_ALL, sid, false, null)); return acl; } private static void SetDefaultDacl(SafeAccessTokenHandle token, SecurityIdentifier worker) { using var identity = WindowsIdentity.GetCurrent(); var acl = DefaultDacl(identity.User ?? throw new InvalidOperationException("the host token has no user"), worker); var bytes = new byte[acl.BinaryLength]; acl.GetBinaryForm(bytes, 0); var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { var info = new TOKEN_DEFAULT_DACL { DefaultDacl = handle.AddrOfPinnedObject() }; if (!SetTokenInformation(token, TokenDefaultDacl, ref info, (uint)Marshal.SizeOf())) throw new Win32Exception(Marshal.GetLastWin32Error(), "SetTokenInformation(TokenDefaultDacl) failed"); // The token object itself: its DACL came from the host's default DACL, which no restricting SID passes, so the // worker could not open its own token and the loader fails (coreclr.dll, ERROR_DLL_INIT_FAILED, on windev). var error = SetSecurityInfo(token, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, IntPtr.Zero, IntPtr.Zero, handle.AddrOfPinnedObject(), IntPtr.Zero); if (error != 0) throw new Win32Exception((int)error, "SetSecurityInfo(token DACL) failed"); } finally { handle.Free(); } } /// /// Gives the worker identity Modify on its per-launch working directory: protected, host account + SYSTEM full /// control, worker identity modify. Its temp files go there (TEMP/TMP point at it). /// /// The working directory the host created. /// The worker identity's SID string. public static void GrantWorkDirectory(string directory, string workerSid) { using var identity = WindowsIdentity.GetCurrent(); var security = new DirectorySecurity(); security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); const InheritanceFlags inherit = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit; var principals = new List { new(WellKnownSidType.LocalSystemSid, null) }; if (identity.User is { } user) principals.Add(user); if (identity.Owner is { } owner && !principals.Contains(owner)) principals.Add(owner); foreach (var principal in principals) security.AddAccessRule(new FileSystemAccessRule(principal, FileSystemRights.FullControl, inherit, PropagationFlags.None, AccessControlType.Allow)); security.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(workerSid), FileSystemRights.Modify | FileSystemRights.Synchronize, inherit, PropagationFlags.None, AccessControlType.Allow)); new DirectoryInfo(directory).SetAccessControl(security); } private static void Pump(AnonymousPipeServerStream stream, Action onLine) { var thread = new Thread(() => { try { using var reader = new StreamReader(stream, Encoding.UTF8); while (reader.ReadLine() is { } line) onLine(line); } catch (Exception ex) when (ex is IOException or ObjectDisposedException) { // The worker is gone or the host is stopping. } }) { IsBackground = true, Name = "ScriptWorker.Stdio" }; thread.Start(); } private const uint TOKEN_DUPLICATE = 0x0002; private const uint TOKEN_ASSIGN_PRIMARY = 0x0001; private const uint TOKEN_QUERY = 0x0008; private const uint TOKEN_ADJUST_DEFAULT = 0x0080; private const uint READ_CONTROL = 0x00020000; private const uint WRITE_DAC = 0x00040000; // the restricted token inherits these rights: its own DACL is rewritten private const uint DISABLE_MAX_PRIVILEGE = 0x1; private const int TokenDefaultDacl = 6; private const int SE_KERNEL_OBJECT = 6; private const int SE_WINDOW_OBJECT = 7; private const uint DACL_SECURITY_INFORMATION = 0x4; private const int GENERIC_ALL = 0x10000000; private const int STARTF_USESTDHANDLES = 0x00000100; private const uint CREATE_SUSPENDED = 0x00000004; private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400; private const uint CREATE_NO_WINDOW = 0x08000000; private const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000; private static readonly IntPtr PROC_THREAD_ATTRIBUTE_HANDLE_LIST = (IntPtr)0x00020002; [StructLayout(LayoutKind.Sequential)] private struct SID_AND_ATTRIBUTES { public IntPtr Sid; public uint Attributes; } [StructLayout(LayoutKind.Sequential)] private struct TOKEN_DEFAULT_DACL { public IntPtr DefaultDacl; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct STARTUPINFO { public int cb; public string? lpReserved; public string? lpDesktop; public string? lpTitle; public int dwX; public int dwY; public int dwXSize; public int dwYSize; public int dwXCountChars; public int dwYCountChars; public int dwFillAttribute; public int dwFlags; public short wShowWindow; public short cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } [StructLayout(LayoutKind.Sequential)] private struct STARTUPINFOEX { public STARTUPINFO StartupInfo; public IntPtr lpAttributeList; } [StructLayout(LayoutKind.Sequential)] private struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public int dwProcessId; public int dwThreadId; } #pragma warning disable SYSLIB1054 // DllImport kept, as in WindowsJobObject: LibraryImport would need AllowUnsafeBlocks. [DllImport("kernel32.dll")] private static extern IntPtr GetCurrentProcess(); [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool OpenProcessToken(IntPtr process, uint desiredAccess, out SafeAccessTokenHandle token); [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CreateRestrictedToken(SafeAccessTokenHandle existingToken, uint flags, uint disableSidCount, IntPtr sidsToDisable, uint deletePrivilegeCount, IntPtr privilegesToDelete, uint restrictedSidCount, IntPtr sidsToRestrict, out SafeAccessTokenHandle newToken); [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool SetTokenInformation(SafeAccessTokenHandle token, int infoClass, ref TOKEN_DEFAULT_DACL info, uint length); [DllImport("advapi32.dll", SetLastError = true)] private static extern uint SetSecurityInfo(SafeAccessTokenHandle handle, int objectType, uint securityInfo, IntPtr owner, IntPtr group, IntPtr dacl, IntPtr sacl); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool InitializeProcThreadAttributeList(IntPtr list, int count, int flags, ref IntPtr size); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool UpdateProcThreadAttribute(IntPtr list, uint flags, IntPtr attribute, IntPtr value, IntPtr size, IntPtr previousValue, IntPtr returnSize); [DllImport("kernel32.dll")] private static extern void DeleteProcThreadAttributeList(IntPtr list); [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CreateProcessAsUserW(SafeAccessTokenHandle token, string applicationName, StringBuilder commandLine, IntPtr processAttributes, IntPtr threadAttributes, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, uint creationFlags, IntPtr environment, string? currentDirectory, ref STARTUPINFOEX startupInfo, out PROCESS_INFORMATION processInformation); [DllImport("kernel32.dll", SetLastError = true)] private static extern uint ResumeThread(IntPtr thread); [DllImport("user32.dll", SetLastError = true)] private static extern IntPtr GetProcessWindowStation(); [DllImport("user32.dll", SetLastError = true)] private static extern IntPtr GetThreadDesktop(uint threadId); [DllImport("kernel32.dll")] private static extern uint GetCurrentThreadId(); [DllImport("kernel32.dll")] private static extern IntPtr LocalFree(IntPtr memory); [DllImport("advapi32.dll", EntryPoint = "GetSecurityInfo", SetLastError = true)] private static extern uint GetSecurityInfoRaw(IntPtr handle, int objectType, uint securityInfo, IntPtr owner, IntPtr group, out IntPtr dacl, IntPtr sacl, out IntPtr securityDescriptor); [DllImport("advapi32.dll", EntryPoint = "SetSecurityInfo", SetLastError = true)] private static extern uint SetSecurityInfoRaw(IntPtr handle, int objectType, uint securityInfo, IntPtr owner, IntPtr group, IntPtr dacl, IntPtr sacl); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool TerminateProcess(IntPtr process, uint exitCode); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CloseHandle(IntPtr handle); #pragma warning restore SYSLIB1054 }