Search code examples
phpldappassword-hash

PHP - ldap_add userPassword crypt and password_hash


I am using PHP 7.1. and create LDAP management page.

When using ldap_add() function. there's ['userPassword'] field.

When I use below code, that works OK. (If salt does not exist, it's fine.)

$entry['userPassword'] = '{crypt}'.crypt('default_password');

Or below code is also works OK.

$entry['userPassword'] = '{MD5}'.'base64_encode(pack("H*", md5('default_password')));

But I read PHP recommend password_hash() function than crypt().

Can I use password_hash() function for LDAP? Is it possible?

UPDATE:

OK. then what what is the best solution for LDAP password ?

$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
$entry['userPassword'] = '{crypt}'.crypt('defaultpassword', '$2y$10$'.$salt.'$');

This does not work.


Solution

  • PHPs Password-Hashing mechanism is intended for use when you want to handle passwords only within PHP. Then it's great to use password_hash to create and password_verify to verify the password. The used backend here is completely irrelevant.

    LDAP on the other hand uses ldap_bind to not only verify a password, but to bind a user to an LDAP-Server. That's like logging into the Server. For that there are different Crypto-Algos that can be used like crypt or md5(which we do not use anymore…).

    As this binding-mechanism can be used by different systems to verify a login, the by LDAP supported Crypto-Algos need to be used so that the LDAP-Server can handle the password-verification.

    So when you want to use LDAP-Verification via bind on different systems with the password you are storing in LDAP you will not be able to use password_hash.

    If you want to use the password only with your PHP-Application you can use password_hash but I would not put it into the userPassword-attribute as that is the one the LDAP-Server uses to verify a password given by bind. And you usually can only read that field when you are authenticated as either an Admin or the user in question, which you won't be able to login as due to the password not being able to be handled by the user. So you'd need to bind to the LDAP as admin-user which adds much more security issues to your application than the use of password_hash solves.

    And I would also question what sense it makes to use LDAP as backend when you don't use the benefits of LDAP like one password for multiple systems. It's usually much easier to store informations in a database than to setup an LDAP just for a single project.