Ldap Injection in Mongodb
How Ldap Injection Manifests in Mongodb
LDAP injection in MongoDB contexts typically occurs when user input is incorporated into LDAP filters that are used to query directory services for authentication or authorization decisions. While MongoDB itself is a document database, many applications using MongoDB also integrate with LDAP directories for user management, making this a critical security concern.
The most common attack vector appears in authentication middleware where applications construct LDAP filters dynamically. Consider a Node.js application using MongoDB for data storage but LDAP for authentication:
const { MongoClient } = require('mongodb');
const ldap = require('ldapjs');
async function authenticateUser(username, password) {
const client = new ldap.Client();
// Vulnerable: LDAP injection possible
const filter = `(uid=${username})`;
return new Promise((resolve, reject) => {
client.bind(
'ldap://directory.company.com',
filter,
(err, res) => {
if (err) return reject(err);
resolve(true);
}
);
});
}An attacker could supply a username like admin)(uid=*))(|(uid=*, which would transform the filter into:
(uid=admin)(uid=*))(|(uid=*This breaks the intended logic, potentially bypassing authentication or revealing information about valid usernames. The issue compounds when MongoDB queries are then executed based on the authenticated LDAP identity without proper validation.
Another MongoDB-specific scenario involves using LDAP group membership to control database access. Applications might construct queries like:
const groupFilter = `(member=uid=${username},ou=users,dc=company,dc=com)`;
const searchOptions = {
filter: groupFilter,
scope: 'sub',
attributes: ['cn']
};
client.search('ou=groups,dc=company,dc=com', searchOptions, (err, res) => {
res.on('searchEntry', (entry) => {
const groupName = entry.object.cn;
// Use groupName to determine MongoDB collection access
db.collection(groupName).find({ owner: username });
});
});Attackers can manipulate the username to alter the LDAP group filter, potentially accessing collections they shouldn't have permissions for.
Mongodb-Specific Detection
Detecting LDAP injection vulnerabilities in MongoDB applications requires examining both the application code and runtime behavior. Static analysis tools can identify dangerous patterns where user input is concatenated into LDAP filters without proper escaping.
MiddleBrick's black-box scanning approach tests the unauthenticated attack surface by sending specially crafted payloads to API endpoints. For LDAP injection detection, it examines:
- Authentication endpoints that might construct LDAP filters
- Authorization endpoints that use LDAP group membership
- API parameters that could influence LDAP queries
The scanner tests for LDAP injection by sending payloads containing special characters like *, (, ), &, and | to see if they affect query results. For MongoDB applications specifically, it looks for:
username=admin*)((|(uid=*Dynamic analysis complements static detection. Tools like OWASP ZAP or Burp Suite can intercept requests and modify parameters to test for LDAP injection. When testing MongoDB applications, focus on endpoints that:
- Handle user authentication
- Query user groups or roles
- Perform authorization checks
Runtime detection involves monitoring for unusual LDAP query patterns. If your application uses MongoDB's Node.js driver alongside LDAP, watch for:
db.collection('audit').find({
$expr: {
$in: [
'$user',
{
$map: {
$ldapQuery: 'ou=users,dc=company,dc=com',
$filter: '(uid=' + $userInput + ')'
}
}
]
}
});This pseudo-code illustrates how LDAP queries might be embedded within MongoDB's aggregation framework, creating a hybrid attack surface that requires specialized detection approaches.
Mongodb-Specific Remediation
Remediating LDAP injection in MongoDB applications requires a defense-in-depth approach. The primary defense is proper input validation and LDAP filter construction using parameterized queries.
For Node.js applications using the ldapjs library, always use parameterized filters:
const ldap = require('ldapjs');
async function safeAuthenticate(username, password) {
const client = ldap.Client();
// Safe: uses parameterized filter
const filter = ldap.filters.and([
ldap.filters.equals('uid', username)
]);
return new Promise((resolve, reject) => {
client.bind(
'ldap://directory.company.com',
filter,
(err, res) => {
if (err) return reject(err);
resolve(true);
}
);
});
}Alternatively, use the ldap-filters library for safer filter construction:
const { Filter } = require('ldap-filters');
const filter = new Filter()
.eq('uid', username)
.toString();
For MongoDB applications that integrate LDAP for authorization, implement role-based access control (RBAC) at the database level:
const { MongoClient } = require('mongodb');
async function setupRBAC() {
const client = new MongoClient(uri);
await client.connect();
// Create role with specific privileges
await client.db('admin').createRole({
role: 'app_user',
privileges: [
{
resource: { db: 'appdb', collection: 'public' },
actions: ['find']
}
],
roles: []
});
// Assign role to users based on LDAP group membership
// (after proper validation)
}Implement input validation at the API layer before LDAP queries are constructed:
function validateUsername(username) {
// Allow only alphanumeric, dots, and underscores
const usernameRegex = /^[a-zA-Z0-9._-]+$/;
return usernameRegex.test(username);
}
// Use in authentication endpoint
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (!validateUsername(username)) {
return res.status(400).json({ error: 'Invalid username format' });
}
// Proceed with safe LDAP authentication
});For applications using MongoDB Atlas with LDAP integration, configure Atlas's built-in LDAP authentication rather than implementing custom LDAP logic:
// Connect using MongoDB Atlas LDAP authentication
const client = new MongoClient(
'mongodb+srv://cluster0.mongodb.net/test?authMechanism=GSSAPI&authMechanismProperties=LDAP_BASE_DN:uid=%2525s,ou=users,dc=company,dc=com'
);
This approach leverages MongoDB's native LDAP support, which includes proper input sanitization and validation.