Reputation: 107
This is my code in C:
snprintf(buffer, 1023, "ls -%s", argv[1]);
system(buffer);
How can I sanitize the buffer, so that no one can run a malicious command apart from what's given?
Upvotes: 3
Views: 1559
Reputation: 106549
In the general case, this is impossible. The C standard does not make any claim regarding who is interpreting the command passed through system
. If you write an escape function for the borne shell, for example, that may be completely useless on a Windows system or on a system using a different command shell.
Upvotes: 0
Reputation: 11943
Unfortunately this is a very big topic that can't possibly be covered in a SO question. Fortunately there is a phenomenal book out there about Secure Coding in C and C++. That book was used as a "textbook" for my company's secure coding class, and it's very good.
There are dozens of different ways to sanitize input, and the best one to choose depends almost entirely on where the input comes from, and how it will be used. Where you're passing it to system(), you need to research in depth and you should really have a Security Engineer review your design. The reason is that there could be exploitable vulnerabilities in the ls
binary that could be triggered using only standard characters, or there could be buffer overflow vulnerabilities that you're not aware of, etc.
Speaking specifically to your scenario, and only looking for the simplest attacks, if you recursively remove all ;
&&
||
$
(
)
, you defeat most of the attacks that I can think of easily. Note that this does nothing though to prevent an exploitation of the binary to which you're passing the input to as an arg (in this case, ls
), rather it only protects against common shell characters that take on special meaning and allow the executing of arbitrary commands.
Upvotes: 2