4

If I can guarantee input ($value in below example) is string (ie. attacker can't inject using PHP magic array), is following code sufficient for preventing injection?

$regex = str_replace('%', '', $value);

if (substr($value, 0, 1) != '%') $regex = '^' . $regex;
if (substr($value, -1) != '%') $regex = $regex . '$';

$value = new MongoRegex("/$regex/i");

Generally speaking, is MongoRegex("/$user-input/i") ok in terms of MongoDB security? Or should we take more precaution as in SQL world?

bitinn
  • 9,188
  • 10
  • 38
  • 64
  • magic array? I am unsure if magic array would work since the string output of an array is `Array` – Sammaye Dec 14 '13 at 17:21
  • @Sammaye true, I might be over-cautious (can't help myself given my SQL background). if this thread is to be believed, I think MongoRegex is safe enough for user input? http://security.stackexchange.com/questions/23734/what-type-of-attacks-can-be-used-vs-mongodb – bitinn Dec 14 '13 at 17:32
  • Yeah, I mean the biggest threat you have is operator injection, fortunately you cannot have that with mongoregex, but, regex is regex which means that if you accept regex from any old source then that regex is uncontrollable and someone could use it to get back records you don't want them to see, so even though mongoregex is "safe" it is up to your program to decide if it is safe enough – Sammaye Dec 14 '13 at 17:36
  • for example if you use the regex only on that users records then it is perfectly safe because at the end of the day the user should be able to search their own records but if you allow the regex to run uncontrolled on the collection then...well yeah – Sammaye Dec 14 '13 at 17:39
  • 2
    I'd be more concerned about perf impact of user provided regular expressions. – WiredPrairie Dec 14 '13 at 18:04

0 Answers0