PunDefeated PunDefeated - 23 days ago 15
Javascript Question

Invoke pre-parsed command line with Node.js

I need to invoke the following command, where password is user input. However, I am worried about the possibility of an attack, such as

"; rm -rf / ;"
being the input given by the user.

var checkPassword = exec('echo "'+password+ '"| cracklib-check\n', function(err, stdout, stderr) {
...
...
}


is there a way to invoke the command with pre-parsed arguments (preferably native to nodejs/ javascript), kind of like prepared statements which are used to avoid SQL injection?

I could probably avoid the problem by blacklisting certain characters, but that seems much less reliable, and I'd like to avoid it is possible.

Answer

@Ilmora's answered me started, but I still had to handle encoding.

const spawn = require('child_process').spawn;

// Read password from argument to nodejs invocation
var password = process.argv[2];

var cracklib_check = spawn('/usr/sbin/cracklib-check');

cracklib_check.stdin.setEncoding = 'utf-8';
cracklib_check.stdin.write(password);
cracklib_check.stdin.end();

// Process results of cracklib-check
cracklib_check.stdout.on('data', function (data) {
  console.log("[*] " + data.toString());
});

cracklib_check.stderr.on('data', function (data) {
  console.log("[-] " + data.toString());
});
Comments