Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: How to escape user input for safe system calls?

On a Linux platform, I have C++ code that goes like this:

// ...
std::string myDir;
myDir = argv[1]; // myDir is initialized using user input from the command line.
std::string command;
command = "mkdir " + myDir;
if (system(command.c_str()) != 0) {
   return 1;
}
// continue....
  • Is passing user input to a system() call safe at all?
  • Should the user input be escaped / sanitized?
  • How?
  • How could the above code be exploited for malicious purposes?

Thanks.

like image 716
augustin Avatar asked Aug 29 '10 11:08

augustin


People also ask

What is sanitizing user input?

Input sanitization is a cybersecurity measure of checking, cleaning, and filtering data inputs from users, APIs, and web services of any unwanted characters and strings to prevent the injection of harmful codes into the system.

What is sanitization in Java?

HTML sanitization is the process of examining an HTML document and producing a new HTML document that preserves only whatever tags are designated “safe” and desired. HTML sanitization can be used to protect against cross-site scripting (XSS) attacks by sanitizing any HTML code submitted by a user.


1 Answers

Just don't use system. Prefer execl.

execl ("/bin/mkdir", "mkdir", myDir, (char *)0);

That way, myDir is always passed as a single argument to mkdir, and the shell isn't involved. Note that you need to fork if you use this method.

But if this is not just an example, you should use the mkdir C function:

mkdir(myDir, someMode);
like image 62
Matthew Flaschen Avatar answered Oct 03 '22 17:10

Matthew Flaschen