/* * Copyright (c) 2022 Winsider Seminars & Solutions, Inc. All rights reserved. * * This file is part of System Informer. * * Authors: * * dmex * */ namespace CustomBuildTool { /// /// Provides utility methods for interacting with the Windows file system, environment variables, processes, and /// registry, as well as other Win32-related operations. /// public static unsafe class Win32 { private static readonly FrozenSet RequiredPathEntries = new[] { // Windows system directories "\\Windows\\System32", "\\Windows\\", "\\Windows\\System32\\Wbem", "\\Windows\\System32\\WindowsPowerShell", "\\Windows\\System32\\OpenSSH", // Build tools "\\Microsoft Visual Studio", "\\MSBuild", "\\Windows Kits", "\\dotnet", // Version control "\\git", "\\GitHub CLI", // CMake and build tools "\\CMake", "\\vcpkg", "\\ninja", "\\LLVM", "\\mingw", }.ToFrozenSet(StringComparer.OrdinalIgnoreCase); /// /// Creates all directories and subdirectories in the specified path unless they already exist. /// /// The directory name or path. public static DirectoryInfo CreateDirectory(string FileName) { if (string.IsNullOrWhiteSpace(FileName)) return null; if (File.Exists(FileName)) return null; return Directory.CreateDirectory(FileName); } /// /// Creates a new process and buffers the output into a string. /// /// The name of the application to start. /// The arguments to pass to the application. /// The output from the application /// /// /// If the creation succeeds, the return value is nonzero. public static int CreateProcess(string FileName, IEnumerable Arguments, out string OutputString, bool FixNewLines = true, bool RedirectOutput = true) { int exitcode = int.MaxValue; StringBuilder output = new StringBuilder(0x1000); StringBuilder error = new StringBuilder(0x1000); try { using (Process process = new Process()) { process.StartInfo.FileName = FileName; process.StartInfo.UseShellExecute = false; if (Arguments != null) { foreach (string argument in Arguments) { process.StartInfo.ArgumentList.Add(argument); } } if (RedirectOutput) { process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.StandardErrorEncoding = Utils.UTF8NoBOM; process.StartInfo.StandardOutputEncoding = Utils.UTF8NoBOM; process.OutputDataReceived += (_, e) => { if (e.Data != null) output.AppendLine(e.Data); }; process.ErrorDataReceived += (_, e) => { if (e.Data != null) error.AppendLine(e.Data); }; } process.Start(); if (RedirectOutput) { process.BeginOutputReadLine(); process.BeginErrorReadLine(); } process.WaitForExit(); exitcode = process.ExitCode; } } catch (Exception ex) { Program.PrintColorMessage($"[CreateProcess] {ex}", ConsoleColor.Red); } OutputString = (output.ToString().Trim() + error.ToString().Trim()); if (FixNewLines) { OutputString = OutputString.Replace("\n\n", "\r\n", StringComparison.OrdinalIgnoreCase).Trim(); } return exitcode; } /// /// Creates a new process and buffers the output into a string using a raw command-line argument string. /// /// The name of the application to start. /// The raw argument string to pass to the application. /// The output from the application /// /// /// If the creation succeeds, the return value is nonzero. public static int CreateProcess(string FileName, string Arguments, out string OutputString, bool FixNewLines = true, bool RedirectOutput = true) { int exitcode = int.MaxValue; StringBuilder output = new StringBuilder(0x1000); StringBuilder error = new StringBuilder(0x1000); try { using (Process process = new Process()) { process.StartInfo.FileName = FileName; process.StartInfo.UseShellExecute = false; if (!string.IsNullOrWhiteSpace(Arguments)) { process.StartInfo.Arguments = Arguments; } if (RedirectOutput) { process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.StandardErrorEncoding = Utils.UTF8NoBOM; process.StartInfo.StandardOutputEncoding = Utils.UTF8NoBOM; process.OutputDataReceived += (_, e) => { if (e.Data != null) output.AppendLine(e.Data); }; process.ErrorDataReceived += (_, e) => { if (e.Data != null) error.AppendLine(e.Data); }; } process.Start(); if (RedirectOutput) { process.BeginOutputReadLine(); process.BeginErrorReadLine(); } process.WaitForExit(); exitcode = process.ExitCode; } } catch (Exception ex) { Program.PrintColorMessage($"[CreateProcess] {ex}", ConsoleColor.Red); } OutputString = (output.ToString().Trim() + error.ToString().Trim()); if (FixNewLines) { OutputString = OutputString.Replace("\n\n", "\r\n", StringComparison.OrdinalIgnoreCase).Trim(); } return exitcode; } /// /// Create an empty file. /// /// The file name or path. public static void CreateEmptyFile(string FileName) { if (string.IsNullOrWhiteSpace(FileName)) return; FileStreamOptions options = new FileStreamOptions { Mode = FileMode.Create, // Overwrite Access = FileAccess.Write, Share = FileShare.None }; new FileStream(FileName, options).Dispose(); } /// /// Deletes the specified file. /// /// The file name or path. /// public static void DeleteFile(string FileName, BuildFlags Flags = BuildFlags.None) { if (string.IsNullOrWhiteSpace(FileName)) return; if (File.Exists(FileName)) { if (Flags.HasFlag(BuildFlags.BuildVerbose)) { Program.PrintColorMessage($"Deleting: {FileName}", ConsoleColor.DarkGray); } File.Delete(FileName); } } /// /// Searches for a specified file using environment paths. /// /// The name of the file for which to search. /// The path and file name of the file found. public static string SearchPath(string FileName) { if (string.IsNullOrWhiteSpace(FileName)) return null; // System32 directory. { string where = Path.Join([Environment.SystemDirectory, FileName]); if (File.Exists(where)) return where; } // %PATH% directory. { if (Win32.GetEnvironmentVariable("PATH", out string values)) { foreach (var range in values.AsSpan().Split(';')) { var path = values.AsSpan(range); if (path.IsWhiteSpace()) continue; string where = Path.Join(path, FileName.AsSpan()); if (File.Exists(where)) return where; } } } // Current directory. { if (File.Exists(FileName)) { return Path.GetFullPath(FileName); } } return null; } // // Number of times, and delay between, retries for a transiently-locked file operation. // private const int FileRetryAttempts = 10; private const int FileRetryDelay = 200; /// /// Determines whether the exception represents a transient file lock (a sharing or lock /// violation) that is expected to clear once another process releases the file. /// /// The IO exception to inspect. /// True if the failure is a transient sharing/lock violation; otherwise false. private static bool IsTransientFileLock(IOException Exception) { int code = Exception.HResult & 0xffff; return code == 32 /* ERROR_SHARING_VIOLATION */ || code == 33 /* ERROR_LOCK_VIOLATION */; } /// /// Invokes a file operation, retrying briefly when the file is transiently locked by another /// process. During parallel multi-platform builds the linker for one architecture can still /// hold a binary that another architecture's post-build step needs to read (for example the /// WOW64 payload copied into the x64/ARM64 output); the lock clears once the linker finishes. /// /// The return type of the operation. /// The file operation to invoke. /// The result of the operation. private static T InvokeWithFileRetry(Func Operation) { for (int attempt = 1; ; attempt++) { try { return Operation(); } catch (IOException exception) when (attempt < FileRetryAttempts && IsTransientFileLock(exception)) { Thread.Sleep(FileRetryDelay); } } } /// /// Invokes a file operation, retrying briefly when the file is transiently locked by another process. /// /// The file operation to invoke. private static void InvokeWithFileRetry(Action Operation) { InvokeWithFileRetry(() => { Operation(); return null; }); } /// /// Copies the source file to the destination file if the source is newer or the destination does not exist. /// Preserves creation and last write times, and optionally sets the read-only attribute. /// /// The path to the source file. /// The path to the destination file. /// Build flags controlling output verbosity and behavior. /// If true, sets the destination file as read-only after copying. public static void CopyIfNewer(string SourceFile, string DestinationFile, BuildFlags Flags = BuildFlags.None, bool ReadOnly = false) { bool updated = false; if (!File.Exists(SourceFile)) { if (!Build.BuildIntegration && SourceFile!.EndsWith(".sig", StringComparison.OrdinalIgnoreCase)) return; Program.PrintColorMessage($"[SDK] [CopyIfNewer-FileNotFound] {SourceFile}", ConsoleColor.Yellow); return; } if (string.IsNullOrWhiteSpace(DestinationFile)) { Program.PrintColorMessage($"[SDK] [CopyIfNewer-DestinationFile-null]", ConsoleColor.Yellow); return; } { string directory = Path.GetDirectoryName(DestinationFile); if (string.IsNullOrWhiteSpace(directory)) { Program.PrintColorMessage($"[SDK] [CopyIfNewer-DestinationFile-null]", ConsoleColor.Yellow); return; } Win32.CreateDirectory(directory); } if (File.Exists(DestinationFile)) { Win32.GetFileBasicInfo(SourceFile, out var sourceCreationTime, out var sourceWriteTime, out var sourceAttributes); Win32.GetFileBasicInfo(DestinationFile, out var destinationCreationTime, out var destinationWriteTime, out var destinationAttributes); if (sourceWriteTime != destinationWriteTime || sourceCreationTime != destinationCreationTime) { if ((destinationAttributes & FileAttributes.ReadOnly) != 0) { try { File.SetAttributes(DestinationFile, FileAttributes.Normal); } catch { } } InvokeWithFileRetry(() => File.Copy(SourceFile, DestinationFile, true)); Win32.SetFileBasicInfo(DestinationFile, sourceCreationTime, sourceWriteTime, ReadOnly); updated = true; } } else { Win32.GetFileBasicInfo(SourceFile, out var sourceCreationTime, out var sourceWriteTime, out _); InvokeWithFileRetry(() => File.Copy(SourceFile, DestinationFile, true)); Win32.SetFileBasicInfo(DestinationFile, sourceCreationTime, sourceWriteTime, ReadOnly); updated = true; } if (updated) { Program.PrintColorMessage($"[SDK] {SourceFile} copied to {DestinationFile}", ConsoleColor.Green, true, Flags); } } /// /// Copies the source file to the destination file if the source has a newer last write time or a higher file version. /// /// The path to the source file. /// The path to the destination file. /// Build flags controlling output verbosity and behavior. public static void CopyVersionIfNewer(string SourceFile, string DestinationFile, BuildFlags Flags = BuildFlags.None) { bool updated = false; if (!File.Exists(SourceFile)) { Program.PrintColorMessage($"[CopyVersionIfNewer-FileNotFound] {SourceFile}", ConsoleColor.Yellow); return; } if (string.IsNullOrWhiteSpace(DestinationFile)) { Program.PrintColorMessage("[CopyVersionIfNewer-DestinationFile]", ConsoleColor.Yellow); return; } { string directory = Path.GetDirectoryName(DestinationFile); if (string.IsNullOrWhiteSpace(directory)) return; CreateDirectory(directory); } if (File.Exists(DestinationFile)) { GetFileBasicInfo(SourceFile, out var sourceCreationTime, out var sourceWriteTime, out _); GetFileBasicInfo(DestinationFile, out _, out var destinationWriteTime, out var destinationAttributes); if (sourceWriteTime > destinationWriteTime || GetFileVersion(SourceFile) > GetFileVersion(DestinationFile)) { if ((destinationAttributes & FileAttributes.ReadOnly) != 0) { try { File.SetAttributes(DestinationFile, FileAttributes.Normal); } catch { } } InvokeWithFileRetry(() => File.Copy(SourceFile, DestinationFile, true)); SetFileBasicInfo(DestinationFile, sourceCreationTime, sourceWriteTime, false); updated = true; } } else { GetFileBasicInfo(SourceFile, out var sourceCreationTime, out var sourceWriteTime, out _); InvokeWithFileRetry(() => File.Copy(SourceFile, DestinationFile, true)); SetFileBasicInfo(DestinationFile, sourceCreationTime, sourceWriteTime, false); updated = true; } if (updated) { Program.PrintColorMessage($"[SDK] {SourceFile} copied to {DestinationFile}", ConsoleColor.Green, true, Flags); } } /// /// Retrieves the value of an environment variable from the current process. /// /// The name of the environment variable. /// The value of the environment variable specified by variable, or null if the environment variable is not found. public static string GetEnvironmentVariable(string Name) { return Environment.GetEnvironmentVariable(Name, EnvironmentVariableTarget.Process); } /// /// Retrieves the value of an environment variable from the current process. /// /// The name of the environment variable. /// The value of the environment variable. /// True if the environment variable was found. public static bool GetEnvironmentVariable(string Name, out string Value) { Value = Environment.GetEnvironmentVariable(Name, EnvironmentVariableTarget.Process); if (string.IsNullOrWhiteSpace(Value)) { if (Build.BuildToolsDebug) { Program.PrintColorMessage($"EnvironmentVariable: {Name} not found.", ConsoleColor.Red); } return false; } return true; } /// /// Retrieves the value of an environment variable from the current process securely. /// /// The name of the environment variable. /// The value of the environment variable as a SecureBuffer. /// True if the environment variable was found. public static bool GetEnvironmentVariableSecure(string Name, out SecureBuffer Value) { Value = null; fixed (char* pName = Name) { uint size = PInvoke.GetEnvironmentVariable(pName, null, 0); if (size == 0) return false; using (var buffer = new SecureBuffer((int)size)) { fixed (char* pBuffer = buffer.WritableSpan) { uint length = PInvoke.GetEnvironmentVariable(pName, pBuffer, size); if (length == 0 || length >= size) return false; ReadOnlySpan value = buffer.Span.Slice(0, (int)length).Trim(); if (value.IsEmpty) return false; Value = new SecureBuffer(value.Length); value.CopyTo(Value.WritableSpan); } } } return true; } /// /// Retrieves the value of an environment variable from the current process. /// /// The name of the environment variable. /// The value of the environment variable. /// True if the environment variable was found. public static bool GetEnvironmentVariableSpan(string Name, out ReadOnlySpan Value) { var value = Environment.GetEnvironmentVariable(Name, EnvironmentVariableTarget.Process); Value = value.AsSpan(); if (Utils.IsSpanNullOrWhiteSpace(Value)) { if (Build.BuildToolsDebug) { Program.PrintColorMessage($"EnvironmentVariable: {Name} not found.", ConsoleColor.Red); } return false; } return true; } /// /// Retrieves the value of an environment variable from the current process. /// /// The name of the environment variable. /// True if the environment variable was found. public static bool HasEnvironmentVariable(string Name) { return GetEnvironmentVariableSpan(Name, out ReadOnlySpan _); } /// /// Retrieves the value of an environment variable from the current process. /// /// The name of the environment variable. /// True if the environment variable was found. public static string ExpandEnvironmentVariables(string Name) { return Environment.ExpandEnvironmentVariables(Name).Replace(Name, string.Empty, StringComparison.OrdinalIgnoreCase); } /// /// Returns the current kernel version information. /// /// The version number of the file or null if the file doesn't exist. public static string GetKernelVersion() { string filePath = ExpandEnvironmentVariables("%SystemRoot%\\System32\\ntoskrnl.exe"); if (File.Exists(filePath)) { FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(filePath); return versionInfo.FileVersion; } return null; } /// /// Retrieves a string value from the Windows registry. /// /// If true, queries HKEY_LOCAL_MACHINE; otherwise, HKEY_CURRENT_USER. /// The registry key path. /// The name of the value to retrieve. (Note: This parameter is not used in the current implementation.) /// The value to return if the registry value is not found or is empty. /// The string value from the registry, or if not found. public static string GetKeyValue(bool LocalMachine, string KeyName, string ValueName, string DefaultValue) { // required for the ESDK string value = string.Empty; byte* valueBuffer = null; HKEY keyHandle; fixed (char* pKey = KeyName) fixed (char* pValue = ValueName) { if (PInvoke.RegOpenKeyEx( LocalMachine ? HKEY.HKEY_LOCAL_MACHINE : HKEY.HKEY_CURRENT_USER, pKey, 0, REG_SAM_FLAGS.KEY_READ, &keyHandle ) == WIN32_ERROR.ERROR_SUCCESS) { uint valueLength = 0; REG_VALUE_TYPE valueType = 0; PInvoke.RegQueryValueEx( keyHandle, pValue, null, &valueType, null, &valueLength ); if ((valueType == REG_VALUE_TYPE.REG_SZ || valueType == REG_VALUE_TYPE.REG_EXPAND_SZ) && valueLength >= sizeof(char)) { try { valueBuffer = (byte*)NativeMemory.Alloc(valueLength); if (PInvoke.RegQueryValueEx( keyHandle, pValue, null, null, valueBuffer, &valueLength ) == WIN32_ERROR.ERROR_SUCCESS) { int charLength = (int)(valueLength / sizeof(char)); if (charLength > 0 && ((char*)valueBuffer)[charLength - 1] == '\0') charLength--; if (charLength > 0) { ReadOnlySpan valueSpan = new ReadOnlySpan((char*)valueBuffer, charLength); value = valueSpan.ToString(); } } } finally { NativeMemory.Free(valueBuffer); } } _ = PInvoke.RegCloseKey(keyHandle); } } return string.IsNullOrWhiteSpace(value) ? DefaultValue : value; } /// /// Gets the size of a file in bytes. /// /// The path to the file. /// The size of the file in bytes, or 0 if the file does not exist or cannot be accessed. public static ulong GetFileSize(string FileName) { WIN32_FILE_ATTRIBUTE_DATA sourceFile = new WIN32_FILE_ATTRIBUTE_DATA(); if (PInvoke.GetFileAttributesEx( FileName, GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, &sourceFile )) { return ((ulong)sourceFile.nFileSizeHigh << 32) | sourceFile.nFileSizeLow; } return 0; } /// /// Retrieves the version information of a file. /// /// The path to the file. /// The of the file, or 0.0.0.0 if not found. public static Version GetFileVersion(string FileName) { try { FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(FileName); return new Version( versionInfo.FileMajorPart, versionInfo.FileMinorPart, versionInfo.FileBuildPart, versionInfo.FilePrivatePart ); } catch (Exception) { return new Version(0, 0, 0, 0); } } /// /// Sets the current process priority class to high. /// public static void SetErrorMode() { PInvoke.SetErrorMode(THREAD_ERROR_MODE.SEM_NOGPFAULTERRORBOX | THREAD_ERROR_MODE.SEM_NOOPENFILEERRORBOX); } /// /// Sets the current process priority class to high. /// public static void SetBasePriority() { //Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High; PInvoke.SetPriorityClass( PInvoke.GetCurrentProcess(), PROCESS_CREATION_FLAGS.HIGH_PRIORITY_CLASS ); } public static bool IsGitInstalled() { return SearchPath("git.exe") != null; } public static string GetDotNetPath() { return SearchPath("dotnet.exe"); } public static string GetDotNetVersion() { string dotnet = GetDotNetPath(); if (dotnet == null) return string.Empty; if (CreateProcess(dotnet, ["--version"], out string output) == 0) return output.Trim(); return string.Empty; } /// /// Filters the PATH environment variable to include only directories essential for building System Informer. /// Removes scripting languages (Python, Ruby, Node.js) and other non-essential tools. /// /// /// This method is called during build initialization and keeps essential build tools /// while removing potentially unnecessary dependencies. /// public static void SetPathEnvironment() { if (!GetEnvironmentVariable("PATH", out string currentPath)) return; List allowedPaths = new List(); foreach (var range in currentPath.AsSpan().Split(';')) { var entry = currentPath.AsSpan(range); if (entry.IsWhiteSpace()) continue; bool isEssential = false; foreach (string pattern in RequiredPathEntries) { if (entry.Contains(pattern, StringComparison.OrdinalIgnoreCase)) { isEssential = true; break; } } if (isEssential) { allowedPaths.Add(entry.ToString()); } } if (allowedPaths.Count > 0) { string filteredPath = string.Join(';', allowedPaths); if (!string.IsNullOrWhiteSpace(filteredPath)) { Environment.SetEnvironmentVariable("PATH", filteredPath, EnvironmentVariableTarget.Process); } //Program.PrintColorMessage($"[PATH] filtered: {pathEntries.Length} entries -> {allowedPaths.Count} entries", ConsoleColor.DarkGray); } } /// /// Sets the basic file information, including creation and last write times, and optionally the read-only attribute. /// /// The path to the file. /// The creation time to set. If , uses current UTC time. /// The last write time to set. If , uses current UTC time. /// Whether to set the file as read-only. /// Thrown if the file information cannot be set. public static void SetFileBasicInfo( string FileName, DateTime CreationDateTime, DateTime LastWriteDateTime, bool ReadOnly ) { FILE_BASIC_INFO basicInfo = new FILE_BASIC_INFO(); using (var fs = new FileStream( FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete, 0, FileOptions.None )) { if (fs.SafeFileHandle == null) return; var handle = new HANDLE(fs.SafeFileHandle.DangerousGetHandle()); if (!PInvoke.GetFileInformationByHandleEx(handle, FILE_INFO_BY_HANDLE_CLASS.FileBasicInfo, &basicInfo, (uint)sizeof(FILE_BASIC_INFO))) throw new Win32Exception(Marshal.GetLastWin32Error()); basicInfo.CreationTime = CreationDateTime == DateTime.MinValue ? DateTime.UtcNow.ToFileTimeUtc() : CreationDateTime.ToFileTimeUtc(); basicInfo.LastWriteTime = LastWriteDateTime == DateTime.MinValue ? DateTime.UtcNow.ToFileTimeUtc() : LastWriteDateTime.ToFileTimeUtc(); if (!Build.BuildIntegration) // Skip read-only attribute during build integration (dmex) { if (ReadOnly) basicInfo.FileAttributes |= (uint)FileAttributes.ReadOnly; else basicInfo.FileAttributes &= ~(uint)FileAttributes.ReadOnly; } PInvoke.SetFileInformationByHandle(handle, FILE_INFO_BY_HANDLE_CLASS.FileBasicInfo, &basicInfo, (uint)sizeof(FILE_BASIC_INFO)); } } /// /// Retrieves basic file information, including creation time, last write time, and attributes. /// /// The path to the file. /// When this method returns, contains the creation time of the file. /// When this method returns, contains the last write time of the file. /// When this method returns, contains the file attributes. /// True if the file exists and information was retrieved; otherwise, false. /// Thrown if the file information cannot be retrieved. public static bool GetFileBasicInfo( string FileName, out DateTime CreationTime, out DateTime LastWriteDateTime, out FileAttributes Attributes ) { FILE_BASIC_INFO basicInfo = new FILE_BASIC_INFO(); CreationTime = DateTime.MinValue; LastWriteDateTime = DateTime.MinValue; if (!File.Exists(FileName)) { Attributes = FileAttributes.None; return false; } using (var fs = File.OpenRead(FileName)) { var handle = new HANDLE(fs.SafeFileHandle!.DangerousGetHandle()); if (!PInvoke.GetFileInformationByHandleEx(handle, FILE_INFO_BY_HANDLE_CLASS.FileBasicInfo, &basicInfo, (uint)sizeof(FILE_BASIC_INFO))) throw new Win32Exception(Marshal.GetLastWin32Error()); CreationTime = DateTime.FromFileTimeUtc(basicInfo.CreationTime); LastWriteDateTime = DateTime.FromFileTimeUtc(basicInfo.LastWriteTime); Attributes = (FileAttributes)basicInfo.FileAttributes; } return true; } /// /// Sets low (untrusted) integrity level for processes. /// /// /// This method lists all running processes, identifies those with executables in /// temporary folders (containing "\Temp\"), and attempts to lower their integrity level /// to Untrusted (S-1-16-0). This is a security mitigation technique. /// /// Each matching image is additionally blocked from launching again by creating an /// Image File Execution Options (IFEO) key with a Debugger value of *, /// which is not a valid file name and therefore always fails the launch. /// Requires elevation; failures are reported and otherwise ignored. /// /// public static void SetLowIntegrityForProcesses() { const uint PROCESS_QUERY_LIMITED_INFORMATION = 0x1000; const uint TOKEN_QUERY = 0x0008; const uint TOKEN_ADJUST_DEFAULT = 0x0080; const uint SE_GROUP_INTEGRITY = 0x00000020; const uint SECURITY_MANDATORY_UNTRUSTED_RID = 0x00000000; const int TokenIntegrityLevel = 25; var processesToModify = new List(); var imagesToBlock = new HashSet(StringComparer.OrdinalIgnoreCase); try { var allProcesses = Process.GetProcesses(); foreach (var process in allProcesses) { try { var filename = process.MainModule?.FileName; if (!string.IsNullOrWhiteSpace(filename) && filename.Contains("\\Temp\\", StringComparison.OrdinalIgnoreCase)) { Program.PrintColorMessage($"Process: {filename}", ConsoleColor.DarkGray); processesToModify.Add(process); imagesToBlock.Add(Path.GetFileName(filename)); } else { process.Dispose(); } } catch { process.Dispose(); } } foreach (var process in processesToModify) { try { ApplyLowIntegrity( process, PROCESS_QUERY_LIMITED_INFORMATION, TOKEN_QUERY | TOKEN_ADJUST_DEFAULT, SE_GROUP_INTEGRITY, SECURITY_MANDATORY_UNTRUSTED_RID, TokenIntegrityLevel ); } catch (Exception ex) { Program.PrintColorMessage( $"Failed to set integrity for {process.ProcessName} (PID: {process.Id}): {ex.Message}", ConsoleColor.Yellow ); } finally { process.Dispose(); } } foreach (var imageName in imagesToBlock) { BlockImageFileExecution(imageName); } } catch (Exception ex) { Program.PrintColorMessage($"Error enumerating processes: {ex.Message}", ConsoleColor.Red); } } /// /// Blocks an executable from launching by creating an Image File Execution Options (IFEO) /// key for the image and setting its Debugger value. /// /// The file name (without path) of the executable to block. private static void BlockImageFileExecution(string ImageName) { if (string.IsNullOrWhiteSpace(ImageName)) return; try { using (var key = Microsoft.Win32.Registry.LocalMachine.CreateSubKey($"Software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\{ImageName}", true)) { if (key == null) { Program.PrintColorMessage($"Failed to create IFEO key for {ImageName}", ConsoleColor.Yellow); return; } key.SetValue("Debugger", "*", Microsoft.Win32.RegistryValueKind.String); } Program.PrintColorMessage($"Blocked execution: {ImageName}", ConsoleColor.DarkGray); } catch (Exception ex) { Program.PrintColorMessage($"Failed to block {ImageName}: {ex.Message}", ConsoleColor.Yellow); } } /// /// Sets the specified process's token integrity level to low by updating its mandatory label information. /// /// The process whose token integrity level will be modified. /// The access rights required to open the target process. Must be enough to allow token manipulation. /// The access rights required to open the process token. Must permit setting token information. /// The attributes to assign to the integrity SID in the token mandatory label. /// The relative identifier (RID) used to construct the integrity SID. Typically, specifies the desired integrity /// level. /// The token information class specifying the type of information to set. Must correspond to mandatory label /// information. /// Thrown if any Windows API call fails, such as opening the process, opening the process token, or setting /// token information. private static void ApplyLowIntegrity( Process Process, uint ProcessAccess, uint TokenAccess, uint SidAttributes, uint MandatoryRid, int TokenInfoClass ) { HANDLE processHandle = default; HANDLE tokenHandle = default; try { processHandle = PInvoke.OpenProcess((PROCESS_ACCESS_RIGHTS)ProcessAccess, false, (uint)Process.Id); if (processHandle.IsNull) { throw new Win32Exception(Marshal.GetLastWin32Error(), $"OpenProcess failed for {Process.ProcessName}"); } if (!PInvoke.OpenProcessToken(processHandle, (TOKEN_ACCESS_MASK)TokenAccess, &tokenHandle)) { throw new Win32Exception(Marshal.GetLastWin32Error(), "OpenProcessToken failed"); } // Manually construct the Untrusted Integrity SID (S-1-16-0) // SID structure: Revision(1) + SubAuthorityCount(1) + Authority(6 bytes) + SubAuthority(4 bytes) byte* sidBuffer = stackalloc byte[12]; Span sidSpan = new Span(sidBuffer, 12); sidSpan.Clear(); sidSpan[0] = 1; // SID_REVISION sidSpan[1] = 1; // SubAuthorityCount sidSpan[7] = 16; // IdentifierAuthority[5] - SECURITY_MANDATORY_LABEL_AUTHORITY (S-1-16) BinaryPrimitives.WriteUInt32LittleEndian(sidSpan[8..], MandatoryRid); // SubAuthority[0] = mandatoryRid (little-endian) var integritySid = new PSID(sidBuffer); var tokenMandatoryLabel = new TOKEN_MANDATORY_LABEL { Label = new SID_AND_ATTRIBUTES { Attributes = SidAttributes, Sid = integritySid } }; if (!PInvoke.SetTokenInformation( tokenHandle, (TOKEN_INFORMATION_CLASS)TokenInfoClass, &tokenMandatoryLabel, (uint)sizeof(TOKEN_MANDATORY_LABEL) )) { throw new Win32Exception(Marshal.GetLastWin32Error(), "SetTokenInformation failed"); } Program.PrintColorMessage($"Successfully set low integrity for {Process.ProcessName} (PID: {Process.Id})", ConsoleColor.Green); } catch (Exception ex) { Program.PrintColorMessage($"Error setting integrity: {ex.Message}", ConsoleColor.Red); } finally { if (!tokenHandle.IsNull) PInvoke.CloseHandle(tokenHandle); if (!processHandle.IsNull) PInvoke.CloseHandle(processHandle); } } } }