NoSql Injection in Python

2019-04-11 00:37发布

问题:

when trying to make this question, i got this one it is using Java, and in the answer it gave a Ruby example, and it seems that the injection happens only when using Json? because i've an expose where i'll try to compare between NoSQL and SQL and i was trying to said: be happy, nosql has no sql injection since it's not sql ...

can you please explain me:

  • how sql injection happens when using Python driver (pymongo).
  • how to avoid it.
  • the comparison using the old way sql injection using the comment in the login form.

回答1:

There are a couple of concerns with injection in MongoDB:

  • $where JS injection - Building JavaScript functions from user input can result in a query that can behave differently to what you expect. JavaScript functions in general are not a responsible method to program MongoDB queries and it is highly recommended to not use them unless absolutely needed.
  • Operator injection - If you allow users to build (from the front) a $or or something they could easily manipulate this ability to change your queries. This of course does not apply if you just take data from a set of text fields and manually build a $or from that data.
  • JSON injection - Quite a few people recently have been trying to convert a full JSON document sent (saw this first in JAVA, ironically) from some client side source into a document for insertion into MongoDB. I shouldn't need to even go into why this is bad. A JSON value for a field is fine since, of course, MongoDB is BSON.

As @Burhan stated injection comes from none sanitized input. Fortunately for MongoDB it has object orientated querying.

The problem with SQL injection comes from the word "SQL". SQL is a querying language built up of strings. On the other hand MongoDB actually uses a BSON document to specify a query (an Object). If you keep to the basic common sense rules I gave you above you should never have a problem with an attack vector like:

SELECT * FROM tbl_user WHERE ='';DROP TABLE;

Also MongoDB only supports one operation per command atm (without using eval, don't ever do that though) so that wouldn't work anyway...

I should add that this does not apply to data validation only injection.



回答2:

SQL injection has nothing to do with the database. It is a type of vulnerability that allows for execution of arbitrary SQL commands because the target system does not sanitize the SQL that is given to the SQL server.

It doesn't matter if you are on NoSQL or not. If you have a system running on mongodb (or couchdb, or XYZ db), and you provide a front end where users can enter records - and you don't correctly escape and sanitize the input coming from the front end; you are open to SQL injection.