Home > Net >  How to create a process as a another user without a password in C#?
How to create a process as a another user without a password in C#?

Time:11-24

I'm trying to create something in C# like sudo for Linux. I found a way to run the process as a different user using the password, but I want to do this without the password.

Also, my C# software is running as Administrator and has passed UAC.

My currently Code:

static void CreateProcessAsUser(string name, string path, SecureString password)
{
    Process proc = new Process();

    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.FileName = path;
    proc.StartInfo.UserName = name;
    proc.StartInfo.Password = password;

    proc.Start();
}

Thank you.

CodePudding user response:

Windows is not Linux, so you cannot expect a feature just like sudo.

No matter which programming language (C# or C ) you use, deep down inside you need to call RunProcessAsUser (no, not your current code as yours is far too simple for the purpose) to initialize a process running as another user account. This API in turn wants a user token, which you either create with user credentials (aka password) via LogonUser, or clone from an existing token via DuplicateToken.

So the only way to avoid password is to find a valid user token already on this machine (once that user logs on).

You might wonder what applications use such a complex mechanism and why. One example is your antivirus software, whose main component is a Windows service running as administrator. This service detects who logs on to the machine and then launches a tray icon application. (That's the perfect time to duplicate a user token and create a process as that user.)

If your goal is not to cover similar scenarios, I wonder whether you should continue on this path.

  • Related