Is there a way to prevent sh / bash from doing command replacements?

From C program, I want to call a shell script with the file name as a parameter. Users can control the file name. C is something like (initialization / error check omitted):

sprintf(buf, "/bin/sh script.sh \"%s\"", filename); system(buf); 

The target device is actually an embedded system, so I don’t have to worry about malicious users. Obviously, this will be an attack vector in a web environment. However, if the system has a file name that, for example, contains backticks in its name, the command will fail because the shell will expand by name. Is there a way to prevent command substitution?

+4
source share
4 answers

Well, you can always override system () using a call to fork () and then execv ().

http://www.opengroup.org/onlinepubs/000095399/functions/system.html

+3
source

Try running "unalias" in the system function.

0
source

Since you marked it as C, I will give you the answer C. You will need to avoid the file name - create a new line that will be processed properly by the shell, so things like This is a file name give This\ is\ a\ file\ name or bad;rm *;filename becomes bad\;rm\ \*\;filename . Then you can pass this to the shell.

Another way would be to start the shell directly with fork and one of the exec functions. Passing arguments directly to programs does not extend or interpret the shell command line.

0
source

As Chart said, you should not use system , but fork and execv yourself. But in order to answer the question of how to make strings safe for transfer to the shell (in case you insist on using system ), you need to avoid the string. The easiest way to do this is to first replace each occurrence of ' (single quote) with '\'' (single quote, backslash, single quote, single quote), and then add ' (single quote) at the beginning and end of the line. Another fairly simple (but usually less effective) method is to put a backslash in front of each individual character, but then you still need to do some special tagged tricks to handle inline strings, so I prefer the first method.

0
source

All Articles