开发者

Safely escaping arguments on the command line in C#

开发者 https://www.devze.com 2023-01-20 15:18 出处:网络
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 i

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开发者_Go百科();
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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号