Should I be sanitizing user-created strings before input into MongoDB (using the C# driver)?

StackOverflow https://stackoverflow.com/questions/22719655

  •  23-06-2023
  •  | 
  •  

Pergunta

Using MongoCollection<ThingWithString> collection, should I be wary of calling collection.Insert(stringythingy)? If a user-given field in ThingWithString is, eg ";db.dropDatabase();, am I setting myself up for some misery down the line?

Foi útil?

Solução

Short answer: no, there's no need for sanitizing user input on entry to MongoDB for the reasons you mentioned. There is no equivalent of "SQL Injection" in MongoDB, because of its binary transfer format (BSON).

No string inside a BSON document can be mistakenly interpreted as code (e.g. ";db.dropDatabase();), unless you try really hard - for example, if you build your own string representation of the code you want to run and pass that to db.eval(), which you should probably never do anyway.

As long as you use the driver's native methods for communicating with Mongo, any data you include in your requests will be mapped by the driver to a valid BSON document before it's sent to the server -- that's the driver's responsibility.

You could, however, decide to sanitize user input as it's going into Mongo for other purposes (e.g. HTML-encode it), but that's totally up to you. Personally, I'd do that on the way out rather than on the way in for a variety of reasons that are outside the scope of this question.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top