C ++: how to avoid user input for secure system calls?

On the Linux platform, I have C ++ code that looks 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.... 
  • Does user login () make a secure call at all?
  • Should user input be escaped / cleared?
  • How?
  • How can the above code be used for malicious purposes?

Thanks.

+4
source share
3 answers

Just do not use system . Prefer execl .

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

Thus, myDir always passed as a single mkdir argument, and the shell is not involved. Note that if you use this method, you need a fork .

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

 mkdir(myDir, someMode); 
+10
source

Using a system () call with command line parameters without disinfecting the login can be very unsafe.

A potential security risk could be a user passing the following directory name

 somedir ; rm -rf / 

To prevent this, use a mixture of the following

  • use getopt to make sure your input is sanitized
  • sanitize the entrance
  • use execl instead of system to execute command

The best option would be to use all three

+2
source

In response to Matthew's answer, do not create a shell process if you do not need it. If you use the fork / execl combination, the individual parameters will never be parsed, so they should not be avoided. Beware of null characters, however this will terminate the parameter prematurely (in some cases this is not a security issue).

I assume mkdir is just an example, since mkdir can be trivially called from C ++ much easier than these subprocess sentences.

0
source

All Articles