How to prevent SQL injection using C# mongodb driver?

945 views Asked by At

I am using C# Mongodb driver to insert / update data in Mongodb. I have scanned my web api through "Qualys" and this was getting inserted in one my field called "createdOn" and I have provided sample data below.

1. Central Pacific Standard Time + (SELECT 0 FROM (SELECT
2. SLEEP(29))qsqli_1111) Central Pacific Standard Time',0,0);WAITFOR
3. DELAY'00:00:29'- |ping -c2 -i91 localhost|

Could you please me help to sort out of this issue.

1

There are 1 answers

3
securecodeninja On

Arbitrary code can potentially be injected in one of the filters (status). I suggest to implement whitelisting if you are just expecting a finite list of accepted characters

NOTE: I haven't tested the code below, but I hope you get the gist

Regex regex = new Regex(@"^[a-zA-Z0-9\s,]*$");  // alphanumeric pattern

if (regex.IsMatch(status)) {
    chatSessionCollection = Db.GetCollection<ChatSessionModel(ConfigurationManager.AppSettings["chatsession"]); 
    JObject dateFilter = new JObject(); 
    jFilter.Add("botId", 1); 
    jFilter.Add("status", status); 
    var _chatSessionList = _chatSessionCollection.Find(Convert.ToString(jFilter)).ToList(); 
}   
else 
  return false;