Reputation: 17
I have read a lot of answers saying that the system()
command is bad. First off, why is it so bad? Second off, is there an alternative that doesn't produce such a security hole? I mostly want to know if there is a way to clear screen in C++. In python I have a clear function that checks the os name and runs either system('cls')
or system('clear')
. Is this a security hole as well? If so, is there a python alternative?
Upvotes: 1
Views: 2346
Reputation: 1
First off, why is it so bad?
Because you introduce dependencies to the OS in your code, and make it unportable.
Second off, is there an alternative that doesn't produce such a security hole?
No, the existing alternatives (POSIX compatible) fork()
and execxx()
or pipe()
have the same problems of introducing OS dependencies and security holes.
Is this a security hole as well?
The main secuity hole is introduced with commands constructed from parameters like
void exec_ls(const std::string param) {
std::string cmd;
cmd = "ls -l " + param;
system(cmd.c_str());
If someone manages to inject some additional command via param
, e.g.
std::string param = "dir ; rm -rf /*";
// ^^^^^^^^^^^
exec_ls(param);
they can call all kinds of malicious commands.
Another security hole comes from the point, that someone might replace cls
or clear
commands on your system with some malicious code.
The only way to get over this, is to secure your system in a way, that such isn't possible.
If so, is there a python alternative?
Using a different programming language as an intermediate caller doesn't fix the problem I mentioned above.
Upvotes: 1
Reputation: 144
system
functions (across many language, including Python and C++) are not inherently "bad" but they present difficulties for correct use.
You need to be absolutely sure that whatever you're executing via system
is secure.
If you write system("echo hello " + name)
then you need to be absolutely sure that name
cannot be controlled by a malicious user. name = "; rm -rf /"
would result in echo hello ; rm -rf /
, so if that's coming from a user, via something like a web form or a database, then you need to exercise a lot of caution, and I would recommend a more sophisticated solution than system
.
A call like system("clear")
is secure for your purposes.
System calls give you several outputs (I'll give an example for calls to a bash
shell):
system
returns the status code. For commands like ls
, you are interested in receiving STDOUT, and you may also check the status code. This is unwieldy with system
.
The Python subprocess
module is generally accepted by the community as an easier way to manage these concerns.
If you're trying to manage the console display, you may be interested in a library like ncurses
which has broad OS support.
Adding ncurses
as a dependency could be heavy-handed, if clearing the screen is the only thing you need to do. If that's the case, then I see nothing wrong with using system()
like you're doing.
Upvotes: 2