3
votes

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?

magic array? I am unsure if magic array would work since the string output of an array is ArraySammaye
@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? security.stackexchange.com/questions/23734/…bitinn
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 enoughSammaye
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 yeahSammaye
I'd be more concerned about perf impact of user provided regular expressions.WiredPrairie