LDAP Injection in Claude Skills
Claude skills that authenticate users or query employee data against Active Directory or OpenLDAP are exposed to LDAP injection attacks that can bypass authentication, escalate privileges, and leak sensitive directory attributes. Because MCP tool arguments arrive as LLM-generated strings, the injection surface is wider than in traditional web forms — a prompt injection or confused-deputy attack can craft payloads that never come from a human keyboard.
Why LDAP injection is a distinct concern for MCP skills
Most LDAP injection guidance assumes a human attacker typing into a login form. In an MCP skill context the input arrives from an LLM that has been instructed — possibly by a malicious document or tool result — to supply a crafted value. The skill developer may not have fuzz-tested their LDAP code because the tool is called by Claude, not directly by users. Active Directory environments are particularly sensitive: a successful LDAP bind or search against AD can expose password hashes, group memberships, account expiry dates, and service principal names that an attacker can use to pivot across the organization.
SA-SKL-LDAP in scope: LDAP-001 DN injection in bind operation, LDAP-002 filter injection authentication bypass, LDAP-003 operational attribute leakage in search response, LDAP-004 anonymous bind permits unrestricted directory enumeration.
LDAP-001 — Distinguished Name injection in bind operation
When a skill constructs the bind DN by interpolating a user-supplied username directly into the string cn=${username},ou=users,dc=example,dc=com, an attacker can supply a username that escapes the intended OU. LDAP DNs use commas as component separators, so an input of admin,ou=admins,dc=example,dc=com completes the target OU and shifts all following components into a different subtree. The ldapjs client performs the bind against the attacker-controlled DN, and if that account exists and the password matches, authentication succeeds for the wrong identity.
// VULNERABLE — username interpolated directly into DN string
import ldap from 'ldapjs';
server.tool(
'authenticate_user',
{ username: z.string(), password: z.string() },
async ({ username, password }) => {
const client = ldap.createClient({ url: 'ldap://ad.corp.example.com' });
// Attacker supplies: admin,ou=admins,dc=example,dc=com
// Resulting DN: cn=admin,ou=admins,dc=example,dc=com,ou=users,dc=example,dc=com
// ldapjs resolves leftmost valid DN — binds as the admin account
const bindDn = `cn=${username},ou=users,dc=example,dc=com`;
return new Promise((resolve, reject) => {
client.bind(bindDn, password, (err) => {
client.destroy();
if (err) return reject(new Error('AUTH_FAILED'));
resolve({ authenticated: true, username });
});
});
}
);
// FIXED — validate username before DN construction
import ldap from 'ldapjs';
// RFC 4514: safe characters for a CN value (conservative allowlist)
const USERNAME_RE = /^[a-zA-Z0-9_.\-]{1,64}$/;
server.tool(
'authenticate_user',
{ username: z.string(), password: z.string() },
async ({ username, password }) => {
// Reject any username that contains LDAP DN special characters
if (!USERNAME_RE.test(username)) {
throw new Error('INVALID_USERNAME: contains disallowed characters');
}
const client = ldap.createClient({ url: 'ldap://ad.corp.example.com' });
// username is now guaranteed to contain only safe alphanumeric chars
const bindDn = `cn=${username},ou=users,dc=example,dc=com`;
return new Promise((resolve, reject) => {
client.bind(bindDn, password, (err) => {
client.destroy();
if (err) return reject(new Error('AUTH_FAILED'));
resolve({ authenticated: true, username });
});
});
}
);
LDAP-002 — LDAP filter injection bypasses authentication
LDAP search filters follow a Polish-prefix notation where parentheses and logical operators are part of the syntax. When a skill constructs a filter like (&(uid=${username})(userPassword=${password})) using unsanitized user input, an attacker can inject filter metacharacters to change the logical structure. A username value of *)(uid=*)(&(uid=* turns the filter into (&(uid=*)(uid=*)(&(uid=*)(userPassword=anything))) — the outer & clause short-circuits to true for any entry in the directory, returning the first user regardless of password. The special characters that must be escaped in LDAP filter values are: * (wildcard), ( and ) (grouping), \ (escape prefix), and NUL (0x00).
// VULNERABLE — user input interpolated directly into LDAP search filter
import ldap from 'ldapjs';
server.tool(
'lookup_employee',
{ username: z.string(), password: z.string() },
async ({ username, password }) => {
const client = ldap.createClient({ url: 'ldap://ad.corp.example.com' });
// Bind as service account first
await bindAsync(client, 'cn=svc-mcp,ou=service,dc=corp,dc=example', process.env.SVC_PASSWORD!);
// INJECTION: username = *)(uid=*)(&(uid=*
// Filter becomes: (&(uid=*)(uid=*)(&(uid=*)(userPassword=x)))
// Returns first user in directory — authentication bypass
const filter = `(&(uid=${username})(userPassword=${password}))`;
return new Promise((resolve, reject) => {
client.search('ou=users,dc=corp,dc=example', { filter, scope: 'sub' }, (err, res) => {
const entries: ldap.SearchEntry[] = [];
res.on('searchEntry', (e) => entries.push(e));
res.on('end', () => {
client.destroy();
resolve({ authenticated: entries.length > 0 });
});
res.on('error', reject);
});
});
}
);
// FIXED — escape all LDAP filter special characters before interpolation
import ldap from 'ldapjs';
/**
* Escape a string for safe use as an LDAP filter assertion value.
* RFC 4515 §3: escape *, (, ), \, NUL as \XX hex sequences.
*/
function escapeLdapFilter(value: string): string {
return value
.replace(/\\/g, '\\5c') // backslash must be first
.replace(/\*/g, '\\2a') // wildcard
.replace(/\(/g, '\\28') // open paren
.replace(/\)/g, '\\29') // close paren
.replace(/\0/g, '\\00'); // NUL byte
}
server.tool(
'lookup_employee',
{ username: z.string(), password: z.string() },
async ({ username, password }) => {
// Reject inputs that are clearly too long (defense in depth)
if (username.length > 128 || password.length > 256) {
throw new Error('INPUT_TOO_LONG');
}
const safeUsername = escapeLdapFilter(username);
const safePassword = escapeLdapFilter(password);
const client = ldap.createClient({ url: 'ldap://ad.corp.example.com' });
await bindAsync(client, 'cn=svc-mcp,ou=service,dc=corp,dc=example', process.env.SVC_PASSWORD!);
// All metacharacters are now safely escaped — filter cannot be manipulated
const filter = `(&(uid=${safeUsername})(userPassword=${safePassword}))`;
return new Promise((resolve, reject) => {
client.search('ou=users,dc=corp,dc=example', { filter, scope: 'sub' }, (err, res) => {
if (err) { client.destroy(); return reject(err); }
const entries: ldap.SearchEntry[] = [];
res.on('searchEntry', (e) => entries.push(e));
res.on('end', () => { client.destroy(); resolve({ authenticated: entries.length === 1 }); });
res.on('error', (e) => { client.destroy(); reject(e); });
});
});
}
);
LDAP-003 — Operational attributes exposed in directory search response
When a skill performs an LDAP search without specifying a restricted attribute list, the directory server returns all attributes the bound account can read. In Active Directory this commonly includes userPassword (or its hash equivalent), pwdChangedTime, shadowExpire, memberOf (revealing group memberships), badPwdCount, and lastLogonTimestamp. If the skill serializes the full entry object and returns it as a tool result, all of these appear in the LLM context window and can be relayed to the user or logged in conversation history.
// VULNERABLE — search returns all attributes; full entry forwarded to LLM
import ldap from 'ldapjs';
server.tool(
'get_employee_info',
{ employeeId: z.string() },
async ({ employeeId }) => {
const client = ldap.createClient({ url: 'ldap://ad.corp.example.com' });
await bindAsync(client, process.env.LDAP_BIND_DN!, process.env.LDAP_BIND_PW!);
const safeId = escapeLdapFilter(employeeId);
// No attributes list specified — server returns ALL readable attributes
// Result includes: userPassword, pwdChangedTime, memberOf, badPwdCount, etc.
const opts = { filter: `(employeeID=${safeId})`, scope: 'sub' as const };
return new Promise((resolve, reject) => {
client.search('ou=users,dc=corp,dc=example', opts, (err, res) => {
if (err) { client.destroy(); return reject(err); }
let entry: Record<string, unknown> = {};
res.on('searchEntry', (e) => {
// Dumps every attribute including sensitive operational ones
entry = e.pojo.attributes.reduce((acc: Record<string, unknown>, attr) => {
acc[attr.type] = attr.values;
return acc;
}, {});
});
res.on('end', () => { client.destroy(); resolve(entry); });
res.on('error', (e) => { client.destroy(); reject(e); });
});
});
}
);
// FIXED — explicitly request only the attributes the skill needs
import ldap from 'ldapjs';
// Allowlist of attributes safe to return; never include password-related fields
const SAFE_ATTRIBUTES = ['uid', 'mail', 'displayName', 'telephoneNumber', 'department', 'title'];
server.tool(
'get_employee_info',
{ employeeId: z.string() },
async ({ employeeId }) => {
const client = ldap.createClient({ url: 'ldap://ad.corp.example.com' });
await bindAsync(client, process.env.LDAP_BIND_DN!, process.env.LDAP_BIND_PW!);
const safeId = escapeLdapFilter(employeeId);
// Pass explicit attributes array — server returns ONLY these fields
const opts = {
filter: `(employeeID=${safeId})`,
scope: 'sub' as const,
attributes: SAFE_ATTRIBUTES,
};
return new Promise((resolve, reject) => {
client.search('ou=users,dc=corp,dc=example', opts, (err, res) => {
if (err) { client.destroy(); return reject(err); }
let result: Record<string, string | string[]> | null = null;
res.on('searchEntry', (e) => {
// Build response from known-safe attribute list only
result = Object.fromEntries(
SAFE_ATTRIBUTES.map((attr) => [
attr,
e.pojo.attributes.find((a) => a.type === attr)?.values[0] ?? null,
])
);
});
res.on('end', () => {
client.destroy();
if (!result) return reject(new Error('EMPLOYEE_NOT_FOUND'));
resolve(result);
});
res.on('error', (e) => { client.destroy(); reject(e); });
});
});
}
);
LDAP-004 — Anonymous bind permits unrestricted directory enumeration
When a skill's LDAP client is initialized without bind credentials, ldapjs performs an anonymous bind by default. Many misconfigured Active Directory and OpenLDAP deployments allow anonymous read access to the base naming context. An anonymous bind gives the skill (and therefore anyone who can invoke the skill) the ability to enumerate every user, group, and computer object in the directory using a filter of (objectClass=*). Even if the target server blocks anonymous reads on user entries, it may allow enumeration of organizational units and schema attributes that aid further attacks.
// VULNERABLE — no credentials provided; ldapjs uses anonymous bind
import ldap from 'ldapjs';
// Connection is shared across requests — initialized at module load
const ldapClient = ldap.createClient({
url: 'ldap://ad.corp.example.com',
// No bindDN or bindCredentials — anonymous bind
});
server.tool(
'check_username_exists',
{ username: z.string() },
async ({ username }) => {
const safeUsername = escapeLdapFilter(username);
// Anonymous client can search the entire DIT on a misconfigured server
const opts = { filter: `(uid=${safeUsername})`, scope: 'sub' as const };
return new Promise((resolve, reject) => {
ldapClient.search('dc=corp,dc=example', opts, (err, res) => {
if (err) return reject(err);
let found = false;
res.on('searchEntry', () => { found = true; });
res.on('end', () => resolve({ exists: found }));
res.on('error', reject);
});
});
}
);
// FIXED — always bind with a service account; verify bind succeeded before searching
import ldap from 'ldapjs';
function createBoundClient(): Promise<ldap.Client> {
return new Promise((resolve, reject) => {
const client = ldap.createClient({ url: 'ldap://ad.corp.example.com' });
const bindDn = process.env.LDAP_SVC_DN;
const bindPw = process.env.LDAP_SVC_PW;
if (!bindDn || !bindPw) {
return reject(new Error('LDAP_CONFIG: service account credentials not configured'));
}
client.bind(bindDn, bindPw, (err) => {
if (err) {
client.destroy();
return reject(new Error('LDAP_BIND_FAILED: ' + err.message));
}
resolve(client);
});
});
}
server.tool(
'check_username_exists',
{ username: z.string() },
async ({ username }) => {
const safeUsername = escapeLdapFilter(username);
// Fresh authenticated client per request (or use a connection pool with verified binds)
const client = await createBoundClient();
// Restrict search to the users OU; do not search from root DC
const opts = {
filter: `(uid=${safeUsername})`,
scope: 'sub' as const,
attributes: ['uid'], // return only the uid — no data leakage
};
return new Promise((resolve, reject) => {
client.search('ou=users,dc=corp,dc=example', opts, (err, res) => {
if (err) { client.destroy(); return reject(err); }
let found = false;
res.on('searchEntry', () => { found = true; });
res.on('end', () => { client.destroy(); resolve({ exists: found }); });
res.on('error', (e) => { client.destroy(); reject(e); });
});
});
}
);