Preventing SQL injection in Node.js

funseiki picture funseiki · Apr 3, 2013 · Viewed 150.6k times · Source

Is it possible to prevent SQL injections in Node.js (preferably with a module) in the same way that PHP had Prepared Statements that protected against them.

If so, how? If not, what are some examples that might bypass the code I've provided (see below).


Some Context:

I'm making a web application with a back-end stack consisting of Node.js + MySql using the node-mysql module. From a usability perspective, the module is great, but it has not yet implemented something akin to PHP's Prepared Statements (though I'm aware it is on the todo).

From my understanding, PHP's implementation of prepared statements, among other things, helped greatly in the prevention of SQL injections. I'm worried, though, that my node.js app may be open to similar attacks, even with the string escaping provided by default (as in the code snippet below).

node-mysql seems to be the most popular mysql connector for node.js, so I was wondering what other people might be doing (if anything) to account for this issue - or if it is even an issue with node.js to begin with (not sure how this wouldn't be, since user/client-side input is involved).

Should I switch to node-mysql-native for the time being, since it does provide prepared statements? I'm hesitant to do this, because it does not seem to be as active as node-mysql (though that may just mean that it is complete).

Here is a snippet of user registration code, which uses the sanitizer module, along with node-mysql's prepared statement-like syntax (which, as I mentioned above, does character escaping), to prevent cross site scripting and sql injections, respectively:

// Prevent xss
var clean_user = sanitizer.sanitize(username);

// assume password is hashed already
var post = {Username: clean_user, Password: hash};

// This just uses connection.escape() underneath
var query = connection.query('INSERT INTO users SET ?', post,
   function(err, results)
   {
       // Can a Sql injection happen here?
   });

Answer

Michael Pratt picture Michael Pratt · Apr 3, 2013

The node-mysql library automatically performs escaping when used as you are already doing. See https://github.com/felixge/node-mysql#escaping-query-values