popen vs system: is popen as evil as system?

2019-04-29 02:20发布

问题:

popen buffers output while system does not. is that the only difference?

I understand that popen and system both run the command through the shell. However, is popen() as evil as system()?

回答1:

Look, the whole thing about "system being evil" is, at heart, people who don't think about the security consequences of their particular use case. The only reason system is "more evil" than doing your own fork/dup/exec is that used badly, it's possible for someone to introduce a malicious command line. So, for example

#include <stdlib.h>

int main(int argc, char** argv){
    (void) system(argv[1]);
}

is certainly dumb, because someone could put, eg, rm -rf / in as the argument. And, of course, something similarly dumb could be done with popen.

But then consider something that does fork and exec using a user string for the command: the exact same vulnerability and stupidity exists.

The evil -- which is to say, the error -- lies in using a random input string as a command without some filtering, not in the system call.



回答2:

Neither system nor popen is evil. They are simply easy to use in such a way that cause your programs to be hacked. If you need your binary to run a separate binary, you will need to use one of those calls. Just use it properly.

That being said, system("PAUSE") is kinda excessive, when a simple cin.getline() would work.



标签: c++ system popen