Start process with impersonation – roll your own RunAs in C#

Quite a few of our servers are now in a different domain than the one I’m in – and especially for using SQL Server Management Studio that means that I have to use the RunAs command quite often (or use the shift + right-click RunAs option). Being a bare-bones command-line tool RunAs is not as user-friendly as one might wish, so I decided to try and make my own today, and here is the heart of the matter:

using System.Diagnostics;
using System.IO;
using System.Security;

var file = @”C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\Ssms.exe”;

// http://stackoverflow.com/questions/4624113/how-to-process-start-with-impersonated-domain-user

var sspw = new SecureString();

foreach (var c in “Mypassword”) sspw.AppendChar(c);

var proc = new Process();

proc.StartInfo.UseShellExecute = false;

proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(file);

proc.StartInfo.FileName = Path.GetFileName(file);          
proc.StartInfo.Arguments = “”;

proc.StartInfo.Domain = “MyDomainName”;

proc.StartInfo.UserName = “MyUserName”;

proc.StartInfo.Password = sspw;

// http://stackoverflow.com/questions/4422084/impersonating-in-net-c-opening-a-file-via-process-start

proc.StartInfo.LoadUserProfile = true;

proc.Start();

What was especially tricky was that StartInfo must absolutely have a valid path, and that – in order for Ssms.exe to find its modules – StartInfo must also be told to use the UserProfile of the impersonated user.

I find it a little odd that SecureString doesn’t have a constructor or method for taking a string, but maybe I’m overlooking some finer security detail here.

The whole thing will have to go inside a GUI with some sort of secure persistance of user info, but that should be the easy part 🙂

Advertisements
Posted in C#

One thought on “Start process with impersonation – roll your own RunAs in C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s