mirror of
https://github.com/goatcorp/Dalamud.git
synced 2025-12-12 10:17:22 +01:00
chore: fix some warnings, cleanup
This commit is contained in:
parent
9a38a9470c
commit
96ed22534c
49 changed files with 413 additions and 440 deletions
|
|
@ -1,21 +1,262 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Linq;
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
|
||||
using Serilog;
|
||||
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace Dalamud.Injector
|
||||
{
|
||||
/// <summary>
|
||||
/// Class responsible for stripping ACL protections from processes.
|
||||
/// </summary>
|
||||
public static class NativeAclFix
|
||||
{
|
||||
/// <summary>
|
||||
/// Start a process without ACL protections.
|
||||
/// </summary>
|
||||
/// <param name="workingDir">The working directory.</param>
|
||||
/// <param name="exePath">The path to the executable file.</param>
|
||||
/// <param name="arguments">Arguments to pass to the executable file.</param>
|
||||
/// <param name="beforeResume">Action to execute before the process is started.</param>
|
||||
/// <returns>The started process.</returns>
|
||||
/// <exception cref="Win32Exception">Thrown when a win32 error occurs.</exception>
|
||||
/// <exception cref="GameExitedException">Thrown when the process did not start correctly.</exception>
|
||||
public static Process LaunchGame(string workingDir, string exePath, string arguments, Action<Process> beforeResume)
|
||||
{
|
||||
Process process = null;
|
||||
|
||||
var userName = Environment.UserName;
|
||||
|
||||
var pExplicitAccess = default(PInvoke.EXPLICIT_ACCESS);
|
||||
PInvoke.BuildExplicitAccessWithName(
|
||||
ref pExplicitAccess,
|
||||
userName,
|
||||
PInvoke.STANDARD_RIGHTS_ALL | PInvoke.SPECIFIC_RIGHTS_ALL & ~PInvoke.PROCESS_VM_WRITE,
|
||||
PInvoke.GRANT_ACCESS,
|
||||
0);
|
||||
|
||||
if (PInvoke.SetEntriesInAcl(1, ref pExplicitAccess, IntPtr.Zero, out var newAcl) != 0)
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
|
||||
if (!PInvoke.InitializeSecurityDescriptor(out var secDesc, PInvoke.SECURITY_DESCRIPTOR_REVISION))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
|
||||
if (!PInvoke.SetSecurityDescriptorDacl(ref secDesc, true, newAcl, false))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
|
||||
var psecDesc = Marshal.AllocHGlobal(Marshal.SizeOf<PInvoke.SECURITY_DESCRIPTOR>());
|
||||
Marshal.StructureToPtr(secDesc, psecDesc, true);
|
||||
|
||||
var lpProcessInformation = default(PInvoke.PROCESS_INFORMATION);
|
||||
try
|
||||
{
|
||||
var lpProcessAttributes = new PInvoke.SECURITY_ATTRIBUTES
|
||||
{
|
||||
nLength = Marshal.SizeOf<PInvoke.SECURITY_ATTRIBUTES>(),
|
||||
lpSecurityDescriptor = psecDesc,
|
||||
bInheritHandle = false,
|
||||
};
|
||||
|
||||
var lpStartupInfo = new PInvoke.STARTUPINFO
|
||||
{
|
||||
cb = Marshal.SizeOf<PInvoke.STARTUPINFO>(),
|
||||
};
|
||||
|
||||
var compatLayerPrev = Environment.GetEnvironmentVariable("__COMPAT_LAYER");
|
||||
|
||||
Environment.SetEnvironmentVariable("__COMPAT_LAYER", "RunAsInvoker");
|
||||
try
|
||||
{
|
||||
if (!PInvoke.CreateProcess(
|
||||
null,
|
||||
$"\"{exePath}\" {arguments}",
|
||||
ref lpProcessAttributes,
|
||||
IntPtr.Zero,
|
||||
false,
|
||||
PInvoke.CREATE_SUSPENDED,
|
||||
IntPtr.Zero,
|
||||
workingDir,
|
||||
ref lpStartupInfo,
|
||||
out lpProcessInformation))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Environment.SetEnvironmentVariable("__COMPAT_LAYER", compatLayerPrev);
|
||||
}
|
||||
|
||||
DisableSeDebug(lpProcessInformation.hProcess);
|
||||
|
||||
process = new ExistingProcess(lpProcessInformation.hProcess);
|
||||
|
||||
beforeResume?.Invoke(process);
|
||||
|
||||
PInvoke.ResumeThread(lpProcessInformation.hThread);
|
||||
|
||||
// Ensure that the game main window is prepared
|
||||
try
|
||||
{
|
||||
do
|
||||
{
|
||||
process.WaitForInputIdle();
|
||||
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
while (TryFindGameWindow(process) == IntPtr.Zero);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
throw new GameExitedException();
|
||||
}
|
||||
|
||||
if (PInvoke.GetSecurityInfo(
|
||||
PInvoke.GetCurrentProcess(),
|
||||
PInvoke.SE_OBJECT_TYPE.SE_KERNEL_OBJECT,
|
||||
PInvoke.SECURITY_INFORMATION.DACL_SECURITY_INFORMATION,
|
||||
IntPtr.Zero,
|
||||
IntPtr.Zero,
|
||||
out var pACL,
|
||||
IntPtr.Zero,
|
||||
IntPtr.Zero) != 0)
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
|
||||
if (PInvoke.SetSecurityInfo(
|
||||
lpProcessInformation.hProcess,
|
||||
PInvoke.SE_OBJECT_TYPE.SE_KERNEL_OBJECT,
|
||||
PInvoke.SECURITY_INFORMATION.DACL_SECURITY_INFORMATION | PInvoke.SECURITY_INFORMATION.UNPROTECTED_DACL_SECURITY_INFORMATION,
|
||||
IntPtr.Zero,
|
||||
IntPtr.Zero,
|
||||
pACL,
|
||||
IntPtr.Zero) != 0)
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Error(ex, "[NativeAclFix] Uncaught error during initialization, trying to kill process");
|
||||
|
||||
try
|
||||
{
|
||||
process?.Kill();
|
||||
}
|
||||
catch (Exception killEx)
|
||||
{
|
||||
Log.Error(killEx, "[NativeAclFix] Could not kill process");
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(psecDesc);
|
||||
PInvoke.CloseHandle(lpProcessInformation.hThread);
|
||||
}
|
||||
|
||||
return process;
|
||||
}
|
||||
|
||||
private static void DisableSeDebug(IntPtr processHandle)
|
||||
{
|
||||
if (!PInvoke.OpenProcessToken(processHandle, PInvoke.TOKEN_QUERY | PInvoke.TOKEN_ADJUST_PRIVILEGES, out var tokenHandle))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
|
||||
var luidDebugPrivilege = default(PInvoke.LUID);
|
||||
if (!PInvoke.LookupPrivilegeValue(null, "SeDebugPrivilege", ref luidDebugPrivilege))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
|
||||
var requiredPrivileges = new PInvoke.PRIVILEGE_SET
|
||||
{
|
||||
PrivilegeCount = 1,
|
||||
Control = PInvoke.PRIVILEGE_SET_ALL_NECESSARY,
|
||||
Privilege = new PInvoke.LUID_AND_ATTRIBUTES[1],
|
||||
};
|
||||
|
||||
requiredPrivileges.Privilege[0].Luid = luidDebugPrivilege;
|
||||
requiredPrivileges.Privilege[0].Attributes = PInvoke.SE_PRIVILEGE_ENABLED;
|
||||
|
||||
if (!PInvoke.PrivilegeCheck(tokenHandle, ref requiredPrivileges, out bool bResult))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
|
||||
// SeDebugPrivilege is enabled; try disabling it
|
||||
if (bResult)
|
||||
{
|
||||
var tokenPrivileges = new PInvoke.TOKEN_PRIVILEGES
|
||||
{
|
||||
PrivilegeCount = 1,
|
||||
Privileges = new PInvoke.LUID_AND_ATTRIBUTES[1],
|
||||
};
|
||||
|
||||
tokenPrivileges.Privileges[0].Luid = luidDebugPrivilege;
|
||||
tokenPrivileges.Privileges[0].Attributes = PInvoke.SE_PRIVILEGE_REMOVED;
|
||||
|
||||
if (!PInvoke.AdjustTokenPrivileges(tokenHandle, false, ref tokenPrivileges, 0, IntPtr.Zero, 0))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
}
|
||||
|
||||
PInvoke.CloseHandle(tokenHandle);
|
||||
}
|
||||
|
||||
private static IntPtr TryFindGameWindow(Process process)
|
||||
{
|
||||
IntPtr hwnd = IntPtr.Zero;
|
||||
while ((hwnd = PInvoke.FindWindowEx(IntPtr.Zero, hwnd, "FFXIVGAME", IntPtr.Zero)) != IntPtr.Zero)
|
||||
{
|
||||
PInvoke.GetWindowThreadProcessId(hwnd, out uint pid);
|
||||
|
||||
if (pid == process.Id && PInvoke.IsWindowVisible(hwnd))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return hwnd;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Exception thrown when the process has exited before a window could be found.
|
||||
/// </summary>
|
||||
public class GameExitedException : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GameExitedException"/> class.
|
||||
/// </summary>
|
||||
public GameExitedException()
|
||||
: base("Game exited prematurely.")
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
// Definitions taken from PInvoke.net (with some changes)
|
||||
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:Accessible fields should begin with upper-case letter", Justification = "WINAPI conventions")]
|
||||
[SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1121:Use built-in type alias", Justification = "WINAPI conventions")]
|
||||
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1400:Access modifier should be declared", Justification = "WINAPI conventions")]
|
||||
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:Field names should begin with lower-case letter", Justification = "WINAPI conventions")]
|
||||
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:Field names should not contain underscore", Justification = "WINAPI conventions")]
|
||||
[SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1124:Do not use regions", Justification = "WINAPI conventions")]
|
||||
private static class PInvoke
|
||||
{
|
||||
#region Constants
|
||||
|
|
@ -37,11 +278,10 @@ namespace Dalamud.Injector
|
|||
public const UInt32 SE_PRIVILEGE_ENABLED = 0x00000002;
|
||||
public const UInt32 SE_PRIVILEGE_REMOVED = 0x00000004;
|
||||
|
||||
|
||||
public enum MULTIPLE_TRUSTEE_OPERATION
|
||||
{
|
||||
NO_MULTIPLE_TRUSTEE,
|
||||
TRUSTEE_IS_IMPERSONATE
|
||||
TRUSTEE_IS_IMPERSONATE,
|
||||
}
|
||||
|
||||
public enum TRUSTEE_FORM
|
||||
|
|
@ -50,7 +290,7 @@ namespace Dalamud.Injector
|
|||
TRUSTEE_IS_NAME,
|
||||
TRUSTEE_BAD_FORM,
|
||||
TRUSTEE_IS_OBJECTS_AND_SID,
|
||||
TRUSTEE_IS_OBJECTS_AND_NAME
|
||||
TRUSTEE_IS_OBJECTS_AND_NAME,
|
||||
}
|
||||
|
||||
public enum TRUSTEE_TYPE
|
||||
|
|
@ -63,7 +303,7 @@ namespace Dalamud.Injector
|
|||
TRUSTEE_IS_WELL_KNOWN_GROUP,
|
||||
TRUSTEE_IS_DELETED,
|
||||
TRUSTEE_IS_INVALID,
|
||||
TRUSTEE_IS_COMPUTER
|
||||
TRUSTEE_IS_COMPUTER,
|
||||
}
|
||||
|
||||
public enum SE_OBJECT_TYPE
|
||||
|
|
@ -80,8 +320,10 @@ namespace Dalamud.Injector
|
|||
SE_DS_OBJECT_ALL,
|
||||
SE_PROVIDER_DEFINED_OBJECT,
|
||||
SE_WMIGUID_OBJECT,
|
||||
SE_REGISTRY_WOW64_32KEY
|
||||
SE_REGISTRY_WOW64_32KEY,
|
||||
}
|
||||
|
||||
[Flags]
|
||||
public enum SECURITY_INFORMATION
|
||||
{
|
||||
OWNER_SECURITY_INFORMATION = 1,
|
||||
|
|
@ -90,12 +332,120 @@ namespace Dalamud.Injector
|
|||
SACL_SECURITY_INFORMATION = 8,
|
||||
UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000,
|
||||
UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000,
|
||||
PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000
|
||||
PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000,
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Methods
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
|
||||
public static extern void BuildExplicitAccessWithName(
|
||||
ref EXPLICIT_ACCESS pExplicitAccess,
|
||||
string pTrusteeName,
|
||||
uint accessPermissions,
|
||||
uint accessMode,
|
||||
uint inheritance);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
|
||||
public static extern int SetEntriesInAcl(
|
||||
int cCountOfExplicitEntries,
|
||||
ref EXPLICIT_ACCESS pListOfExplicitEntries,
|
||||
IntPtr oldAcl,
|
||||
out IntPtr newAcl);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern bool InitializeSecurityDescriptor(
|
||||
out SECURITY_DESCRIPTOR pSecurityDescriptor,
|
||||
uint dwRevision);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern bool SetSecurityDescriptorDacl(
|
||||
ref SECURITY_DESCRIPTOR pSecurityDescriptor,
|
||||
bool bDaclPresent,
|
||||
IntPtr pDacl,
|
||||
bool bDaclDefaulted);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
|
||||
public static extern bool CreateProcess(
|
||||
string lpApplicationName,
|
||||
string lpCommandLine,
|
||||
ref SECURITY_ATTRIBUTES lpProcessAttributes,
|
||||
IntPtr lpThreadAttributes,
|
||||
bool bInheritHandles,
|
||||
UInt32 dwCreationFlags,
|
||||
IntPtr lpEnvironment,
|
||||
string lpCurrentDirectory,
|
||||
[In] ref STARTUPINFO lpStartupInfo,
|
||||
out PROCESS_INFORMATION lpProcessInformation);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
public static extern bool CloseHandle(IntPtr hObject);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
public static extern uint ResumeThread(IntPtr hThread);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern bool OpenProcessToken(
|
||||
IntPtr processHandle,
|
||||
UInt32 desiredAccess,
|
||||
out IntPtr tokenHandle);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, ref LUID lpLuid);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern bool PrivilegeCheck(
|
||||
IntPtr clientToken,
|
||||
ref PRIVILEGE_SET requiredPrivileges,
|
||||
out bool pfResult);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern bool AdjustTokenPrivileges(
|
||||
IntPtr tokenHandle,
|
||||
bool disableAllPrivileges,
|
||||
ref TOKEN_PRIVILEGES newState,
|
||||
UInt32 bufferLengthInBytes,
|
||||
IntPtr previousState,
|
||||
UInt32 returnLengthInBytes);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern uint GetSecurityInfo(
|
||||
IntPtr handle,
|
||||
SE_OBJECT_TYPE objectType,
|
||||
SECURITY_INFORMATION securityInfo,
|
||||
IntPtr pSidOwner,
|
||||
IntPtr pSidGroup,
|
||||
out IntPtr pDacl,
|
||||
IntPtr pSacl,
|
||||
IntPtr pSecurityDescriptor);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern uint SetSecurityInfo(
|
||||
IntPtr handle,
|
||||
SE_OBJECT_TYPE objectType,
|
||||
SECURITY_INFORMATION securityInfo,
|
||||
IntPtr psidOwner,
|
||||
IntPtr psidGroup,
|
||||
IntPtr pDacl,
|
||||
IntPtr pSacl);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
public static extern IntPtr GetCurrentProcess();
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr hWndChildAfter, string className, IntPtr windowTitle);
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static extern bool IsWindowVisible(IntPtr hWnd);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Structures
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 0)]
|
||||
public struct TRUSTEE : IDisposable
|
||||
{
|
||||
|
|
@ -105,12 +455,16 @@ namespace Dalamud.Injector
|
|||
public TRUSTEE_TYPE TrusteeType;
|
||||
private IntPtr ptstrName;
|
||||
|
||||
public string Name => Marshal.PtrToStringAuto(this.ptstrName) ?? string.Empty;
|
||||
|
||||
#pragma warning disable CA1416
|
||||
|
||||
void IDisposable.Dispose()
|
||||
{
|
||||
if (ptstrName != IntPtr.Zero) Marshal.Release(ptstrName);
|
||||
if (this.ptstrName != IntPtr.Zero) Marshal.Release(this.ptstrName);
|
||||
}
|
||||
|
||||
public string Name { get { return Marshal.PtrToStringAuto(ptstrName); } }
|
||||
#pragma warning restore CA1416
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 0)]
|
||||
|
|
@ -204,341 +558,6 @@ namespace Dalamud.Injector
|
|||
public LUID_AND_ATTRIBUTES[] Privileges;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region Methods
|
||||
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
|
||||
public static extern void BuildExplicitAccessWithName(
|
||||
ref EXPLICIT_ACCESS pExplicitAccess,
|
||||
string pTrusteeName,
|
||||
uint AccessPermissions,
|
||||
uint AccessMode,
|
||||
uint Inheritance);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
|
||||
public static extern int SetEntriesInAcl(
|
||||
int cCountOfExplicitEntries,
|
||||
ref EXPLICIT_ACCESS pListOfExplicitEntries,
|
||||
IntPtr OldAcl,
|
||||
out IntPtr NewAcl);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern bool InitializeSecurityDescriptor(
|
||||
out SECURITY_DESCRIPTOR pSecurityDescriptor,
|
||||
uint dwRevision);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern bool SetSecurityDescriptorDacl(
|
||||
ref SECURITY_DESCRIPTOR pSecurityDescriptor,
|
||||
bool bDaclPresent,
|
||||
IntPtr pDacl,
|
||||
bool bDaclDefaulted);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
|
||||
public static extern bool CreateProcess(
|
||||
string lpApplicationName,
|
||||
string lpCommandLine,
|
||||
ref SECURITY_ATTRIBUTES lpProcessAttributes,
|
||||
IntPtr lpThreadAttributes,
|
||||
bool bInheritHandles,
|
||||
UInt32 dwCreationFlags,
|
||||
IntPtr lpEnvironment,
|
||||
string lpCurrentDirectory,
|
||||
[In] ref STARTUPINFO lpStartupInfo,
|
||||
out PROCESS_INFORMATION lpProcessInformation);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
public static extern bool CloseHandle(IntPtr hObject);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
public static extern uint ResumeThread(IntPtr hThread);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern bool OpenProcessToken(
|
||||
IntPtr ProcessHandle,
|
||||
UInt32 DesiredAccess,
|
||||
out IntPtr TokenHandle);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, ref LUID lpLuid);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern bool PrivilegeCheck(
|
||||
IntPtr ClientToken,
|
||||
ref PRIVILEGE_SET RequiredPrivileges,
|
||||
out bool pfResult);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern bool AdjustTokenPrivileges(
|
||||
IntPtr TokenHandle,
|
||||
bool DisableAllPrivileges,
|
||||
ref TOKEN_PRIVILEGES NewState,
|
||||
UInt32 BufferLengthInBytes,
|
||||
IntPtr PreviousState,
|
||||
UInt32 ReturnLengthInBytes);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern uint GetSecurityInfo(
|
||||
IntPtr handle,
|
||||
SE_OBJECT_TYPE ObjectType,
|
||||
SECURITY_INFORMATION SecurityInfo,
|
||||
IntPtr pSidOwner,
|
||||
IntPtr pSidGroup,
|
||||
out IntPtr pDacl,
|
||||
IntPtr pSacl,
|
||||
IntPtr pSecurityDescriptor);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern uint SetSecurityInfo(
|
||||
IntPtr handle,
|
||||
SE_OBJECT_TYPE ObjectType,
|
||||
SECURITY_INFORMATION SecurityInfo,
|
||||
IntPtr psidOwner,
|
||||
IntPtr psidGroup,
|
||||
IntPtr pDacl,
|
||||
IntPtr pSacl);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
public static extern IntPtr GetCurrentProcess();
|
||||
#endregion
|
||||
}
|
||||
|
||||
public class ExistingProcess : Process
|
||||
{
|
||||
public ExistingProcess(IntPtr handle)
|
||||
{
|
||||
SetHandle(handle);
|
||||
}
|
||||
|
||||
private void SetHandle(IntPtr handle)
|
||||
{
|
||||
var baseType = GetType().BaseType;
|
||||
if (baseType == null)
|
||||
return;
|
||||
|
||||
var setProcessHandleMethod = baseType.GetMethod("SetProcessHandle",
|
||||
BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
setProcessHandleMethod?.Invoke(this, new object[] {new SafeProcessHandle(handle, true)});
|
||||
}
|
||||
}
|
||||
|
||||
public class GameExitedException : Exception
|
||||
{
|
||||
public GameExitedException()
|
||||
: base("Game exited prematurely.")
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public static Process LaunchGame(string workingDir, string exePath, string arguments, Action<Process> beforeResume)
|
||||
{
|
||||
Process process = null;
|
||||
|
||||
var userName = Environment.UserName;
|
||||
|
||||
var pExplicitAccess = new PInvoke.EXPLICIT_ACCESS();
|
||||
PInvoke.BuildExplicitAccessWithName(
|
||||
ref pExplicitAccess,
|
||||
userName,
|
||||
PInvoke.STANDARD_RIGHTS_ALL | PInvoke.SPECIFIC_RIGHTS_ALL & ~PInvoke.PROCESS_VM_WRITE,
|
||||
PInvoke.GRANT_ACCESS,
|
||||
0);
|
||||
|
||||
if (PInvoke.SetEntriesInAcl(1, ref pExplicitAccess, IntPtr.Zero, out var newAcl) != 0)
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
|
||||
var secDesc = new PInvoke.SECURITY_DESCRIPTOR();
|
||||
if (!PInvoke.InitializeSecurityDescriptor(out secDesc, PInvoke.SECURITY_DESCRIPTOR_REVISION))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
|
||||
if (!PInvoke.SetSecurityDescriptorDacl(ref secDesc, true, newAcl, false))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
|
||||
var psecDesc = Marshal.AllocHGlobal(Marshal.SizeOf<PInvoke.SECURITY_DESCRIPTOR>());
|
||||
Marshal.StructureToPtr<PInvoke.SECURITY_DESCRIPTOR>(secDesc, psecDesc, true);
|
||||
|
||||
var lpProcessInformation = new PInvoke.PROCESS_INFORMATION();
|
||||
try
|
||||
{
|
||||
var lpProcessAttributes = new PInvoke.SECURITY_ATTRIBUTES
|
||||
{
|
||||
nLength = Marshal.SizeOf<PInvoke.SECURITY_ATTRIBUTES>(),
|
||||
lpSecurityDescriptor = psecDesc,
|
||||
bInheritHandle = false
|
||||
};
|
||||
|
||||
var lpStartupInfo = new PInvoke.STARTUPINFO
|
||||
{
|
||||
cb = Marshal.SizeOf<PInvoke.STARTUPINFO>()
|
||||
};
|
||||
|
||||
var compatLayerPrev = Environment.GetEnvironmentVariable("__COMPAT_LAYER");
|
||||
|
||||
Environment.SetEnvironmentVariable("__COMPAT_LAYER", "RunAsInvoker");
|
||||
try
|
||||
{
|
||||
if (!PInvoke.CreateProcess(
|
||||
null,
|
||||
$"\"{exePath}\" {arguments}",
|
||||
ref lpProcessAttributes,
|
||||
IntPtr.Zero,
|
||||
false,
|
||||
PInvoke.CREATE_SUSPENDED,
|
||||
IntPtr.Zero,
|
||||
workingDir,
|
||||
ref lpStartupInfo,
|
||||
out lpProcessInformation))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Environment.SetEnvironmentVariable("__COMPAT_LAYER", compatLayerPrev);
|
||||
}
|
||||
|
||||
DisableSeDebug(lpProcessInformation.hProcess);
|
||||
|
||||
process = new ExistingProcess(lpProcessInformation.hProcess);
|
||||
|
||||
beforeResume?.Invoke(process);
|
||||
|
||||
PInvoke.ResumeThread(lpProcessInformation.hThread);
|
||||
|
||||
// Ensure that the game main window is prepared
|
||||
try
|
||||
{
|
||||
do
|
||||
{
|
||||
process.WaitForInputIdle();
|
||||
|
||||
Thread.Sleep(100);
|
||||
} while (IntPtr.Zero == TryFindGameWindow(process));
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
throw new GameExitedException();
|
||||
}
|
||||
|
||||
if (PInvoke.GetSecurityInfo(
|
||||
PInvoke.GetCurrentProcess(),
|
||||
PInvoke.SE_OBJECT_TYPE.SE_KERNEL_OBJECT,
|
||||
PInvoke.SECURITY_INFORMATION.DACL_SECURITY_INFORMATION,
|
||||
IntPtr.Zero, IntPtr.Zero,
|
||||
out var pACL,
|
||||
IntPtr.Zero, IntPtr.Zero) != 0)
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
|
||||
if (PInvoke.SetSecurityInfo(
|
||||
lpProcessInformation.hProcess,
|
||||
PInvoke.SE_OBJECT_TYPE.SE_KERNEL_OBJECT,
|
||||
PInvoke.SECURITY_INFORMATION.DACL_SECURITY_INFORMATION | PInvoke.SECURITY_INFORMATION.UNPROTECTED_DACL_SECURITY_INFORMATION,
|
||||
IntPtr.Zero, IntPtr.Zero, pACL, IntPtr.Zero) != 0)
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Error(ex, "[NativeAclFix] Uncaught error during initialization, trying to kill process");
|
||||
|
||||
try
|
||||
{
|
||||
process?.Kill();
|
||||
}
|
||||
catch (Exception killEx)
|
||||
{
|
||||
Log.Error(killEx, "[NativeAclFix] Could not kill process");
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(psecDesc);
|
||||
PInvoke.CloseHandle(lpProcessInformation.hThread);
|
||||
}
|
||||
|
||||
return process;
|
||||
}
|
||||
|
||||
private static void DisableSeDebug(IntPtr ProcessHandle)
|
||||
{
|
||||
if (!PInvoke.OpenProcessToken(ProcessHandle, PInvoke.TOKEN_QUERY | PInvoke.TOKEN_ADJUST_PRIVILEGES, out var TokenHandle))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
|
||||
var luidDebugPrivilege = new PInvoke.LUID();
|
||||
if (!PInvoke.LookupPrivilegeValue(null, "SeDebugPrivilege", ref luidDebugPrivilege))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
|
||||
var RequiredPrivileges = new PInvoke.PRIVILEGE_SET
|
||||
{
|
||||
PrivilegeCount = 1,
|
||||
Control = PInvoke.PRIVILEGE_SET_ALL_NECESSARY,
|
||||
Privilege = new PInvoke.LUID_AND_ATTRIBUTES[1]
|
||||
};
|
||||
|
||||
RequiredPrivileges.Privilege[0].Luid = luidDebugPrivilege;
|
||||
RequiredPrivileges.Privilege[0].Attributes = PInvoke.SE_PRIVILEGE_ENABLED;
|
||||
|
||||
if (!PInvoke.PrivilegeCheck(TokenHandle, ref RequiredPrivileges, out bool bResult))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
|
||||
if (bResult) // SeDebugPrivilege is enabled; try disabling it
|
||||
{
|
||||
var TokenPrivileges = new PInvoke.TOKEN_PRIVILEGES
|
||||
{
|
||||
PrivilegeCount = 1,
|
||||
Privileges = new PInvoke.LUID_AND_ATTRIBUTES[1]
|
||||
};
|
||||
|
||||
TokenPrivileges.Privileges[0].Luid = luidDebugPrivilege;
|
||||
TokenPrivileges.Privileges[0].Attributes = PInvoke.SE_PRIVILEGE_REMOVED;
|
||||
|
||||
if (!PInvoke.AdjustTokenPrivileges(TokenHandle, false, ref TokenPrivileges, 0, IntPtr.Zero, 0))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
}
|
||||
|
||||
PInvoke.CloseHandle(TokenHandle);
|
||||
}
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
private static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr hWndChildAfter, string className, IntPtr windowTitle);
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
static extern bool IsWindowVisible(IntPtr hWnd);
|
||||
|
||||
private static IntPtr TryFindGameWindow(Process process)
|
||||
{
|
||||
IntPtr hwnd = IntPtr.Zero;
|
||||
while (IntPtr.Zero != (hwnd = FindWindowEx(IntPtr.Zero, hwnd, "FFXIVGAME", IntPtr.Zero)))
|
||||
{
|
||||
GetWindowThreadProcessId(hwnd, out uint pid);
|
||||
|
||||
if (pid == process.Id && IsWindowVisible(hwnd))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
return hwnd;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue