Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include a string variable(char *) within "system" command - linux

Tags:

c

linux

grep

char * S = "hello"; // assume it's dynamically allocated correctly

I want to use S in the below statement when S would be treated as a string with the value "hello".

system("grep S searchtext.txt > result.txt");

How do I do this?

like image 343
Eternal Learner Avatar asked Nov 27 '10 11:11

Eternal Learner


2 Answers

In general it's a very very bad idea to use system like this. system runs the command through the shell, meaning that the string you pass to system is subject to all of the shell's variable expansion, command expansion, special character interpretation, etc.

If you insist on using system, you must first sanitize your string. The easiest way to do that is:

char *tmp = malloc(4*strlen(S)+3);
tmp[0] = '\'';
for (i=0,j=1; tmp[j]=S[i]; i++, j++)
    if (S[i]=='\'') tmp[++j]='\\', tmp[++j]='\'', tmp[++j]='\'';
tmp[j++] = '\'';
tmp[j++] = 0;
if (snprintf(cmd, sizeof cmd, "foo %s ...", tmp) >= sizeof cmd) goto error;
system(cmd);

This code single-quotes the whole string S and replaces any embedded single-quotes with '\''. Note that I also checked for command line truncation in case it could lead to execution of dangerous commands.

A better alternative would be to abandon system entirely and perform your own fork and exec to bypass the shell. Then there is no command line to be interpreted; you have full control over the arguments (*argv[] array) that are passed to the external program.

like image 72
R.. GitHub STOP HELPING ICE Avatar answered Oct 23 '22 17:10

R.. GitHub STOP HELPING ICE


In plain C, you traditionally use snprintf() to format your command line string into a buffer:

char buf[1024];
snprintf(buf, sizeof(buf), "grep '%s' searchtext.txt > result.txt", S);
system(buf);

Of course, for security reasons, you should never do that if S comes from an external source such as a file, a database, or the user himself. That could lead to shell code injection.

like image 37
Frédéric Hamidi Avatar answered Oct 23 '22 18:10

Frédéric Hamidi