3

I've run across some node.js code that gets a user-supplied string, calls JSON.stringify(str) and injects the value directly into an SQL statement.

e.g.

var x = JSON.stringify(UNSAFE_USER_STRING);
mysql_execute('UPDATE foo SET v = ' + x + ' WHERE id = 1');

Obviously this is an abuse of JSON.stringify, however this is not my code and the authors would like to see an attack vector before they patch it. Because UNSAFE_USER_STRING is a string, not an object and does escaping of the obvious " and \ it's not obvious if there is a serious problem

Is this code safe? And if not, could someone demonstrate what would be unsafe input?

Thanks!

Heptic
  • 3,076
  • 4
  • 30
  • 51
  • [Preventing SQL injection in Node.js](http://stackoverflow.com/questions/15778572/preventing-sql-injection-in-node-js). Use prepared statements. – Devon Bessemer May 11 '15 at 14:37
  • 3
    Above comments, please at least read the question title before commenting. Bonus if you read the entire question. – danneu May 11 '15 at 14:45
  • 1
    What if you don't send UTF8 encoding? http://stackoverflow.com/questions/12456762/accented-characters-breaks-json-encode-in-php (though, a PHP question. *Should it differ from node.js?*) – ʰᵈˑ May 11 '15 at 14:51

2 Answers2

1

If you are sure x is a string, then I'm 99% sure this makes it impossible to conduct an SQL injection attack. My confidence goes down to 90% when you are unsure of the type for x. That said, considering all of the following should not pose a vulnerability:

  • Null, NaN, Infinity, -Infinity all seem to come back as null which is safe.
  • Undefined comes back as the value undefined, not a string, so I'm not sure about that. I think it would just be considered invalid SQL rather than pose a vulnerability.
  • Date in node.js JSON.stringify(new Date()) returns '"2015-11-09T18:53:46.198Z"' which is exactly what you'd want.
  • Arrays and Objects should result in invalid SQL although a smart conversion could enable successful use of SQL arrays. That said, there might be some tricky way to fill the array with Objects that might cause a vulnerability, but I doubt it.
  • Hex seems to just convert it to an integer.
  • Buffers and Uint8Arrays seem to come back as objects. Again, there might be some way to populate the Object with something that would be a vulnerability, but I doubt it.
Larry Maccherone
  • 9,393
  • 3
  • 27
  • 43
-1

Even if characters like " are being escaped. Character(combinations) used for comments like -- or # could still cause the WHERE clause to be ignored.

notlisted
  • 79
  • 2