Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [StructLayout(LayoutKind.Sequential)]
- public struct SECURITY_ATTRIBUTES
- {
- public int nLength;
- public IntPtr lpSecurityDescriptor;
- public int bInheritHandle;
- }
- [StructLayout(LayoutKind.Sequential)]
- internal struct PROCESS_INFORMATION
- {
- public IntPtr hProcess;
- public IntPtr hThread;
- public int dwProcessId;
- public int dwThreadId;
- }
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- struct STARTUPINFO
- {
- public Int32 cb;
- public string lpReserved;
- public string lpDesktop;
- public string lpTitle;
- public Int32 dwX;
- public Int32 dwY;
- public Int32 dwXSize;
- public Int32 dwYSize;
- public Int32 dwXCountChars;
- public Int32 dwYCountChars;
- public Int32 dwFillAttribute;
- public Int32 dwFlags;
- public Int16 wShowWindow;
- public Int16 cbReserved2;
- public IntPtr lpReserved2;
- public IntPtr hStdInput;
- public IntPtr hStdOutput;
- public IntPtr hStdError;
- }
- public enum SECURITY_IMPERSONATION_LEVEL
- {
- SecurityAnonymous,
- SecurityIdentification,
- SecurityImpersonation,
- SecurityDelegation
- }
- public enum TOKEN_TYPE
- {
- TokenPrimary = 1,
- TokenImpersonation
- }
- [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
- public extern static bool DuplicateTokenEx(
- IntPtr hExistingToken,
- uint dwDesiredAccess,
- ref SECURITY_ATTRIBUTES lpTokenAttributes,
- SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
- TOKEN_TYPE TokenType,
- ref IntPtr phNewToken);
- [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
- static extern bool CreateProcessAsUser(
- IntPtr hToken,
- string lpApplicationName,
- string lpCommandLine,
- ref SECURITY_ATTRIBUTES lpProcessAttributes,
- ref SECURITY_ATTRIBUTES lpThreadAttributes,
- bool bInheritHandles,
- uint dwCreationFlags,
- IntPtr lpEnvironment,
- string lpCurrentDirectory,
- ref STARTUPINFO lpStartupInfo,
- ref PROCESS_INFORMATION lpProcessInformation);
- public static Process CreateProcessAsUser(string filename, string args)
- {
- IntPtr hToken = WindowsIdentity.GetCurrent().Token;
- IntPtr hDupedToken = IntPtr.Zero;
- PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
- SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
- sa.nLength = Marshal.SizeOf(sa);
- DuplicateTokenEx(hToken,
- (uint)0,
- ref sa,
- SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
- TOKEN_TYPE.TokenPrimary,
- ref hDupedToken);
- STARTUPINFO si = new STARTUPINFO();
- si.cb = Marshal.SizeOf(si);
- si.lpDesktop = string.Empty;
- string path = Path.GetFullPath(filename);
- using (WindowsIdentity.Impersonate(IntPtr.Zero))
- {
- CreateProcessAsUser(hDupedToken,
- path,
- string.Format("\"{0}\" {1}", filename.Replace("\"", "\"\""), args),
- ref sa,
- ref sa,
- false,
- 0,
- IntPtr.Zero,
- @".\",
- ref si,
- ref pi);
- }
- return Process.GetProcessById(pi.dwProcessId);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement