GuardAPI Logo
GuardAPI

Fix NoSQL Injection in Slim

NoSQL Injection in Slim/PHP environments typically arises when raw user-controlled arrays are passed directly into MongoDB query filters. Attackers leverage operators like '$gt', '$ne', or '$where' to bypass authentication or exfiltrate data. If you are piping 'request->getParsedBody()' straight into a 'find()' call without sanitization, your application is trivially exploitable.

The Vulnerable Pattern

$app->post('/api/user/lookup', function ($request, $response) {
    $params = $request->getParsedBody();
    // VULNERABLE: If attacker sends {"id": {"$ne": null}}, they dump the first user in the DB
    $user = $this->db->users->findOne([
        '_id' => $params['id']
    ]);
    return $response->withJson($user);
});

The Secure Implementation

The vulnerability exists because PHP's MongoDB driver allows query filters to be nested arrays. When an attacker provides a JSON object instead of a scalar string, the driver interprets the keys as operators. By casting the input to a string, you force the driver to treat the input as a literal value rather than a command. For IDs, always wrap inputs in the 'ObjectId' constructor, which provides built-in validation and prevents operator injection entirely.

$app->post('/api/user/lookup', function ($request, $response) {
    $params = $request->getParsedBody();
// SECURE: Cast to string to ensure NoSQL operators are treated as literal values
$safeId = (string)($params['id'] ?? '');

// ALTERNATIVE: Use MongoDB\BSON\ObjectId for ID lookups to enforce format
try {
    $user = $this->db->users->findOne([
        '_id' => new MongoDB\BSON\ObjectId($safeId)
    ]);
} catch (Exception $e) {
    return $response->withStatus(400);
}

return $response->withJson($user);

});

System Alert • ID: 1330
Target: Slim API
Potential Vulnerability

Your Slim API might be exposed to NoSQL Injection

74% of Slim apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.