PunDefeated PunDefeated - 1 year ago 148
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 Source

@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';

// 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());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download