Ldap Injection in Cockroachdb
How Ldap Injection Manifests in Cockroachdb
LDAP injection in Cockroachdb contexts typically occurs when application code constructs LDAP queries using untrusted user input, which are then used to authenticate against directory services or retrieve user information for authorization decisions. This vulnerability is particularly dangerous in Cockroachdb environments because applications often need to integrate with enterprise LDAP directories for user management while simultaneously handling database credentials.
The most common manifestation involves authentication middleware that constructs LDAP queries based on HTTP request parameters. Consider a REST API endpoint that accepts username and password parameters:
app.post('/login', async (req, res) => {
const { username, password } = req.body;
// Vulnerable LDAP query construction
const searchFilter = `(uid=${username})`;
const ldapClient = new LdapClient(config);
const result = await ldapClient.search(
'dc=example,dc=com',
searchFilter,
['cn', 'mail', 'memberOf']
);
if (result.length === 0) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Use LDAP result to fetch database permissions
const userDn = result[0].dn;
const dbUser = await getUserFromLdap(userDn);
// Authenticate against Cockroachdb
const db = await cockroach.connect({
user: dbUser,
password: password,
database: 'myapp'
});
res.json({ success: true, user: dbUser });
});The critical vulnerability lies in the searchFilter construction. An attacker can inject LDAP metacharacters like *, (, ), or
to manipulate the query. For example, submitting username=admin)(|(uid=* would create the filter (uid=admin)(|(uid=*)), potentially returning all users.
In Cockroachdb-specific deployments, LDAP injection often combines with database-level attacks. After successful LDAP authentication, applications frequently construct SQL queries using the authenticated user's attributes. If an attacker manipulates LDAP attributes like memberOf or role, they can escalate privileges within the database context.
Another Cockroachdb-specific pattern involves using LDAP for row-level security (RLS) decisions. Applications might query LDAP to determine a user's department or access level, then use that information in SQL queries with Cockroachdb's CREATE POLICY statements. If LDAP responses are manipulated, the RLS policies can be bypassed.
Consider this vulnerable pattern:
// Fetch user's department from LDAP
const userDept = await ldapClient.getAttribute(userDn, 'department');
// Use in SQL query
const results = await db.query(`
SELECT * FROM financial_data
WHERE department = '${userDept}'
AND (user_id = CURRENT_USER OR is_public = true)
`);An attacker who can manipulate the department attribute through LDAP injection could access data from other departments, bypassing the intended row-level security.
Cockroachdb-Specific Detection
Detecting LDAP injection in Cockroachdb applications requires examining both the LDAP query construction and the downstream database access patterns. middleBrick's black-box scanning approach is particularly effective for this because it can test the unauthenticated attack surface without requiring source code access.
middleBrick scans for LDAP injection by sending specially crafted payloads to authentication endpoints and analyzing the responses. The scanner tests for LDAP metacharacter injection using payloads like:
*)(&(objectClass=*
*)(uid=*
*)(cn=*
*)(mail=*
*)(sn=*
*))
*)(objectClass=*
*))(|(objectClass=*
*)))(&(objectClass=*
*)))(&(uid=*
*)))(&(cn=*
*)))(&(mail=*
*)))(&(sn=*
*)))(uid=*
*)))(cn=*
*)))(mail=*
*)))(sn=*
*)))(objectClass=*
*)))(|(objectClass=*
*)))(|(uid=*
*)))(|(cn=*
*)))(|(mail=*
*)))(|(sn=*
*)))(%00
*)))(%00(uid=*
*)))(%00(cn=*
*)))(%00(mail=*
*)))(%00(sn=*
*)))(%00objectClass=*
*)))(%00|(objectClass=*
*)))(%00|(uid=*
*)))(%00|(cn=*
*)))(%00|(mail=*
*)))(%00|(sn=*
*))The scanner analyzes response patterns to identify LDAP injection vulnerabilities. Different responses to various payloads can indicate whether the LDAP query is being manipulated. For example, a 200 OK response to a wildcard injection payload might indicate that the query is returning more results than expected.
middleBrick's OpenAPI analysis capabilities are particularly useful for Cockroachdb applications because it can cross-reference API specifications with runtime behavior. The scanner examines Swagger/OpenAPI specs to identify authentication endpoints and then tests them systematically.
For Cockroachdb-specific detection, middleBrick looks for patterns where LDAP authentication results are used in database queries. The scanner tests whether manipulated LDAP attributes can affect downstream SQL queries or row-level security decisions. This includes testing for:
- LDAP attribute manipulation affecting database role assignments
- LDAP group membership injection affecting access controls
- LDAP attribute injection in SQL WHERE clauses
- LDAP-based row-level security bypass attempts
The scanner also tests for timing attacks that might reveal information about LDAP query structure. By measuring response times to different payloads, it can identify whether certain injection attempts are causing additional LDAP processing or database queries.
middleBrick provides a security risk score (0-100) with letter grades (A-F) and per-category breakdowns. For LDAP injection in Cockroachdb contexts, the scanner reports findings with severity levels (Critical, High, Medium, Low) and provides specific remediation guidance.
Cockroachdb-Specific Remediation
Remediating LDAP injection in Cockroachdb applications requires a defense-in-depth approach that addresses both the LDAP query construction and the downstream database access patterns. The primary defense is proper input validation and parameterized LDAP queries.
For Cockroachdb applications, the first step is to validate all user input before using it in LDAP queries. This includes:
function validateLdapInput(input) {
// Reject any input containing LDAP metacharacters
const ldapMetaChars = /[\(\)\*\&\|\\\x00\n\r\t\x01-\x1f]/;
if (ldapMetaChars.test(input)) {
throw new Error('Invalid characters in input');
}
// Additional length and format validation
if (input.length > 255) {
throw new Error('Input too long');
}
// Validate against expected format (e.g., email, username)
if (!/^[a-zA-Z0-9._%+-@]+$/.test(input)) {
throw new Error('Invalid format');
}
return input;
}The next critical step is using parameterized LDAP queries instead of string concatenation. Most LDAP libraries support query parameters:
const ldap = require('ldapjs');
async function authenticateUser(username, password) {
const client = await ldap.createClient({
url: 'ldap://ldap.example.com'
});
// Use parameterized query
const searchFilter = '(uid=?';
const searchOptions = {
filter: searchFilter,
scope: 'sub',
attributes: ['dn', 'cn', 'mail', 'memberOf']
};
try {
const results = await client.search('dc=example,dc=com', {
filter: searchFilter,
scope: 'sub',
filterArgs: [validateLdapInput(username)]
});
// Process results
let userDn;
for await (const entry of results) {
userDn = entry.dn;
break;
}
if (!userDn) {
return null;
}
// Bind with user DN and provided password
const bound = await client.bind(userDn, password);
return bound ? userDn : null;
} finally {
client.destroy();
}
}For Cockroachdb-specific integration, implement proper separation between LDAP authentication and database authorization. Never use LDAP attributes directly in SQL queries without validation:
async function getUserDatabaseRole(ldapAttributes) {
// Whitelist allowed roles
const allowedRoles = ['viewer', 'editor', 'admin'];
// Get role from LDAP, but validate it
const ldapRole = ldapAttributes.role?.toLowerCase();
if (!allowedRoles.includes(ldapRole)) {
throw new Error('Invalid role');
}
return ldapRole;
}
// When connecting to Cockroachdb
const dbRole = await getUserDatabaseRole(ldapResult);
const db = await cockroach.connect({
user: dbRole,
password: dbPassword,
database: 'myapp',
ssl: {
ca: fs.readFileSync('ca.crt'),
cert: fs.readFileSync('client.maxroach.crt'),
key: fs.readFileSync('client.maxroach.key')
}
});Implement row-level security in Cockroachdb using parameterized queries rather than relying on LDAP attributes directly:
// Use Cockroachdb's CREATE POLICY with proper parameterization
await db.query(`
CREATE POLICY user_access ON financial_data
FOR SELECT USING (
department = $1 OR
user_id = current_user() OR
is_public = true
)
`, [userDepartment]);
Add comprehensive logging and monitoring to detect LDAP injection attempts. Log failed authentication attempts with the original input (after sanitization) and monitor for unusual patterns like repeated wildcard characters or unusual metacharacter combinations.
Finally, implement regular security scanning with middleBrick to ensure that LDAP injection vulnerabilities don't reappear as the codebase evolves. The continuous monitoring feature in middleBrick's Pro plan can automatically scan your authentication endpoints on a schedule and alert you to new vulnerabilities.