Get number of AD errors with LDAP and PHP (ldap function return unprecise error)

active-directory, ldap, php

Solution

After spend a lot of hours in search I found the solution!

I have founded in this page : http://php.net/manual/en/function.ldap-get-option.php

basically you have to define a new constant variable called LDAP_OPT_DIAGNOSTIC_MESSAGE

like this

define('LDAP_OPT_DIAGNOSTIC_MESSAGE', 0x0032);

and then

ldap_get_option($conn, LDAP_OPT_DIAGNOSTIC_MESSAGE, $extended_error);

With that, LDAP will give you extended error and you will be able to know what really happened, the value will be put in $extended_error.

Problem

I'm making an application with uses PHP to connect to Active Directory (AD), using LDAP protocol. Works fine, my problem is how to catch the specific errors if the login operations fails. Today, the application only shows if the login worked or not, example: suppose that the username is expired in AD, the system will show that the "username/password is invalid" because we don't verify specific returns of LDAP. Ok, let's go to the problem itself, below is my code that I expect to catch specific errors. ``` <?php if (! ($bind = @ldap_bind ( $connect, "DOMAIN\\" . strtoupper ( $this->user), $this->password))) { error_log ( "Autentication fails LDAP (user: $this->user)" ); return ldap_errno ( $connect ); ?> ``` That function, ldap_errno, returns me the number of what happened, based on this table: (There are more, see link below) 48 LDAP_INAPPROPRIATE_AUTH 49 LDAP_INVALID_CREDENTIALS 49 / 52e AD_INVALID CREDENTIALS 49 / 525 USER NOT FOUND 49 / 530 NOT_PERMITTED_TO_LOGON_AT_THIS_TIME 49 / 531 RESTRICTED_TO_SPECIFIC_MACHINES 49 / 532 PASSWORD_EXPIRED 49 / 533 ACCOUNT_DISABLED 49 / 568 ERROR_TOO_MANY_CONTEXT_IDS 49 / 701 ACCOUNT_EXPIRED 49 / 773 USER MUST RESET PASSWORD 50 LDAP_INSUFFICIENT_ACCESS http://wiki.servicenow.com/index.php?title=LDAP_Error_Codes Ok, the problem is that PHP returns me always only 49 (LDAP_INVALID_CREDENTIALS), independent of the situation (situation where have relation with login). Example, if my account is expired, PHP returns me 49, I want that return 49 / 701, how I can find the 701? Is another function? And how I show to the user if his password OR his username is invalid, not both? I know it is a point of security to show that both is invalid, but we decide that is better show what is wrong, if username or if is password, is possible to know with LDAP? PHP Version 5.4.31 EDIT I have found an issue that can be useful: https://bugs.php.net/bug.php?id=47222 Anyone know how to do a ldap_search in this way: ``` ldapsearch -x -H ldap://der-ad-server.de:389 -D accountname@der-ad-server.de -W ``` I don't know how to make this search with PHP `ldap_search()` function

Original source