169 lines
11 KiB
C#
169 lines
11 KiB
C#
|
|
// Isolated maintenance process containment, independent of VPNPlus binaries.
|
||
|
|
// Windows 10/11: create suspended, assign a non-breakaway job, then resume.
|
||
|
|
// https://learn.microsoft.com/en-us/windows/win32/procthread/job-objects
|
||
|
|
using System;
|
||
|
|
using System.ComponentModel;
|
||
|
|
using System.Diagnostics;
|
||
|
|
using System.Runtime.InteropServices;
|
||
|
|
using System.Text;
|
||
|
|
using System.Threading;
|
||
|
|
|
||
|
|
namespace UCVL.Maintenance {
|
||
|
|
public sealed class OwnedProcessGroup : IDisposable {
|
||
|
|
[StructLayout(LayoutKind.Sequential)] struct BasicLimits {
|
||
|
|
public long ProcessTime, JobTime;
|
||
|
|
public uint Flags;
|
||
|
|
public UIntPtr MinWorkingSet, MaxWorkingSet;
|
||
|
|
public uint ActiveProcessLimit;
|
||
|
|
public UIntPtr Affinity;
|
||
|
|
public uint Priority, Scheduling;
|
||
|
|
}
|
||
|
|
[StructLayout(LayoutKind.Sequential)] struct IoCounters { public ulong R, W, O, RB, WB, OB; }
|
||
|
|
[StructLayout(LayoutKind.Sequential)] struct ExtendedLimits {
|
||
|
|
public BasicLimits Basic; public IoCounters Io;
|
||
|
|
public UIntPtr ProcessMemory, JobMemory, PeakProcessMemory, PeakJobMemory;
|
||
|
|
}
|
||
|
|
[StructLayout(LayoutKind.Sequential)] struct Accounting {
|
||
|
|
public long UserTime, KernelTime, PeriodUserTime, PeriodKernelTime;
|
||
|
|
public uint PageFaults, Total, Active, Terminated;
|
||
|
|
}
|
||
|
|
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] struct Startup {
|
||
|
|
public uint Size; public string Reserved, Desktop, Title;
|
||
|
|
public uint X,Y,Width,Height,XChars,YChars,Fill,Flags;
|
||
|
|
public ushort Show, ReservedBytes; public IntPtr ReservedPtr, Input, Output, Error;
|
||
|
|
}
|
||
|
|
[StructLayout(LayoutKind.Sequential)] struct ProcessInfo { public IntPtr Process, Thread; public uint Pid, Tid; }
|
||
|
|
[StructLayout(LayoutKind.Sequential)] struct FileInformation {
|
||
|
|
public uint Attributes,CreatedLow,CreatedHigh,AccessedLow,AccessedHigh,WrittenLow,WrittenHigh;
|
||
|
|
public uint VolumeSerial,SizeHigh,SizeLow,Links,IndexHigh,IndexLow;
|
||
|
|
}
|
||
|
|
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] static extern IntPtr CreateFile(string name,uint access,uint share,IntPtr security,uint disposition,uint flags,IntPtr template);
|
||
|
|
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetFileInformationByHandle(IntPtr file,out FileInformation information);
|
||
|
|
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] static extern IntPtr CreateJobObject(IntPtr attributes,string name);
|
||
|
|
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] static extern IntPtr OpenJobObject(uint access,bool inherit,string name);
|
||
|
|
[DllImport("kernel32.dll",SetLastError=true)] static extern IntPtr OpenProcess(uint access,bool inherit,int pid);
|
||
|
|
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetProcessTimes(IntPtr process,out long created,out long exited,out long kernel,out long user);
|
||
|
|
[DllImport("kernel32.dll",SetLastError=true)] static extern bool IsProcessInJob(IntPtr process,IntPtr job,out bool member);
|
||
|
|
[DllImport("kernel32.dll",SetLastError=true)] static extern bool SetInformationJobObject(IntPtr job,int info,ref ExtendedLimits data,uint length);
|
||
|
|
[DllImport("kernel32.dll",SetLastError=true)] static extern bool QueryInformationJobObject(IntPtr job,int info,out Accounting data,uint length,IntPtr returned);
|
||
|
|
[DllImport("kernel32.dll",SetLastError=true)] static extern bool AssignProcessToJobObject(IntPtr job,IntPtr process);
|
||
|
|
[DllImport("kernel32.dll",SetLastError=true)] static extern bool TerminateJobObject(IntPtr job,uint code);
|
||
|
|
[DllImport("kernel32.dll",SetLastError=true)] static extern bool TerminateProcess(IntPtr process,uint code);
|
||
|
|
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] static extern bool CreateProcess(string application,StringBuilder command,IntPtr processAttrs,IntPtr threadAttrs,bool inherit,uint flags,IntPtr env,string directory,ref Startup startup,out ProcessInfo process);
|
||
|
|
[DllImport("kernel32.dll",SetLastError=true)] static extern uint ResumeThread(IntPtr thread);
|
||
|
|
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr process,out uint code);
|
||
|
|
[DllImport("kernel32.dll",SetLastError=true)] static extern uint WaitForSingleObject(IntPtr handle,uint milliseconds);
|
||
|
|
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
|
||
|
|
IntPtr job, process;
|
||
|
|
bool disposed;
|
||
|
|
const string JobPrefix = @"Local\UCVL-Maintenance-";
|
||
|
|
public string JobName { get; private set; }
|
||
|
|
public int ProcessId { get; private set; }
|
||
|
|
public bool RootExited { get { ThrowDisposed(); var result=WaitForSingleObject(process,0); if(result==0xffffffff) throw Error(); return result==0; } }
|
||
|
|
public uint RootExitCode { get { ThrowDisposed(); uint code; if(!GetExitCodeProcess(process,out code))throw Error(); return code; } }
|
||
|
|
public uint ActiveCount { get { ThrowDisposed(); Accounting data; if(!QueryInformationJobObject(job,1,out data,(uint)Marshal.SizeOf<Accounting>(),IntPtr.Zero))throw Error(); return data.Active; } }
|
||
|
|
static Exception Error() { return new Win32Exception(Marshal.GetLastWin32Error()); }
|
||
|
|
void ThrowDisposed() { if(disposed)throw new ObjectDisposedException(nameof(OwnedProcessGroup)); }
|
||
|
|
// A long/8.3 spelling is equivalent only when simultaneous read-only handles
|
||
|
|
// identify the same volume and file index. Equal content alone is not enough.
|
||
|
|
public static bool SameImageFile(string left,string right) {
|
||
|
|
if(String.IsNullOrWhiteSpace(left) || String.IsNullOrWhiteSpace(right) ||
|
||
|
|
left.IndexOf('\0')>=0 || right.IndexOf('\0')>=0)return false;
|
||
|
|
IntPtr invalid=new IntPtr(-1),a=invalid,b=invalid;
|
||
|
|
try {
|
||
|
|
a=CreateFile(left,0x80,7,IntPtr.Zero,3,0x80,IntPtr.Zero); // READ_ATTRIBUTES, share READ|WRITE|DELETE, OPEN_EXISTING
|
||
|
|
if(a==invalid)return false;
|
||
|
|
b=CreateFile(right,0x80,7,IntPtr.Zero,3,0x80,IntPtr.Zero);
|
||
|
|
if(b==invalid)return false;
|
||
|
|
FileInformation x,y;
|
||
|
|
if(!GetFileInformationByHandle(a,out x) || !GetFileInformationByHandle(b,out y))return false;
|
||
|
|
return (x.Attributes&0x10)==0 && (y.Attributes&0x10)==0 &&
|
||
|
|
(x.IndexHigh!=0 || x.IndexLow!=0) && x.VolumeSerial==y.VolumeSerial &&
|
||
|
|
x.IndexHigh==y.IndexHigh && x.IndexLow==y.IndexLow;
|
||
|
|
} finally {
|
||
|
|
if(b!=invalid)CloseHandle(b);
|
||
|
|
if(a!=invalid)CloseHandle(a);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
// Query only the exact named job and a held process identity. SYNCHRONIZE is
|
||
|
|
// read-only and permits an unambiguous liveness check (exit code 259 is legal).
|
||
|
|
// Neither handle grants assignment, termination, or modification rights.
|
||
|
|
public static bool VerifyMembership(string jobName,int pid,long expectedStartTicks) {
|
||
|
|
if(jobName==null || jobName.Length!=JobPrefix.Length+32 ||
|
||
|
|
!jobName.StartsWith(JobPrefix,StringComparison.Ordinal) || pid<=0 || expectedStartTicks<=0)return false;
|
||
|
|
for(int i=JobPrefix.Length;i<jobName.Length;i++) {
|
||
|
|
char c=jobName[i];if(!((c>='0' && c<='9') || (c>='a' && c<='f')))return false;
|
||
|
|
}
|
||
|
|
IntPtr observedJob=IntPtr.Zero,observedProcess=IntPtr.Zero;
|
||
|
|
try {
|
||
|
|
observedJob=OpenJobObject(0x0004,false,jobName); // JOB_OBJECT_QUERY
|
||
|
|
if(observedJob==IntPtr.Zero)return false;
|
||
|
|
observedProcess=OpenProcess(0x00101000,false,pid); // QUERY_LIMITED_INFORMATION | SYNCHRONIZE
|
||
|
|
if(observedProcess==IntPtr.Zero || WaitForSingleObject(observedProcess,0)!=258)return false;
|
||
|
|
long created,exited,kernel,user;
|
||
|
|
if(!GetProcessTimes(observedProcess,out created,out exited,out kernel,out user))return false;
|
||
|
|
if(DateTime.FromFileTimeUtc(created).Ticks!=expectedStartTicks)return false;
|
||
|
|
bool member;
|
||
|
|
return IsProcessInJob(observedProcess,observedJob,out member) && member &&
|
||
|
|
WaitForSingleObject(observedProcess,0)==258;
|
||
|
|
} catch(ArgumentOutOfRangeException) { return false; }
|
||
|
|
finally {
|
||
|
|
if(observedProcess!=IntPtr.Zero)CloseHandle(observedProcess);
|
||
|
|
if(observedJob!=IntPtr.Zero)CloseHandle(observedJob);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
// CommandLineToArgvW/CRT-compatible quoting, including trailing backslashes.
|
||
|
|
static string Quote(string value) {
|
||
|
|
if(value==null || value.IndexOf('\0')>=0)throw new ArgumentException("Invalid process argument");
|
||
|
|
// Match ProcessStartInfo.ArgumentList: NSIS GetOptions reads the raw
|
||
|
|
// command line and does not accept gratuitously quoted /NAME=value.
|
||
|
|
// Values containing whitespace/quotes still use full CRT escaping.
|
||
|
|
if(value.Length>0 && value.IndexOf('"')<0 && !Array.Exists(value.ToCharArray(),Char.IsWhiteSpace))return value;
|
||
|
|
var result=new StringBuilder("\""); int slashes=0;
|
||
|
|
foreach(char c in value) {
|
||
|
|
if(c=='\\'){slashes++;continue;}
|
||
|
|
if(c=='"'){result.Append('\\',slashes*2+1);result.Append(c);slashes=0;continue;}
|
||
|
|
result.Append('\\',slashes);slashes=0;result.Append(c);
|
||
|
|
}
|
||
|
|
result.Append('\\',slashes*2);return result.Append('"').ToString();
|
||
|
|
}
|
||
|
|
public OwnedProcessGroup(string executable,string[] arguments,string directory) {
|
||
|
|
var command=new StringBuilder(Quote(executable)); foreach(var arg in arguments)command.Append(' ').Append(Quote(arg));
|
||
|
|
JobName=JobPrefix+Guid.NewGuid().ToString("N");
|
||
|
|
job=CreateJobObject(IntPtr.Zero,JobName); if(job==IntPtr.Zero)throw Error();
|
||
|
|
// Never adopt an existing named object, even in an improbable collision.
|
||
|
|
if(Marshal.GetLastWin32Error()==183){CloseHandle(job);job=IntPtr.Zero;throw new InvalidOperationException("Maintenance job name already exists");}
|
||
|
|
ProcessInfo child=default(ProcessInfo);
|
||
|
|
try {
|
||
|
|
var limits=new ExtendedLimits();limits.Basic.Flags=0x2000; // KILL_ON_JOB_CLOSE, no BREAKAWAY_OK
|
||
|
|
if(!SetInformationJobObject(job,9,ref limits,(uint)Marshal.SizeOf<ExtendedLimits>()))throw Error();
|
||
|
|
var startup=new Startup();startup.Size=(uint)Marshal.SizeOf<Startup>();startup.Flags=1;startup.Show=0;
|
||
|
|
if(!CreateProcess(executable,command,IntPtr.Zero,IntPtr.Zero,false,0x08000004,IntPtr.Zero,directory,ref startup,out child))throw Error();
|
||
|
|
process=child.Process;ProcessId=(int)child.Pid;
|
||
|
|
if(!AssignProcessToJobObject(job,process))throw Error();
|
||
|
|
if(ResumeThread(child.Thread)==0xffffffff)throw Error();
|
||
|
|
} catch {
|
||
|
|
if(child.Process!=IntPtr.Zero){TerminateProcess(child.Process,125);CloseHandle(child.Process);process=IntPtr.Zero;}
|
||
|
|
CloseHandle(job);job=IntPtr.Zero;throw;
|
||
|
|
} finally { if(child.Thread!=IntPtr.Zero)CloseHandle(child.Thread); }
|
||
|
|
}
|
||
|
|
public bool Stop(int milliseconds) {
|
||
|
|
ThrowDisposed();
|
||
|
|
if(ActiveCount==0)return true;
|
||
|
|
if(!TerminateJobObject(job,124))throw Error();
|
||
|
|
var timer=Stopwatch.StartNew();
|
||
|
|
while(timer.ElapsedMilliseconds<milliseconds){if(ActiveCount==0)return true;Thread.Sleep(20);}
|
||
|
|
return ActiveCount==0;
|
||
|
|
}
|
||
|
|
public void Dispose() {
|
||
|
|
if(disposed)return;disposed=true;
|
||
|
|
// The handle is private and non-inherited. Even abrupt guardian death
|
||
|
|
// closes it, so orphaned installer descendants cannot escape containment.
|
||
|
|
if(job!=IntPtr.Zero){CloseHandle(job);job=IntPtr.Zero;}
|
||
|
|
if(process!=IntPtr.Zero){CloseHandle(process);process=IntPtr.Zero;}
|
||
|
|
GC.SuppressFinalize(this);
|
||
|
|
}
|
||
|
|
~OwnedProcessGroup(){Dispose();}
|
||
|
|
}
|
||
|
|
}
|