We're currently building an application that executes a number of external tools. We often have to pass information entered into our system by users to these tools.
Obviously, this is a big security nightmare waiting to happen.
Unfortunately, we've not yet found any classes in the .NET Framework that execute command line programs while providing the same kind of guards against injection attacks as the IDbCommand objects do for databases.
Right now, we're using a very primitive string substitution which I suspect is rather insufficient:
protected virtual string Escape(string value) { return value .Replace(@"\", @"\\") .Replace(@"$", @"\$") .Replace(@"""", @"\""") .Replace("`", "'") ; }
What do you guys do to prevent command-line injection attacks? We're planning to implement a regex that is very strict and only allows a very small subset of characters through, but I was wondering if there was a better way.
Some clarifications:
- Some of these tools do not have APIs we can program against. If they did, we wouldn't be having this problem.
- The users don't pick tools to execute, they enter meta-data which the tools we've chosen use (for example, injecting meta data such as copyright notices into target files).