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:
Command Injection PreventionAvoid system calls and user input—to prevent threat actors from inserting characters into the OS command. Set up input validation—to prevent attacks like XSS and SQL Injection. Create a white list—of possible inputs, to ensure the system accepts only pre-approved inputs.
OS command injection (also known as shell injection) is a web security vulnerability that allows an attacker to execute arbitrary operating system (OS) commands on the server that is running an application, and typically fully compromise the application and all its data.
How to Prevent an SQL Injection. The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly.
No one operating system is immune to it. It can really happen on any operating system, Linux, Windows, Mac, because the vulnerability is really not in the operating system per se, it's the vulnerable application that makes it happen.
Are you executing the programs directly or going through the shell? If you always launch an external program by giving the full path name to the executable and leaving the shell out of the equation, then you aren't really susceptible to any kind of command line injection.
EDIT: DrFloyd, the shell is responsible for evaluating things like the backtick. No shell, no shell evaluation. Obviously, you've still got to be aware of any potential security gotchas in the programs that you're calling -- but I don't think this question is about that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With