functions_ldap.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. <?php
  2. /* Copyright (C) 2007-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2008-2021 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. *
  19. */
  20. /**
  21. * \file htdocs/core/login/functions_ldap.php
  22. * \ingroup core
  23. * \brief Authentication functions for LDAP
  24. */
  25. /**
  26. * Check validity of user/password/entity
  27. * If test is ko, reason must be filled into $_SESSION["dol_loginmesg"]
  28. *
  29. * @param string $usertotest Login
  30. * @param string $passwordtotest Password
  31. * @param int $entitytotest Numero of instance (always 1 if module multicompany not enabled)
  32. * @return string Login if OK, '' if KO
  33. */
  34. function check_user_password_ldap($usertotest, $passwordtotest, $entitytotest)
  35. {
  36. global $db, $conf, $langs;
  37. global $_POST;
  38. global $dolibarr_main_auth_ldap_host, $dolibarr_main_auth_ldap_port;
  39. global $dolibarr_main_auth_ldap_version, $dolibarr_main_auth_ldap_servertype;
  40. global $dolibarr_main_auth_ldap_login_attribute, $dolibarr_main_auth_ldap_dn;
  41. global $dolibarr_main_auth_ldap_admin_login, $dolibarr_main_auth_ldap_admin_pass;
  42. global $dolibarr_main_auth_ldap_filter;
  43. global $dolibarr_main_auth_ldap_debug;
  44. // Force master entity in transversal mode
  45. $entity = $entitytotest;
  46. if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
  47. $entity = 1;
  48. }
  49. $login = '';
  50. $resultFetchUser = '';
  51. if (!function_exists("ldap_connect")) {
  52. dol_syslog("functions_ldap::check_user_password_ldap Authentication KO failed to connect to LDAP. LDAP functions are disabled on this PHP", LOG_ERR);
  53. sleep(1);
  54. // Load translation files required by the page
  55. $langs->loadLangs(array('main', 'other'));
  56. $_SESSION["dol_loginmesg"] = $langs->transnoentitiesnoconv("ErrorLDAPFunctionsAreDisabledOnThisPHP").' '.$langs->transnoentitiesnoconv("TryAnotherConnectionMode");
  57. return '';
  58. }
  59. if ($usertotest) {
  60. dol_syslog("functions_ldap::check_user_password_ldap usertotest=".$usertotest." passwordtotest=".preg_replace('/./', '*', $passwordtotest)." entitytotest=".$entitytotest);
  61. // If test username/password asked, we define $test=false and $login var if ok, set $_SESSION["dol_loginmesg"] if ko
  62. $ldaphost = $dolibarr_main_auth_ldap_host;
  63. $ldapport = $dolibarr_main_auth_ldap_port;
  64. $ldapversion = $dolibarr_main_auth_ldap_version;
  65. $ldapservertype = (empty($dolibarr_main_auth_ldap_servertype) ? 'openldap' : $dolibarr_main_auth_ldap_servertype);
  66. $ldapuserattr = $dolibarr_main_auth_ldap_login_attribute;
  67. $ldapdn = $dolibarr_main_auth_ldap_dn;
  68. $ldapadminlogin = $dolibarr_main_auth_ldap_admin_login;
  69. $ldapadminpass = $dolibarr_main_auth_ldap_admin_pass;
  70. $ldapdebug = ((empty($dolibarr_main_auth_ldap_debug) || $dolibarr_main_auth_ldap_debug == "false") ? false : true);
  71. if ($ldapdebug) {
  72. print "DEBUG: Logging LDAP steps<br>\n";
  73. }
  74. require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php';
  75. $ldap = new Ldap();
  76. $ldap->server = explode(',', $ldaphost);
  77. $ldap->serverPort = $ldapport;
  78. $ldap->ldapProtocolVersion = $ldapversion;
  79. $ldap->serverType = $ldapservertype;
  80. $ldap->searchUser = $ldapadminlogin;
  81. $ldap->searchPassword = $ldapadminpass;
  82. if ($ldapdebug) {
  83. dol_syslog("functions_ldap::check_user_password_ldap Server:".join(',', $ldap->server).", Port:".$ldap->serverPort.", Protocol:".$ldap->ldapProtocolVersion.", Type:".$ldap->serverType);
  84. dol_syslog("functions_ldap::check_user_password_ldap uid/samaccountname=".$ldapuserattr.", dn=".$ldapdn.", Admin:".$ldap->searchUser.", Pass:".dol_trunc($ldap->searchPassword, 3));
  85. print "DEBUG: Server:".join(',', $ldap->server).", Port:".$ldap->serverPort.", Protocol:".$ldap->ldapProtocolVersion.", Type:".$ldap->serverType."<br>\n";
  86. print "DEBUG: uid/samaccountname=".$ldapuserattr.", dn=".$ldapdn.", Admin:".$ldap->searchUser.", Pass:".dol_trunc($ldap->searchPassword, 3)."<br>\n";
  87. }
  88. $resultFetchLdapUser = 0;
  89. // Define $userSearchFilter
  90. $userSearchFilter = "";
  91. if (empty($dolibarr_main_auth_ldap_filter)) {
  92. $userSearchFilter = "(".$ldapuserattr."=".$usertotest.")";
  93. } else {
  94. $userSearchFilter = str_replace('%1%', $usertotest, $dolibarr_main_auth_ldap_filter);
  95. }
  96. // If admin login or ldap auth filter provided
  97. // Code to get user in LDAP from an admin connection (may differ from user connection, done later)
  98. if ($ldapadminlogin || $dolibarr_main_auth_ldap_filter) {
  99. $result = $ldap->connect_bind();
  100. if ($result > 0) {
  101. $resultFetchLdapUser = $ldap->fetch($usertotest, $userSearchFilter);
  102. //dol_syslog('functions_ldap::check_user_password_ldap resultFetchLdapUser='.$resultFetchLdapUser);
  103. if ($resultFetchLdapUser > 0 && $ldap->pwdlastset == 0) { // If ok but password need to be reset
  104. dol_syslog('functions_ldap::check_user_password_ldap '.$usertotest.' must change password next logon');
  105. if ($ldapdebug) {
  106. print "DEBUG: User ".$usertotest." must change password<br>\n";
  107. }
  108. $ldap->unbind();
  109. sleep(1); // Anti brut force protection. Must be same delay when user and password are not valid.
  110. $langs->load('ldap');
  111. $_SESSION["dol_loginmesg"] = $langs->transnoentitiesnoconv("YouMustChangePassNextLogon", $usertotest, $ldap->domainFQDN);
  112. return '';
  113. }
  114. } else {
  115. if ($ldapdebug) {
  116. print "DEBUG: ".$ldap->error."<br>\n";
  117. }
  118. }
  119. $ldap->unbind();
  120. }
  121. // Forge LDAP user and password to test with them
  122. // If LDAP need a dn with login like "uid=jbloggs,ou=People,dc=foo,dc=com", default dn may work even if previous code with
  123. // admin login no exectued.
  124. $ldap->searchUser = $ldapuserattr."=".$usertotest.",".$ldapdn; // Default dn (will work if LDAP accept a dn with login value inside)
  125. // But if LDAP need a dn with name like "cn=Jhon Bloggs,ou=People,dc=foo,dc=com", previous part must have been executed to have
  126. // dn detected into ldapUserDN.
  127. if ($resultFetchLdapUser && !empty($ldap->ldapUserDN)) {
  128. $ldap->searchUser = $ldap->ldapUserDN;
  129. }
  130. $ldap->searchPassword = $passwordtotest;
  131. // Test with this->seachUser and this->searchPassword
  132. //print $resultFetchLdapUser."-".$ldap->ldapUserDN."-".$ldap->searchUser.'-'.$ldap->searchPassword;exit;
  133. $result = $ldap->connect_bind();
  134. if ($result > 0) {
  135. if ($result == 2) { // Connection is ok for user/pass into LDAP
  136. $login = $usertotest;
  137. dol_syslog("functions_ldap::check_user_password_ldap $login authentication ok");
  138. // For the case, we search the user id using a search key without the login (but using other fields like id),
  139. // we need to get the real login to use in the ldap answer.
  140. if (getDolGlobalString('LDAP_FIELD_LOGIN') && !empty($ldap->login)) {
  141. $login = $ldap->login;
  142. dol_syslog("functions_ldap::check_user_password_ldap login is now $login (LDAP_FIELD_LOGIN=".getDolGlobalString('LDAP_FIELD_LOGIN').")");
  143. }
  144. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  145. // Note: Test on date validity is done later natively with isNotIntoValidityDateRange() by core after calling checkLoginPassEntity() that call this method
  146. // ldap2dolibarr synchronisation
  147. if ($login && !empty($conf->ldap->enabled) && getDolGlobalInt('LDAP_SYNCHRO_ACTIVE') == Ldap::SYNCHRO_LDAP_TO_DOLIBARR) { // ldap2dolibarr synchronization
  148. dol_syslog("functions_ldap::check_user_password_ldap Sync ldap2dolibarr");
  149. // On charge les attributs du user ldap
  150. if ($ldapdebug) {
  151. print "DEBUG: login ldap = ".$login."<br>\n";
  152. }
  153. $resultFetchLdapUser = $ldap->fetch($login, $userSearchFilter);
  154. if ($ldapdebug) {
  155. print "DEBUG: UACF = ".join(',', $ldap->uacf)."<br>\n";
  156. }
  157. if ($ldapdebug) {
  158. print "DEBUG: pwdLastSet = ".dol_print_date($ldap->pwdlastset, 'day')."<br>\n";
  159. }
  160. if ($ldapdebug) {
  161. print "DEBUG: badPasswordTime = ".dol_print_date($ldap->badpwdtime, 'day')."<br>\n";
  162. }
  163. // On recherche le user dolibarr en fonction de son SID ldap (only for Active Directory)
  164. $sid = null;
  165. if (getDolGlobalString('LDAP_SERVER_TYPE') == "activedirectory") {
  166. $sid = $ldap->getObjectSid($login);
  167. if ($ldapdebug) {
  168. print "DEBUG: sid = ".$sid."<br>\n";
  169. }
  170. }
  171. $usertmp = new User($db);
  172. $resultFetchUser = $usertmp->fetch('', $login, $sid, 1, ($entitytotest > 0 ? $entitytotest : -1));
  173. if ($resultFetchUser > 0) {
  174. dol_syslog("functions_ldap::check_user_password_ldap Sync user found user id=".$usertmp->id);
  175. // On verifie si le login a change et on met a jour les attributs dolibarr
  176. if ($usertmp->login != $ldap->login && $ldap->login) {
  177. $usertmp->login = $ldap->login;
  178. $usertmp->update($usertmp);
  179. // TODO Que faire si update echoue car on update avec un login deja existant pour un autre compte.
  180. }
  181. //$resultUpdate = $usertmp->update_ldap2dolibarr($ldap);
  182. }
  183. unset($usertmp);
  184. }
  185. if (isModEnabled('multicompany')) { // We must check entity (even if sync is not active)
  186. global $mc;
  187. $usertmp = new User($db);
  188. $usertmp->fetch('', $login);
  189. if (is_object($mc)) {
  190. $ret = $mc->checkRight($usertmp->id, $entitytotest);
  191. if ($ret < 0) {
  192. dol_syslog("functions_ldap::check_user_password_ldap Authentication KO entity '".$entitytotest."' not allowed for user id '".$usertmp->id."'", LOG_NOTICE);
  193. $login = ''; // force authentication failure
  194. }
  195. unset($usertmp);
  196. }
  197. }
  198. }
  199. if ($result == 1) {
  200. dol_syslog("functions_ldap::check_user_password_ldap Authentication KO bad user/password for '".$usertotest."'", LOG_NOTICE);
  201. sleep(1); // Anti brut force protection. Must be same delay when user and password are not valid.
  202. // Load translation files required by the page
  203. $langs->loadLangs(array('main', 'other'));
  204. $_SESSION["dol_loginmesg"] = $langs->transnoentitiesnoconv("ErrorBadLoginPassword");
  205. }
  206. } else {
  207. /* Login failed. Return false, together with the error code and text from
  208. ** the LDAP server. The common error codes and reasons are listed below :
  209. ** (for iPlanet, other servers may differ)
  210. ** 19 - Account locked out (too many invalid login attempts)
  211. ** 32 - User does not exist
  212. ** 49 - Wrong password
  213. ** 53 - Account inactive (manually locked out by administrator)
  214. */
  215. dol_syslog("functions_ldap::check_user_password_ldap Authentication KO failed to connect to LDAP for '".$usertotest."'", LOG_NOTICE);
  216. if (is_resource($ldap->connection) || is_object($ldap->connection)) { // If connection ok but bind ko
  217. try {
  218. $ldap->ldapErrorCode = ldap_errno($ldap->connection);
  219. $ldap->ldapErrorText = ldap_error($ldap->connection);
  220. dol_syslog("functions_ldap::check_user_password_ldap ".$ldap->ldapErrorCode." ".$ldap->ldapErrorText);
  221. } catch (Throwable $exception) {
  222. $ldap->ldapErrorCode = '';
  223. $ldap->ldapErrorText = '';
  224. dol_syslog('functions_ldap::check_user_password_ldap '.$exception, LOG_WARNING);
  225. }
  226. }
  227. sleep(1); // Anti brut force protection. Must be same delay when user and password are not valid.
  228. // Load translation files required by the page
  229. $langs->loadLangs(array('main', 'other', 'errors'));
  230. $_SESSION["dol_loginmesg"] = ($ldap->error ? $ldap->error : $langs->transnoentitiesnoconv("ErrorBadLoginPassword"));
  231. }
  232. $ldap->unbind();
  233. }
  234. return $login;
  235. }