Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 163415
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T11:33:48+00:00 2026-05-11T11:33:48+00:00

I’ve been attempting to create a new process under the context of a specific

  • 0

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 running into a rather nasty security issue…

Before I explain any further, here’s the code I’m currently using to start the new process (a console process – PowerShell to be specific, though it shouldn’t matter).

    private void StartProcess()     {         bool retValue;          // Create startup info for new console process.         var startupInfo = new STARTUPINFO();         startupInfo.cb = Marshal.SizeOf(startupInfo);         startupInfo.dwFlags = StartFlags.STARTF_USESHOWWINDOW;         startupInfo.wShowWindow = _consoleVisible ? WindowShowStyle.Show : WindowShowStyle.Hide;         startupInfo.lpTitle = this.ConsoleTitle ?? 'Console';          var procAttrs = new SECURITY_ATTRIBUTES();         var threadAttrs = new SECURITY_ATTRIBUTES();         procAttrs.nLength = Marshal.SizeOf(procAttrs);         threadAttrs.nLength = Marshal.SizeOf(threadAttrs);          // Log on user temporarily in order to start console process in its security context.         var hUserToken = IntPtr.Zero;         var hUserTokenDuplicate = IntPtr.Zero;         var pEnvironmentBlock = IntPtr.Zero;         var pNewEnvironmentBlock = IntPtr.Zero;          if (!WinApi.LogonUser('UserName', null, 'Password',             LogonType.Interactive, LogonProvider.Default, out hUserToken))             throw new Win32Exception(Marshal.GetLastWin32Error(), 'Error logging on user.');          var duplicateTokenAttrs = new SECURITY_ATTRIBUTES();         duplicateTokenAttrs.nLength = Marshal.SizeOf(duplicateTokenAttrs);         if (!WinApi.DuplicateTokenEx(hUserToken, 0, ref duplicateTokenAttrs,             SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary,             out hUserTokenDuplicate))             throw new Win32Exception(Marshal.GetLastWin32Error(), 'Error duplicating user token.');          try         {             // Get block of environment vars for logged on user.             if (!WinApi.CreateEnvironmentBlock(out pEnvironmentBlock, hUserToken, false))                 throw new Win32Exception(Marshal.GetLastWin32Error(),                     'Error getting block of environment variables for user.');              // Read block as array of strings, one per variable.             var envVars = ReadEnvironmentVariables(pEnvironmentBlock);              // Append custom environment variables to list.             foreach (var var in this.EnvironmentVariables)                 envVars.Add(var.Key + '=' + var.Value);              // Recreate environment block from array of variables.             var newEnvironmentBlock = string.Join('\0', envVars.ToArray()) + '\0';             pNewEnvironmentBlock = Marshal.StringToHGlobalUni(newEnvironmentBlock);              // Start new console process.             retValue = WinApi.CreateProcessAsUser(hUserTokenDuplicate, null, this.CommandLine,                 ref procAttrs, ref threadAttrs, false, CreationFlags.CREATE_NEW_CONSOLE |                 CreationFlags.CREATE_SUSPENDED | CreationFlags.CREATE_UNICODE_ENVIRONMENT,                 pNewEnvironmentBlock, null, ref startupInfo, out _processInfo);             if (!retValue) throw new Win32Exception(Marshal.GetLastWin32Error(),                 'Unable to create new console process.');         }         catch         {             // Catch any exception thrown here so as to prevent any malicious program operating             // within the security context of the logged in user.              // Clean up.             if (hUserToken != IntPtr.Zero)             {                 WinApi.CloseHandle(hUserToken);                 hUserToken = IntPtr.Zero;             }              if (hUserTokenDuplicate != IntPtr.Zero)             {                 WinApi.CloseHandle(hUserTokenDuplicate);                 hUserTokenDuplicate = IntPtr.Zero;             }              if (pEnvironmentBlock != IntPtr.Zero)             {                 WinApi.DestroyEnvironmentBlock(pEnvironmentBlock);                 pEnvironmentBlock = IntPtr.Zero;             }              if (pNewEnvironmentBlock != IntPtr.Zero)             {                 Marshal.FreeHGlobal(pNewEnvironmentBlock);                 pNewEnvironmentBlock = IntPtr.Zero;             }              throw;         }         finally         {             // Clean up.             if (hUserToken != IntPtr.Zero)                 WinApi.CloseHandle(hUserToken);              if (hUserTokenDuplicate != IntPtr.Zero)                 WinApi.CloseHandle(hUserTokenDuplicate);              if (pEnvironmentBlock != IntPtr.Zero)                 WinApi.DestroyEnvironmentBlock(pEnvironmentBlock);              if (pNewEnvironmentBlock != IntPtr.Zero)                 Marshal.FreeHGlobal(pNewEnvironmentBlock);         }          _process = Process.GetProcessById(_processInfo.dwProcessId);     } 

For the sake of the issue here, ignore the code dealing with the environment variables (I’ve tested that section independently and it seems to work.)

Now, the error I get is the following (thrown at the line following the call to CreateProcessAsUSer):

‘A required privilege is not held by the client’ (error code 1314)

(The error message was discovered by removing the message parameter from the Win32Exception constructor. Admittedly, my error handling code here may not be the best, but that’s a somewhat irrelevant matter. You’re welcome to comment on it if you wish, however.) I’m really quite confused as to the cause of this vague error in this situation. MSDN documentation and various forum threads have only given me so much advice, and especially given that the causes for such errors appear to be widely varied, I have no idea which section of code I need to modify. Perhaps it is simply a single parameter I need to change, but I could be making the wrong/not enough WinAPI calls for all I know. What confuses me greatly is that the previous version of the code that uses the plain CreateProcess function (equivalent except for the user token parameter) worked perfectly fine. As I understand, it is only necessary to call the Logon user function to receive the appropriate token handle and then duplicate it so that it can be passed to CreateProcessAsUser.

Any suggestions for modifications to the code as well as explanations would be very welcome.

Notes

I’ve been primarily referring to the MSDN docs (as well as PInvoke.net for the C# function/strut/enum declarations). The following pages in particular seem to have a lot of information in the Remarks sections, some of which may be important and eluding me:

  • CreateProcessAsUser function
  • LogonUser function
  • DuplicateTokenEx function

Edit

I’ve just tried out Mitch’s suggestion, but unfortunately the old error has just been replaced by a new one: ‘The system cannot find the file specified.’ (error code 2)

The previous call to CreateProcessAsUser was replaced with the following:

retValue = WinApi.CreateProcessWithTokenW(hUserToken, LogonFlags.WithProfile, null,     this.CommandLine, CreationFlags.CREATE_NEW_CONSOLE |     CreationFlags.CREATE_SUSPENDED | CreationFlags.CREATE_UNICODE_ENVIRONMENT,     pNewEnvironmentBlock, null, ref startupInfo, out _processInfo); 

Note that this code no longer uses the duplicate token but rather the original, as the MSDN docs appear to suggest.

And here’s another attempt using CreateProcessWithLogonW. The error this time is ‘Logon failure: unknown user name or bad password’ (error code 1326)

retValue = WinApi.CreateProcessWithLogonW('Alex', null, 'password',     LogonFlags.WithProfile, null, this.CommandLine,     CreationFlags.CREATE_NEW_CONSOLE | CreationFlags.CREATE_SUSPENDED |     CreationFlags.CREATE_UNICODE_ENVIRONMENT, pNewEnvironmentBlock,     null, ref startupInfo, out _processInfo); 

I’ve also tried specifying the username in UPN format (‘Alex@Alex-PC’) and passing the domain independently as the second argument, all to no avail (identical error).

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T11:33:49+00:00Added an answer on May 11, 2026 at 11:33 am

    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
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 99k
  • Answers 99k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Here is an approach, in psuedo-code: inches_per_meter = 39.3700787 inches_total… May 11, 2026 at 7:41 pm
  • Editorial Team
    Editorial Team added an answer uses JclStrings; S := StrKeepChars('mystring', ['A'..'Z', 'a'..'z', '0'..'9']); May 11, 2026 at 7:41 pm
  • Editorial Team
    Editorial Team added an answer Short answer: No. If you do not specify a value… May 11, 2026 at 7:41 pm

Related Questions

I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I am currently running into a problem where an element is coming back from
Seemingly simple, but I cannot find anything relevant on the web. What is the
Configuring TinyMCE to allow for tags, based on a customer requirement. My config is
Is it possible to replace javascript w/ HTML if JavaScript is not enabled on

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.