[英]How to impersonate current process as SYSTEM on windows xp?
Process originaly runs as user (with admin privileges).进程最初以用户身份运行(具有管理员权限)。 In some point I want to rename file owned by user SYSTEM.在某些时候我想重命名用户 SYSTEM 拥有的文件。 So I need to impersonate my process as SYSTEM.所以我需要将我的进程模拟为 SYSTEM。
I have code that works correct on any windows later XP (and 2003):我的代码在任何 windows 以后的 XP(和 2003)上都能正常工作:
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool OpenProcessToken(IntPtr processHandle, uint desiredAccess, out IntPtr tokenHandle);
...
var systemProcessId = Process.GetProcessesByName("wininit").First().Id;
var handle = OpenProcess(ProcessAllAccess, false, systemProcessId);
private IntPtr _token;
OpenProcessToken(handle, (uint) TokenAccessLevels.MaximumAllowed, out _token)
WindowsIdentity.Impersonate(_token);
It doesn't work on Windows XP (and 2003).它不适用于 Windows XP(和 2003)。 How can I get same result on XP and 2003?如何在 XP 和 2003 上获得相同的结果?
I suppose you can try to do something like this:我想你可以尝试做这样的事情:
var handle = Kernel32.OpenProcess(PROCESS_QUERY_INFORMATION, false,
**smss.exe**);
if (handle.IsInvalid)
throw new Exception("Can't open system process for access.");
if (!AdvApi32.OpenProcessToken(handle.DangerousGetHandle(),
WRITE_DAC, out var token))
throw new Exception($"OpenProcessToken failed, error code: {GetLastError()}");
if (!ConvertStringSecurityDescriptorToSecurityDescriptor("O:BAG:BAD:P(A;CIOI;GA;;;BA)", 1, out var pSd, out _))
throw new Exception(
$"ConvertStringSecurityDescriptorToSecurityDescriptor failed, error code: [{GetLastError()}]");
if (!SetKernelObjectSecurity(token.DangerousGetHandle(),
DACL_SECURITY_INFORMATION, pSd))
throw new Exception($"SetKernelObjectSecurity failed, error code: {GetLastError()}");
if (!token.IsInvalid && !token.IsClosed)
token.Close();
if (!AdvApi32.OpenProcessToken(handle.DangerousGetHandle(),
TOKEN_DUPLICATE,
out token))
throw new Exception($"OpenProcessToken failed, error code: {GetLastError()}");
if (!AdvApi32.DuplicateTokenEx(token,
TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY,
null,
SecurityImpersonation,
TokenPrimary,
out var newToken))
throw new Exception($"DuplicateTokenEx failed, error code: {GetLastError()}");
if (!token.IsInvalid && !token.IsClosed)
token.Close();
WindowsIdentity.Impersonate(newToken.DangerousGetHandle());
I really, really think it's working code on Windows XP.我真的,真的认为它是 Windows XP 上的工作代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.