2a8e2981fe
v2-ci / unit-tests (push) Has been cancelled
Owner decisions §14 #5/#6 as built (design §12.5): - Scripting:Worker:Identity (default unset, Windows only, fail-closed validation): each worker starts under a restricted token derived from the host's. Every privilege but SeChangeNotify is removed; the restricting SIDs are NT SERVICE\OtOpcUaScriptWorker's SID + Everyone + Users + RESTRICTED; the token and default DACLs are host + SYSTEM + identity + RESTRICTED. The worker is created suspended, put in its Job Object before it runs, inherits only its stdio pipes, gets an ACL'd work dir as TEMP, and runs with DOTNET_EnableDiagnostics=0. The identity is granted on the host's window station and desktop, because USER32 init made coreclr.dll fail with ERROR_DLL_INIT_FAILED on windev. The logon SID is not used because the host's process DACL gives it PROCESS_VM_READ. - The worker pipe on Windows always has an explicit protected DACL: host account + identity only. There is no owner ACE, so an elevated host's Administrators gets no access. - The worker treats access denied on its parent-pid poll as alive; the Job Object covers that case. - scripts/install/Install-ScriptWorkerIsolation.ps1 + ScriptWorkerIsolation.psm1 are idempotent and support -WhatIf, -Uninstall and -PlanOnly. They create the disabled anchor service, the PeCacheDir ACL (protected, no Users, key and markers host-only, pe\ Modify for the identity), read+execute on script-worker\, a ReadData deny on the install root, the outbound firewall block on the worker exe, and optionally the host-service env. - Tests: the dry-run harness scripts/install/tests/Test-ScriptWorkerIsolation.ps1 (46 assertions, mutation-checked); ScriptWorkerIdentityTests; WorkerIsolationTests, which cover the pipe ACL, token access and a real restricted worker running a script, all green on windev. Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
507 lines
25 KiB
C#
507 lines
25 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// Starts a ScriptWorker under a restricted token for <c>Scripting:Worker:Identity</c> (lmxopcua#780 design §6, owner
|
|
/// decision §14 #5; see <see cref="ScriptWorkerIdentity"/> for why a restricted token and not a logon). The launch:
|
|
/// <list type="number">
|
|
/// <item>derives a primary token from the host's with <c>DISABLE_MAX_PRIVILEGE</c> and the restricting SIDs
|
|
/// (<see cref="ScriptWorkerIdentity.RestrictingSids"/>) — no password, no <c>SeAssignPrimaryTokenPrivilege</c>
|
|
/// (a restricted copy of the caller's own token does not need it);</item>
|
|
/// <item>sets the token's default DACL, and the token object's own DACL, to the host account, SYSTEM, the worker
|
|
/// identity and <c>RESTRICTED</c>, 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;</item>
|
|
/// <item>creates the process <b>suspended</b> with <c>CreateProcessAsUserW</c>, inheriting exactly its stdout and
|
|
/// stderr pipe ends (<c>PROC_THREAD_ATTRIBUTE_HANDLE_LIST</c>), with the allow-listed environment block;</item>
|
|
/// <item>assigns it to the worker's Job Object <b>before</b> its first instruction runs, then resumes it.</item>
|
|
/// </list>
|
|
/// </summary>
|
|
[SupportedOSPlatform("windows")]
|
|
internal static class RestrictedWorkerLauncher
|
|
{
|
|
/// <summary>A started worker: its process, its job and the two stdio readers.</summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>The worker process (opened by pid while the creation handle was still held, so it cannot be a reused pid).</summary>
|
|
public Process Process { get; }
|
|
|
|
/// <summary>The worker's Job Object (kill on close).</summary>
|
|
public WindowsJobObject Job { get; }
|
|
|
|
/// <summary>Closes the stdio readers (the process and job are owned by the caller).</summary>
|
|
public void Dispose()
|
|
{
|
|
_stdout.Dispose();
|
|
_stderr.Dispose();
|
|
}
|
|
}
|
|
|
|
/// <summary>Starts <paramref name="psi"/> under a restricted token for <paramref name="workerSid"/>.</summary>
|
|
/// <param name="psi">What to run: file name, argument list, working directory and the final environment.</param>
|
|
/// <param name="workerSid">The worker identity's SID string.</param>
|
|
/// <param name="processMemoryLimitBytes">The Job Object's per-process commit limit.</param>
|
|
/// <param name="onStdout">Receives each stdout line.</param>
|
|
/// <param name="onStderr">Receives each stderr line.</param>
|
|
/// <returns>The started worker.</returns>
|
|
public static Launched Start(ProcessStartInfo psi, string workerSid, long processMemoryLimitBytes, Action<string> onStdout,
|
|
Action<string> 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<STARTUPINFOEX>(),
|
|
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);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The worker's primary token: the host's, with every privilege but <c>SeChangeNotifyPrivilege</c> removed, the
|
|
/// restricting SIDs of <paramref name="workerSid"/>, and a default DACL of host account + SYSTEM + worker identity.
|
|
/// </summary>
|
|
/// <param name="workerSid">The worker identity's SID string.</param>
|
|
/// <returns>The token (owned by the caller).</returns>
|
|
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<GCHandle>();
|
|
var entries = IntPtr.Zero;
|
|
try
|
|
{
|
|
var entrySize = Marshal.SizeOf<SID_AND_ATTRIBUTES>();
|
|
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<string> SessionGranted = new(StringComparer.Ordinal);
|
|
|
|
/// <summary>
|
|
/// 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 <c>coreclr.dll</c> (<c>ERROR_DLL_INIT_FAILED</c>, measured on windev). The
|
|
/// logon SID, which those objects normally grant, is deliberately NOT a restricting SID (the host's process DACL
|
|
/// gives it <c>PROCESS_VM_READ</c>). 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.
|
|
/// </summary>
|
|
/// <param name="workerSid">The worker identity's SID string.</param>
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>The rights the worker identity gets on the window station: enumerate, read attributes, global atoms.</summary>
|
|
internal const int WindowStationRights = 0x0001 | 0x0002 | 0x0020 | 0x0100 | 0x00020000;
|
|
|
|
/// <summary>The rights the worker identity gets on the desktop: read objects, create windows (USER32 init), enumerate.</summary>
|
|
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<CommonAce>())
|
|
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);
|
|
}
|
|
}
|
|
|
|
/// <summary>The SDDL of the default DACL a worker token carries (tests).</summary>
|
|
/// <param name="hostUser">The host account.</param>
|
|
/// <param name="worker">The worker identity.</param>
|
|
/// <returns>The raw ACL.</returns>
|
|
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<TOKEN_DEFAULT_DACL>()))
|
|
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();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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 (<c>TEMP</c>/<c>TMP</c> point at it).
|
|
/// </summary>
|
|
/// <param name="directory">The working directory the host created.</param>
|
|
/// <param name="workerSid">The worker identity's SID string.</param>
|
|
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<SecurityIdentifier> { 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<string> 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
|
|
}
|