Chris Chris - 3 months ago 12x
PHP Question

how to protect against LDAP Injection

We are building an application which utilizes LDAP via php and I got to thinking is there anything you can do with injecting into LDAP and better yet how does one protect against LDAP injections ?


When constructing LDAP filters you must ensure that filter values are handled according to RFC2254:

Any control characters with an ACII code < 32 as well as the characters with special meaning in LDAP filters "*", "(", ")", and "\" (the backslash) are converted into the representation of a backslash followed by two hex digits representing the hexadecimal value of the character.

Zend_Ldap for example uses the following routine

$val = str_replace(array('\\', '*', '(', ')'), array('\5c', '\2a', '\28', '\29'), $val);
for ($i = 0; $i<strlen($val); $i++) {
    $char = substr($val, $i, 1);
    if (ord($char)<32) {
        $hex = dechex(ord($char));
        if (strlen($hex) == 1) $hex = '0' . $hex;
        $val = str_replace($char, '\\' . $hex, $val);