francesca
francesca

Reputation: 587

How do I escape command injection in node child_process?

I'm adding arguments to child_process.exec command using string concatenation and they are ignored

var exec = require( "child_process" ).exec;

var cmd = exec( "grunt build --project="+application, {
        cwd: application
    },
    function( error, stdout, stderr ){});

cmd.stdout.pipe( process.stdout );
cmd.stderr.pipe( process.stderr );

Why is string concatenation a problem and how to avoid it?

Upvotes: 4

Views: 2032

Answers (2)

shime
shime

Reputation: 9008

Your code is vulnerable to command injection. It depends where's application coming from and you need to make sure it's not customizable by user.

Malicious code in your example would be

var application = '; rm -rf .'

but it wouldn't work since you're also trying to change the current directory via pwd.

The general recommendation is to be careful with child_process.exec and use child_process.execFile or child_process.spawn instead.

Upvotes: 4

Alan
Alan

Reputation: 634

Check your grunt build task to see if there is anything wrong. There is nothing wrong in your code with string concatenation in child_process.exec

Upvotes: 0

Related Questions