functions_ldap.php 12 KB

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