Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sanitise input before using system command in C

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?

like image 576
John smith Avatar asked Mar 15 '26 06:03

John smith


1 Answers

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.

like image 158
Freedom_Ben Avatar answered Mar 17 '26 01:03

Freedom_Ben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!