Advertisement
Guest User

Untitled

a guest
Mar 13th, 2013
2,812
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 17.48 KB | None | 0 0
  1.  
  2.     internal class ApplicationLauncher
  3.     {
  4.         public enum TOKEN_INFORMATION_CLASS
  5.         {
  6.             TokenUser = 1,
  7.             TokenGroups,
  8.             TokenPrivileges,
  9.             TokenOwner,
  10.             TokenPrimaryGroup,
  11.             TokenDefaultDacl,
  12.             TokenSource,
  13.             TokenType,
  14.             TokenImpersonationLevel,
  15.             TokenStatistics,
  16.             TokenRestrictedSids,
  17.             TokenSessionId,
  18.             TokenGroupsAndPrivileges,
  19.             TokenSessionReference,
  20.             TokenSandBoxInert,
  21.             TokenAuditPolicy,
  22.             TokenOrigin,
  23.             MaxTokenInfoClass // MaxTokenInfoClass should always be the last enum
  24.         }
  25.  
  26.         public const int READ_CONTROL = 0x00020000;
  27.  
  28.         public const int STANDARD_RIGHTS_REQUIRED = 0x000F0000;
  29.  
  30.         public const int STANDARD_RIGHTS_READ = READ_CONTROL;
  31.         public const int STANDARD_RIGHTS_WRITE = READ_CONTROL;
  32.         public const int STANDARD_RIGHTS_EXECUTE = READ_CONTROL;
  33.  
  34.         public const int STANDARD_RIGHTS_ALL = 0x001F0000;
  35.  
  36.         public const int SPECIFIC_RIGHTS_ALL = 0x0000FFFF;
  37.  
  38.         public const int TOKEN_ASSIGN_PRIMARY = 0x0001;
  39.         public const int TOKEN_DUPLICATE = 0x0002;
  40.         public const int TOKEN_IMPERSONATE = 0x0004;
  41.         public const int TOKEN_QUERY = 0x0008;
  42.         public const int TOKEN_QUERY_SOURCE = 0x0010;
  43.         public const int TOKEN_ADJUST_PRIVILEGES = 0x0020;
  44.         public const int TOKEN_ADJUST_GROUPS = 0x0040;
  45.         public const int TOKEN_ADJUST_DEFAULT = 0x0080;
  46.         public const int TOKEN_ADJUST_SESSIONID = 0x0100;
  47.  
  48.         public const int TOKEN_ALL_ACCESS_P = (STANDARD_RIGHTS_REQUIRED |
  49.                                                TOKEN_ASSIGN_PRIMARY |
  50.                                                TOKEN_DUPLICATE |
  51.                                                TOKEN_IMPERSONATE |
  52.                                                TOKEN_QUERY |
  53.                                                TOKEN_QUERY_SOURCE |
  54.                                                TOKEN_ADJUST_PRIVILEGES |
  55.                                                TOKEN_ADJUST_GROUPS |
  56.                                                TOKEN_ADJUST_DEFAULT);
  57.  
  58.         public const int TOKEN_ALL_ACCESS = TOKEN_ALL_ACCESS_P | TOKEN_ADJUST_SESSIONID;
  59.  
  60.         public const int TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY;
  61.  
  62.         public const int TOKEN_WRITE = STANDARD_RIGHTS_WRITE |
  63.                                        TOKEN_ADJUST_PRIVILEGES |
  64.                                        TOKEN_ADJUST_GROUPS |
  65.                                        TOKEN_ADJUST_DEFAULT;
  66.  
  67.         public const int TOKEN_EXECUTE = STANDARD_RIGHTS_EXECUTE;
  68.  
  69.         public const uint MAXIMUM_ALLOWED = 0x2000000;
  70.  
  71.         public const int CREATE_NEW_PROCESS_GROUP = 0x00000200;
  72.         public const int CREATE_UNICODE_ENVIRONMENT = 0x00000400;
  73.  
  74.         public const int IDLE_PRIORITY_CLASS = 0x40;
  75.         public const int NORMAL_PRIORITY_CLASS = 0x20;
  76.         public const int HIGH_PRIORITY_CLASS = 0x80;
  77.         public const int REALTIME_PRIORITY_CLASS = 0x100;
  78.  
  79.         public const int CREATE_NEW_CONSOLE = 0x00000010;
  80.  
  81.         public const string SE_DEBUG_NAME = "SeDebugPrivilege";
  82.         public const string SE_RESTORE_NAME = "SeRestorePrivilege";
  83.         public const string SE_BACKUP_NAME = "SeBackupPrivilege";
  84.  
  85.         public const int SE_PRIVILEGE_ENABLED = 0x0002;
  86.  
  87.         public const int ERROR_NOT_ALL_ASSIGNED = 1300;
  88.  
  89.         private const uint TH32CS_SNAPPROCESS = 0x00000002;
  90.  
  91.         public static int INVALID_HANDLE_VALUE = -1;
  92.  
  93.         [DllImport("advapi32.dll", SetLastError = true)]
  94.         public static extern bool LookupPrivilegeValue(IntPtr lpSystemName, string lpname,
  95.             [MarshalAs(UnmanagedType.Struct)] ref LUID lpLuid);
  96.  
  97.         [DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi,
  98.             CallingConvention = CallingConvention.StdCall)]
  99.         public static extern bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine,
  100.             ref SECURITY_ATTRIBUTES lpProcessAttributes,
  101.             ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment,
  102.             String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
  103.  
  104.         [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  105.         public static extern bool DuplicateToken(IntPtr ExistingTokenHandle,
  106.             int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
  107.  
  108.         [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")]
  109.         public static extern bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess,
  110.             ref SECURITY_ATTRIBUTES lpThreadAttributes, int TokenType,
  111.             int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);
  112.  
  113.         [DllImport("advapi32.dll", SetLastError = true)]
  114.         public static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges,
  115.             ref TOKEN_PRIVILEGES NewState, int BufferLength, IntPtr PreviousState, IntPtr ReturnLength);
  116.  
  117.         [DllImport("advapi32.dll", SetLastError = true)]
  118.         public static extern bool SetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass,
  119.             ref uint TokenInformation, uint TokenInformationLength);
  120.  
  121.         [DllImport("userenv.dll", SetLastError = true)]
  122.         public static extern bool CreateEnvironmentBlock(ref IntPtr lpEnvironment, IntPtr hToken, bool bInherit);
  123.  
  124.         public static bool CreateProcessInConsoleSession(String CommandLine, bool bElevate)
  125.         {
  126.  
  127.             PROCESS_INFORMATION pi;
  128.  
  129.             bool bResult = false;
  130.             uint dwSessionId, winlogonPid = 0;
  131.             IntPtr hUserToken = IntPtr.Zero, hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero, hProcess = IntPtr.Zero;
  132.  
  133.             Debug.Print("CreateProcessInConsoleSession");
  134.             // Log the client on to the local computer.
  135.             dwSessionId = WTSGetActiveConsoleSessionId();
  136.  
  137.             // Find the winlogon process
  138.             var procEntry = new PROCESSENTRY32();
  139.  
  140.             uint hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  141.             if (hSnap == INVALID_HANDLE_VALUE)
  142.             {
  143.                 return false;
  144.             }
  145.  
  146.             procEntry.dwSize = (uint) Marshal.SizeOf(procEntry); //sizeof(PROCESSENTRY32);
  147.  
  148.             if (Process32First(hSnap, ref procEntry) == 0)
  149.             {
  150.                 return false;
  151.             }
  152.  
  153.             String strCmp = "explorer.exe";
  154.             do
  155.             {
  156.                 if (strCmp.IndexOf(procEntry.szExeFile) == 0)
  157.                 {
  158.                     // We found a winlogon process...make sure it's running in the console session
  159.                     uint winlogonSessId = 0;
  160.                     if (ProcessIdToSessionId(procEntry.th32ProcessID, ref winlogonSessId) &&
  161.                         winlogonSessId == dwSessionId)
  162.                     {
  163.                         winlogonPid = procEntry.th32ProcessID;
  164.                         break;
  165.                     }
  166.                 }
  167.             }
  168.             while (Process32Next(hSnap, ref procEntry) != 0);
  169.  
  170.             //Get the user token used by DuplicateTokenEx
  171.             WTSQueryUserToken(dwSessionId, ref hUserToken);
  172.  
  173.             var si = new STARTUPINFO();
  174.             si.cb = Marshal.SizeOf(si);
  175.             si.lpDesktop = "winsta0\\default";
  176.             var tp = new TOKEN_PRIVILEGES();
  177.             var luid = new LUID();
  178.             hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);
  179.  
  180.             if (
  181.                 !OpenProcessToken(hProcess,
  182.                     TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY
  183.                     | TOKEN_ADJUST_SESSIONID | TOKEN_READ | TOKEN_WRITE, ref hPToken))
  184.             {
  185.                 Debug.Print(String.Format("CreateProcessInConsoleSession OpenProcessToken error: {0}",
  186.                     Marshal.GetLastWin32Error()));
  187.             }
  188.  
  189.             if (!LookupPrivilegeValue(IntPtr.Zero, SE_DEBUG_NAME, ref luid))
  190.             {
  191.                 Debug.Print(String.Format("CreateProcessInConsoleSession LookupPrivilegeValue error: {0}",
  192.                     Marshal.GetLastWin32Error()));
  193.             }
  194.  
  195.             var sa = new SECURITY_ATTRIBUTES();
  196.             sa.Length = Marshal.SizeOf(sa);
  197.  
  198.             if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa,
  199.                     (int) SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int) TOKEN_TYPE.TokenPrimary,
  200.                     ref hUserTokenDup))
  201.             {
  202.                 Debug.Print(
  203.                     String.Format(
  204.                         "CreateProcessInConsoleSession DuplicateTokenEx error: {0} Token does not have the privilege.",
  205.                         Marshal.GetLastWin32Error()));
  206.                 CloseHandle(hProcess);
  207.                 CloseHandle(hUserToken);
  208.                 CloseHandle(hPToken);
  209.                 return false;
  210.             }
  211.  
  212.             if (bElevate)
  213.             {
  214.                 //tp.Privileges[0].Luid = luid;
  215.                 //tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  216.  
  217.                 tp.PrivilegeCount = 1;
  218.                 tp.Privileges = new int[3];
  219.                 tp.Privileges[2] = SE_PRIVILEGE_ENABLED;
  220.                 tp.Privileges[1] = luid.HighPart;
  221.                 tp.Privileges[0] = luid.LowPart;
  222.  
  223.                 //Adjust Token privilege
  224.                 if (
  225.                     !SetTokenInformation(hUserTokenDup, TOKEN_INFORMATION_CLASS.TokenSessionId, ref dwSessionId,
  226.                         (uint) IntPtr.Size))
  227.                 {
  228.                     Debug.Print(
  229.                         String.Format(
  230.                             "CreateProcessInConsoleSession SetTokenInformation error: {0} Token does not have the privilege.",
  231.                             Marshal.GetLastWin32Error()));
  232.                     //CloseHandle(hProcess);
  233.                     //CloseHandle(hUserToken);
  234.                     //CloseHandle(hPToken);
  235.                     //CloseHandle(hUserTokenDup);
  236.                     //return false;
  237.                 }
  238.                 if (
  239.                     !AdjustTokenPrivileges(hUserTokenDup, false, ref tp, Marshal.SizeOf(tp), /*(PTOKEN_PRIVILEGES)*/
  240.                         IntPtr.Zero, IntPtr.Zero))
  241.                 {
  242.                     int nErr = Marshal.GetLastWin32Error();
  243.  
  244.                     if (nErr == ERROR_NOT_ALL_ASSIGNED)
  245.                     {
  246.                         Debug.Print(
  247.                             String.Format(
  248.                                 "CreateProcessInConsoleSession AdjustTokenPrivileges error: {0} Token does not have the privilege.",
  249.                                 nErr));
  250.                     }
  251.                     else
  252.                     {
  253.                         Debug.Print(String.Format("CreateProcessInConsoleSession AdjustTokenPrivileges error: {0}", nErr));
  254.                     }
  255.                 }
  256.             }
  257.  
  258.             uint dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;
  259.             IntPtr pEnv = IntPtr.Zero;
  260.             if (CreateEnvironmentBlock(ref pEnv, hUserTokenDup, true))
  261.             {
  262.                 dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT;
  263.             }
  264.             else
  265.             {
  266.                 pEnv = IntPtr.Zero;
  267.             }
  268.             // Launch the process in the client's logon session.
  269.             bResult = CreateProcessAsUser(hUserTokenDup, // client's access token
  270.                 null, // file to execute
  271.                 CommandLine, // command line
  272.                 ref sa, // pointer to process SECURITY_ATTRIBUTES
  273.                 ref sa, // pointer to thread SECURITY_ATTRIBUTES
  274.                 false, // handles are not inheritable
  275.                 (int) dwCreationFlags, // creation flags
  276.                 pEnv, // pointer to new environment block
  277.                 null, // name of current directory
  278.                 ref si, // pointer to STARTUPINFO structure
  279.                 out pi // receives information about new process
  280.                 );
  281.             // End impersonation of client.
  282.  
  283.             //GetLastError should be 0
  284.             int iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error();
  285.  
  286.             //Close handles task
  287.             CloseHandle(hProcess);
  288.             CloseHandle(hUserToken);
  289.             CloseHandle(hUserTokenDup);
  290.             CloseHandle(hPToken);
  291.  
  292.             return (iResultOfCreateProcessAsUser == 0) ? true : false;
  293.         }
  294.  
  295.         [DllImport("kernel32.dll")]
  296.         private static extern int Process32First(uint hSnapshot, ref PROCESSENTRY32 lppe);
  297.  
  298.         [DllImport("kernel32.dll")]
  299.         private static extern int Process32Next(uint hSnapshot, ref PROCESSENTRY32 lppe);
  300.  
  301.         [DllImport("kernel32.dll", SetLastError = true)]
  302.         private static extern uint CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);
  303.  
  304.         [DllImport("kernel32.dll", SetLastError = true)]
  305.         private static extern bool CloseHandle(IntPtr hSnapshot);
  306.  
  307.         [DllImport("kernel32.dll")]
  308.         private static extern uint WTSGetActiveConsoleSessionId();
  309.  
  310.         [DllImport("Wtsapi32.dll")]
  311.         private static extern uint WTSQueryUserToken(uint SessionId, ref IntPtr phToken);
  312.  
  313.         [DllImport("kernel32.dll")]
  314.         private static extern bool ProcessIdToSessionId(uint dwProcessId, ref uint pSessionId);
  315.  
  316.         [DllImport("kernel32.dll")]
  317.         private static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);
  318.  
  319.         [DllImport("advapi32", SetLastError = true)]
  320.         [SuppressUnmanagedCodeSecurity]
  321.         private static extern bool OpenProcessToken(IntPtr ProcessHandle, // handle to process
  322.             int DesiredAccess, // desired access to process
  323.             ref IntPtr TokenHandle);
  324.  
  325.         #region Nested type: LUID
  326.  
  327.         [StructLayout(LayoutKind.Sequential)]
  328.         internal struct LUID
  329.         {
  330.             public int LowPart;
  331.             public int HighPart;
  332.         }
  333.  
  334.         #endregion
  335.  
  336.         //end struct
  337.  
  338.         #region Nested type: LUID_AND_ATRIBUTES
  339.  
  340.         [StructLayout(LayoutKind.Sequential)]
  341.         internal struct LUID_AND_ATRIBUTES
  342.         {
  343.             public LUID Luid;
  344.             public int Attributes;
  345.         }
  346.  
  347.         #endregion
  348.  
  349.         #region Nested type: PROCESSENTRY32
  350.  
  351.         [StructLayout(LayoutKind.Sequential)]
  352.         private struct PROCESSENTRY32
  353.         {
  354.             public uint dwSize;
  355.             public readonly uint cntUsage;
  356.             public readonly uint th32ProcessID;
  357.             public readonly IntPtr th32DefaultHeapID;
  358.             public readonly uint th32ModuleID;
  359.             public readonly uint cntThreads;
  360.             public readonly uint th32ParentProcessID;
  361.             public readonly int pcPriClassBase;
  362.             public readonly uint dwFlags;
  363.  
  364.             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
  365.             public readonly string szExeFile;
  366.         }
  367.  
  368.         #endregion
  369.  
  370.         #region Nested type: PROCESS_INFORMATION
  371.  
  372.         [StructLayout(LayoutKind.Sequential)]
  373.         public struct PROCESS_INFORMATION
  374.         {
  375.             public IntPtr hProcess;
  376.             public IntPtr hThread;
  377.             public uint dwProcessId;
  378.             public uint dwThreadId;
  379.         }
  380.  
  381.         #endregion
  382.  
  383.         #region Nested type: SECURITY_ATTRIBUTES
  384.  
  385.         [StructLayout(LayoutKind.Sequential)]
  386.         public struct SECURITY_ATTRIBUTES
  387.         {
  388.             public int Length;
  389.             public IntPtr lpSecurityDescriptor;
  390.             public bool bInheritHandle;
  391.         }
  392.  
  393.         #endregion
  394.  
  395.         #region Nested type: SECURITY_IMPERSONATION_LEVEL
  396.  
  397.         private enum SECURITY_IMPERSONATION_LEVEL
  398.         {
  399.             SecurityAnonymous = 0,
  400.             SecurityIdentification = 1,
  401.             SecurityImpersonation = 2,
  402.             SecurityDelegation = 3,
  403.         }
  404.  
  405.         #endregion
  406.  
  407.         #region Nested type: STARTUPINFO
  408.  
  409.         [StructLayout(LayoutKind.Sequential)]
  410.         public struct STARTUPINFO
  411.         {
  412.             public int cb;
  413.             public String lpReserved;
  414.             public String lpDesktop;
  415.             public String lpTitle;
  416.             public uint dwX;
  417.             public uint dwY;
  418.             public uint dwXSize;
  419.             public uint dwYSize;
  420.             public uint dwXCountChars;
  421.             public uint dwYCountChars;
  422.             public uint dwFillAttribute;
  423.             public uint dwFlags;
  424.             public short wShowWindow;
  425.             public short cbReserved2;
  426.             public IntPtr lpReserved2;
  427.             public IntPtr hStdInput;
  428.             public IntPtr hStdOutput;
  429.             public IntPtr hStdError;
  430.         }
  431.  
  432.         #endregion
  433.  
  434.         #region Nested type: TOKEN_PRIVILEGES
  435.  
  436.         [StructLayout(LayoutKind.Sequential)]
  437.         internal struct TOKEN_PRIVILEGES
  438.         {
  439.             internal int PrivilegeCount;
  440.             //LUID_AND_ATRIBUTES
  441.             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
  442.             internal int[] Privileges;
  443.         }
  444.  
  445.         #endregion
  446.  
  447.         #region Nested type: TOKEN_TYPE
  448.  
  449.         private enum TOKEN_TYPE
  450.         {
  451.             TokenPrimary = 1,
  452.             TokenImpersonation = 2
  453.         }
  454.  
  455.         #endregion
  456.  
  457.         // handle to open access token
  458.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement