Search code examples
phpmongodbsecurityuser-input

MongoDB + PHP: Filter on parsed user-input secure?


Is this secure or is it vulnerable to exploitation by user input?

$ids = explode(",", $_GET['ids']);

$results = $collection->find([
    'arbitraryId' => ['$in' => $ids]
]);

Solution

  • The big issue with what you are doing is that people could try random ID's and might luckily see a document that that user might not be allowed to see.

    So if this is what you fear, then you should add a session flag that holds the user permission and add permissions to your documents.

    //this would have been set at user login
    $perms = $_SESSION['perms'];
    
    //get the right documents
    $results = $collection->find([
        '_id' => ['$in' => $ids],
        'perms' => ['$in' => $perms]
    ]);
    

    Otherwise, if an id does not exist, then it would just return an empty array. There is really no injection here as long as we are talking about reading documents by id, unless you convert those IDs back to MongoID at query time. In this case you should at least validate the format of each id before converting to MongoID, using at least this regex

     [a-z0-9]{24}