June 02, 2004

Secure Coding: Running Processes as a Different User

Shawn has posted an interesting entry about how in Whidbey you can use the Process class to specify the user context that the new process should run under. This differs significantly from current approaches, as you normally have to P/Invoke CreateProcessWithLogonW to do it through impersonation.

I've talked about different approaches before when I discussed spawning external processes securely in Windows and using restricted tokens to execute a process, but this is much more elegant. It's nice to see the Process class add new functionality through the exposure of three new properties on the ProcessStartInfo class: Domain, UserName, and Password.

Here is a snippit that Shawn used (although of course you would do better input validation than that :) ):

Console.Write("Username: ");
string user = Console.ReadLine();
string[] userParts = user.Split('\\');
        
Console.Write("Password: ");
SecureString password = GetPassword();

try
{
    ProcessStartInfo psi = new ProcessStartInfo(args[0]);
    psi.UseShellExecute = false;
            
    if(userParts.Length == 2)
    {
        psi.Domain = userParts[0];
        psi.UserName = userParts[1];
    }
    else
    {
        psi.UserName = userParts[0];
    }

    psi.Password = password;

    Process.Start(psi);
}
catch(Win32Exception e)
{
    Console.WriteLine("Error starting application");
    Console.WriteLine(e.Message);
}

Anyways, nice find Shawn!

Posted by SilverStr at June 2, 2004 04:02 PM | TrackBack
Comments

I wonder what the closest thing would be in the POSIX/Unix/Linux programming world. fork()? sudo/su?

Posted by: Wim at June 4, 2004 07:43 PM