Gabriel Costin
Gabriel Costin

Reputation: 93

MongoDB injection attack

I am trying to increase my knowledge about SQL and NoSQL injection attacks and came across to my mind how could I possibly inject something into a NoSQL database, in this case MongoDB.There are plenty of articles on the internet about different ways of injection attacks and tried to build an example of my own attack which just does what other examples does but I made id just to prove it to my own eyes. However, it seems like almost everything I tried was not working for injecting purposes (which is great). Wondering if there is still a problem with injection attack or there are only old stuff on the internet. I will post my own implementation in case I am missing something:

So it's NodeJs and MongoDB with 1 collection and 1 document. The case scenario is when a user tries to log in so document contains a username and password.
Here is my NodeJs implementation:

app.post('/', async (req,res) => {
let response = {
    withoutProtection: false,
    withProtection:false
};
const query = {
    username: req.body.username,
    password: req.body.password
};
var user = await User.findOne(query);
if(user){
    response.withProtection = true;
}
res.send(response);
})

And here is user schema:

const UserSchema  = new mongoose.Schema({
username:{
    type: String
},
password:{
    type: String
},
})

So I tried different approaches with $ne=1, $gt, sleep(), etc. I will leave here an example of a query:{username: ' admin'|| '1'=='1', password: ''}

Upvotes: 2

Views: 2070

Answers (1)

D. SM
D. SM

Reputation: 14480

Query injection is possible if user input is structurally incorporated into the query. For example, if user can specify a hash which is then incorporated as is into the query.

If user input is stringified (which is what often happen in web applications), and operators are fixed by the application, such that user input can only become values (and the value types are controlled, i.e. they are all strings), the application would generally be safe from query injection.

Note that SQL query is a string, but an MQL query is a hash. Thus string input can be trivially structurally incorporated into an SQL query, but not so much into MQL queries.

Upvotes: 3

Related Questions