Wednesday, June 17, 2015

"RunAs /NetOnly" functionality from C# code

Only recently I've learnt about the "/netonly" flag availability for "runas" command. I was really happy to find it, but the issue came later.
It turns out that the runas.exe command can't be automated, as it accepts passwords only through a prompt. So there is no way to pass in credentials without the prompt.

That made me seek for a custom solution for the problem. What it turned out is that the .Net Process API doesn't expose any functionality to control the process creation the way, which "/netonly" flag would results in.

Long story short, I came up with the following solution:
The CreateProcessWithLogonW Win32 API, which is being called internally by runas.exe, has a number of parameters indicating how exactly the process should be created. One of these parameters is "dwLogonFlags". The set of values it can take has one called "LOGON_NETCREDENTIALS_ONLY". From MSDN documentation for that value: "Log on, but use the specified credentials on the network only. The new process uses the same token as the caller, but the system creates a new logon session within LSA, and the process uses the specified credentials as the default credentials.". This is exactly what I need. After few hours of unsuccessful search for a C# code sample, which would create a process with this flag, I ended up creating my own.
The sample code is available for download at:

Hope you find this useful !
Post a Comment