Tuesday, January 29, 2013

How MongoDB survives From SQL or Query Injection

As We know SQL injection is one of the most famous way people try to hack the SQL based applications.I came to know about interesting thing how MongoDB survives from this SQL injection while reading the mongodb docs.

For SQL based applications most of the drivers support accessing SQL data using query as String which makes the access vulnerable.
For Example in Java we use to get the data from SQL as follows,

String query = "SELECT ZipCode,State FROM zipcodes WHERE City = '+city+' AND State = '+state+'";
connection = DriverManager.getConnection(jdbcurl, username, password);
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);

In case of MongoDB there is no vulnerability because all the drivers creates a BSON object for the given Query instead of calling the DB as a string itself.

For MongoDb in Java QueryBuilder is used to build Queries for accesing MongoDb Data,

DBObject query = QueryBuilder.start("City").is(city).and("State").is(state).get();

As a client program assembles a query in MongoDB, it builds a BSON object, not a string. Thus traditional SQL injection attacks are not a problem. 
MongoDB represents queries as BSON objects. Typically client libraries provide a convenient, injection free, process to build these objects.