Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safely escaping arguments on the command line in C#

I'd like to pass some user supplied arguments to an application (using C# on Windows).

The arguments are in a NameValueCollection and I wish to pass them as a string so that the application can be invoked using the supplied arguments and invoked using ProcessStartInfo:

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.FileName = executableName;
startInfo.Arguments = arguments;
startInfo.Verb = "runas";
Process p = Process.Start(startInfo);

That part is well documented and very straightforward.

However, because of the nature by which these arguments will be constructed in my scenario (user supplied; potentially via a URL so easily maliciously crafted), I wish to be sure they are properly escaped (for example, no one is able to inject an escape character or quotation that would cause another application to be invoked or another action performed).

I wish to be sure there is no risk of command injection from characters in either the argument name or value. I am not clear on if I should attempt to escape any characters or not, and/or if there is an existing function for this.

I am predominantly from a Mac & Unix background and am not sure if this is even a valid concern when it comes to invoking application via ProcessStartInfo, but it seems prudent to be paranoid and ask for wiser council.

like image 830
Iain Collins Avatar asked Oct 19 '10 11:10

Iain Collins


1 Answers

CreateProcess function accepts two distinct parameters, lpApplicationName and lpCommandLine.
If lpApplicationName is NULL, lpCommandLine will be parsed for tokens to determine the executable, otherwise it will not and will be passed to the process, unchanged.

As mentioned by Raymond Chen.

So I would say, provided your startInfo.FileName comes from a trusted source, you are safe to pass arguments as is. Now, the application being run may fail to properly analyse them and do something bogus in case they are malformed, but that's a different story.

like image 143
GSerg Avatar answered Oct 31 '22 08:10

GSerg