0

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.

Peyang
  • 77
  • 8
  • Let's call the user your software is trying to run a process as user2. Does user2's account have a password, and you're trying to get your code to run a process without knowing that password? Or does user2 not have a password at all? – VentricleV Nov 22 '21 at 23:39
  • It is the former. User2 has password certification. The process was running with Administrator authority, so I thought it was possible, but isn't it? – Peyang Nov 23 '21 at 00:05

1 Answers1

5

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.

Lex Li
  • 60,503
  • 9
  • 116
  • 147
  • In addition to Lex's answer, here's further reading to help explain it: https://stackoverflow.com/questions/125341/how-do-you-do-impersonation-in-net – Jeremy Thompson Nov 23 '21 at 03:10