Calling CreateProcessAsUser from C#

后端 未结 3 886
暗喜
暗喜 2020-12-08 09:11

I\'ve been attempting to create a new process under the context of a specific user using the CreateProcessAsUser function of the Windows API, but seem to be run

相关标签:
3条回答
  • 2020-12-08 09:24

    Jonathan Peppers provided this great piece of code that fixed my issues

    http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/0c0ca087-5e7b-4046-93cb-c7b3e48d0dfb?ppud=4

    0 讨论(0)
  • 2020-12-08 09:26

    Ahh... seems liker I've been caught out by one of the biggest gotchas in WinAPI interop programming. Also, Posting the code for my function declarations would have been a wise idea in this case.

    Anyway, all that I needed to do was add an argument to the DllImport attribute of the function specifying CharSet = CharSet.Unicode. This did the trick for both the CreateProcessWithLogonW and CreateProcessWithTokenW functions. I guess it finally just hit me that the W suffix of the function names referred to Unicode and that I needed to explicitly specify this in C#! Here are the correct function declarations in case anyone is interested:

    [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true)]
    public static extern bool CreateProcessWithLogonW(string principal, string authority,
        string password, LogonFlags logonFlags, string appName, string cmdLine,
        CreationFlags creationFlags, IntPtr environmentBlock, string currentDirectory,
        ref STARTUPINFO startupInfo, out PROCESS_INFORMATION processInfo);
    
    [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true)]
    public static extern bool CreateProcessWithTokenW(IntPtr hToken, LogonFlags dwLogonFlags,
        string lpApplicationName, string lpCommandLine, CreationFlags dwCreationFlags,
        IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo,
        out PROCESS_INFORMATION lpProcessInformation);
    
    0 讨论(0)
  • 2020-12-08 09:44

    From here:

    Typically, the process that calls the CreateProcessAsUser function must have the SE_ASSIGNPRIMARYTOKEN_NAME and SE_INCREASE_QUOTA_NAME privileges. If this function fails with ERROR_PRIVILEGE_NOT_HELD (1314), use the CreateProcessWithLogonW function instead. CreateProcessWithLogonW requires no special privileges, but the specified user account must be allowed to log on interactively. Generally, it is best to use CreateProcessWithLogonW to create a process with alternate credentials.

    See this blog post How to call CreateProcessWithLogonW & CreateProcessAsUser in .NET

    0 讨论(0)
提交回复
热议问题