Search code examples
mongodbjdbcnosqlsql-injectionnosql-injection

How to avoid Mongo DB NoSQL blind (sleep) injection


While scanning my Application for vulnerability, I have got one high risk error i.e.

Blind MongoDB NoSQL Injection

I have checked what exactly request is sent to database by tool which performed scanning and found while Requesting GET call it had added below line to GET request.

{"$where":"sleep(181000);return 1;"}

Scan received a "Time Out" response, which indicates that the injected "Sleep" command succeeded.

I need help to fix this vulnerability. Can anyone help me out here? I just wanted to understand what I need to add in my code to perform this check before connecting to database?

Thanks, Anshu


Solution

  • Similar to SQL injection, or any other type of Code Injection, don't copy untrusted content into a string that will be executed as a MongoDB query.

    You apparently have some code in your app that naively accepts user input or some other content and runs it as a MongoDB query.

    Sorry, it's hard to give a more specific answer, because you haven't shown that code, or described what you intended it to do.

    But generally, in every place where you use external content, you have to imagine how it could be misused if the content doesn't contain the format you assume it does.

    You must instead validate the content, so it can only be in the format you intend, or else reject the content if it's not in a valid format.