PageRenderTime 36ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/auth/ldap/auth.php

https://github.com/dongsheng/moodle
PHP | 2294 lines | 1374 code | 260 blank | 660 comment | 306 complexity | 825c7d5b6a0a948d06787eff5ce9e0ce MD5 | raw file
Possible License(s): BSD-3-Clause, MIT, GPL-3.0, Apache-2.0, LGPL-2.1
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Authentication Plugin: LDAP Authentication
  18. * Authentication using LDAP (Lightweight Directory Access Protocol).
  19. *
  20. * @package auth_ldap
  21. * @author Martin Dougiamas
  22. * @author IƱaki Arenaza
  23. * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  24. */
  25. defined('MOODLE_INTERNAL') || die();
  26. // See http://support.microsoft.com/kb/305144 to interprete these values.
  27. if (!defined('AUTH_AD_ACCOUNTDISABLE')) {
  28. define('AUTH_AD_ACCOUNTDISABLE', 0x0002);
  29. }
  30. if (!defined('AUTH_AD_NORMAL_ACCOUNT')) {
  31. define('AUTH_AD_NORMAL_ACCOUNT', 0x0200);
  32. }
  33. if (!defined('AUTH_NTLMTIMEOUT')) { // timewindow for the NTLM SSO process, in secs...
  34. define('AUTH_NTLMTIMEOUT', 10);
  35. }
  36. // UF_DONT_EXPIRE_PASSWD value taken from MSDN directly
  37. if (!defined('UF_DONT_EXPIRE_PASSWD')) {
  38. define ('UF_DONT_EXPIRE_PASSWD', 0x00010000);
  39. }
  40. // The Posix uid and gid of the 'nobody' account and 'nogroup' group.
  41. if (!defined('AUTH_UID_NOBODY')) {
  42. define('AUTH_UID_NOBODY', -2);
  43. }
  44. if (!defined('AUTH_GID_NOGROUP')) {
  45. define('AUTH_GID_NOGROUP', -2);
  46. }
  47. // Regular expressions for a valid NTLM username and domain name.
  48. if (!defined('AUTH_NTLM_VALID_USERNAME')) {
  49. define('AUTH_NTLM_VALID_USERNAME', '[^/\\\\\\\\\[\]:;|=,+*?<>@"]+');
  50. }
  51. if (!defined('AUTH_NTLM_VALID_DOMAINNAME')) {
  52. define('AUTH_NTLM_VALID_DOMAINNAME', '[^\\\\\\\\\/:*?"<>|]+');
  53. }
  54. // Default format for remote users if using NTLM SSO
  55. if (!defined('AUTH_NTLM_DEFAULT_FORMAT')) {
  56. define('AUTH_NTLM_DEFAULT_FORMAT', '%domain%\\%username%');
  57. }
  58. if (!defined('AUTH_NTLM_FASTPATH_ATTEMPT')) {
  59. define('AUTH_NTLM_FASTPATH_ATTEMPT', 0);
  60. }
  61. if (!defined('AUTH_NTLM_FASTPATH_YESFORM')) {
  62. define('AUTH_NTLM_FASTPATH_YESFORM', 1);
  63. }
  64. if (!defined('AUTH_NTLM_FASTPATH_YESATTEMPT')) {
  65. define('AUTH_NTLM_FASTPATH_YESATTEMPT', 2);
  66. }
  67. // Allows us to retrieve a diagnostic message in case of LDAP operation error
  68. if (!defined('LDAP_OPT_DIAGNOSTIC_MESSAGE')) {
  69. define('LDAP_OPT_DIAGNOSTIC_MESSAGE', 0x0032);
  70. }
  71. require_once($CFG->libdir.'/authlib.php');
  72. require_once($CFG->libdir.'/ldaplib.php');
  73. require_once($CFG->dirroot.'/user/lib.php');
  74. require_once($CFG->dirroot.'/auth/ldap/locallib.php');
  75. /**
  76. * LDAP authentication plugin.
  77. */
  78. class auth_plugin_ldap extends auth_plugin_base {
  79. /**
  80. * Init plugin config from database settings depending on the plugin auth type.
  81. */
  82. function init_plugin($authtype) {
  83. $this->pluginconfig = 'auth_'.$authtype;
  84. $this->config = get_config($this->pluginconfig);
  85. if (empty($this->config->ldapencoding)) {
  86. $this->config->ldapencoding = 'utf-8';
  87. }
  88. if (empty($this->config->user_type)) {
  89. $this->config->user_type = 'default';
  90. }
  91. $ldap_usertypes = ldap_supported_usertypes();
  92. $this->config->user_type_name = $ldap_usertypes[$this->config->user_type];
  93. unset($ldap_usertypes);
  94. $default = ldap_getdefaults();
  95. // Use defaults if values not given
  96. foreach ($default as $key => $value) {
  97. // watch out - 0, false are correct values too
  98. if (!isset($this->config->{$key}) or $this->config->{$key} == '') {
  99. $this->config->{$key} = $value[$this->config->user_type];
  100. }
  101. }
  102. // Hack prefix to objectclass
  103. $this->config->objectclass = ldap_normalise_objectclass($this->config->objectclass);
  104. }
  105. /**
  106. * Constructor with initialisation.
  107. */
  108. public function __construct() {
  109. $this->authtype = 'ldap';
  110. $this->roleauth = 'auth_ldap';
  111. $this->errorlogtag = '[AUTH LDAP] ';
  112. $this->init_plugin($this->authtype);
  113. }
  114. /**
  115. * Old syntax of class constructor. Deprecated in PHP7.
  116. *
  117. * @deprecated since Moodle 3.1
  118. */
  119. public function auth_plugin_ldap() {
  120. debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
  121. self::__construct();
  122. }
  123. /**
  124. * Returns true if the username and password work and false if they are
  125. * wrong or don't exist.
  126. *
  127. * @param string $username The username (without system magic quotes)
  128. * @param string $password The password (without system magic quotes)
  129. *
  130. * @return bool Authentication success or failure.
  131. */
  132. function user_login($username, $password) {
  133. if (! function_exists('ldap_bind')) {
  134. print_error('auth_ldapnotinstalled', 'auth_ldap');
  135. return false;
  136. }
  137. if (!$username or !$password) { // Don't allow blank usernames or passwords
  138. return false;
  139. }
  140. $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
  141. $extpassword = core_text::convert($password, 'utf-8', $this->config->ldapencoding);
  142. // Before we connect to LDAP, check if this is an AD SSO login
  143. // if we succeed in this block, we'll return success early.
  144. //
  145. $key = sesskey();
  146. if (!empty($this->config->ntlmsso_enabled) && $key === $password) {
  147. $sessusername = get_cache_flag($this->pluginconfig.'/ntlmsess', $key);
  148. // We only get the cache flag if we retrieve it before
  149. // it expires (AUTH_NTLMTIMEOUT seconds).
  150. if (empty($sessusername)) {
  151. return false;
  152. }
  153. if ($username === $sessusername) {
  154. unset($sessusername);
  155. // Check that the user is inside one of the configured LDAP contexts
  156. $validuser = false;
  157. $ldapconnection = $this->ldap_connect();
  158. // if the user is not inside the configured contexts,
  159. // ldap_find_userdn returns false.
  160. if ($this->ldap_find_userdn($ldapconnection, $extusername)) {
  161. $validuser = true;
  162. }
  163. $this->ldap_close();
  164. // Shortcut here - SSO confirmed
  165. return $validuser;
  166. }
  167. } // End SSO processing
  168. unset($key);
  169. $ldapconnection = $this->ldap_connect();
  170. $ldap_user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
  171. // If ldap_user_dn is empty, user does not exist
  172. if (!$ldap_user_dn) {
  173. $this->ldap_close();
  174. return false;
  175. }
  176. // Try to bind with current username and password
  177. $ldap_login = @ldap_bind($ldapconnection, $ldap_user_dn, $extpassword);
  178. // If login fails and we are using MS Active Directory, retrieve the diagnostic
  179. // message to see if this is due to an expired password, or that the user is forced to
  180. // change the password on first login. If it is, only proceed if we can change
  181. // password from Moodle (otherwise we'll get stuck later in the login process).
  182. if (!$ldap_login && ($this->config->user_type == 'ad')
  183. && $this->can_change_password()
  184. && (!empty($this->config->expiration) and ($this->config->expiration == 1))) {
  185. // We need to get the diagnostic message right after the call to ldap_bind(),
  186. // before any other LDAP operation.
  187. ldap_get_option($ldapconnection, LDAP_OPT_DIAGNOSTIC_MESSAGE, $diagmsg);
  188. if ($this->ldap_ad_pwdexpired_from_diagmsg($diagmsg)) {
  189. // If login failed because user must change the password now or the
  190. // password has expired, let the user in. We'll catch this later in the
  191. // login process when we explicitly check for expired passwords.
  192. $ldap_login = true;
  193. }
  194. }
  195. $this->ldap_close();
  196. return $ldap_login;
  197. }
  198. /**
  199. * Reads user information from ldap and returns it in array()
  200. *
  201. * Function should return all information available. If you are saving
  202. * this information to moodle user-table you should honor syncronization flags
  203. *
  204. * @param string $username username
  205. *
  206. * @return mixed array with no magic quotes or false on error
  207. */
  208. function get_userinfo($username) {
  209. $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
  210. $ldapconnection = $this->ldap_connect();
  211. if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extusername))) {
  212. $this->ldap_close();
  213. return false;
  214. }
  215. $search_attribs = array();
  216. $attrmap = $this->ldap_attributes();
  217. foreach ($attrmap as $key => $values) {
  218. if (!is_array($values)) {
  219. $values = array($values);
  220. }
  221. foreach ($values as $value) {
  222. if (!in_array($value, $search_attribs)) {
  223. array_push($search_attribs, $value);
  224. }
  225. }
  226. }
  227. if (!$user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs)) {
  228. $this->ldap_close();
  229. return false; // error!
  230. }
  231. $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
  232. if (empty($user_entry)) {
  233. $this->ldap_close();
  234. return false; // entry not found
  235. }
  236. $result = array();
  237. foreach ($attrmap as $key => $values) {
  238. if (!is_array($values)) {
  239. $values = array($values);
  240. }
  241. $ldapval = NULL;
  242. foreach ($values as $value) {
  243. $entry = $user_entry[0];
  244. if (($value == 'dn') || ($value == 'distinguishedname')) {
  245. $result[$key] = $user_dn;
  246. continue;
  247. }
  248. if (!array_key_exists($value, $entry)) {
  249. continue; // wrong data mapping!
  250. }
  251. if (is_array($entry[$value])) {
  252. $newval = core_text::convert($entry[$value][0], $this->config->ldapencoding, 'utf-8');
  253. } else {
  254. $newval = core_text::convert($entry[$value], $this->config->ldapencoding, 'utf-8');
  255. }
  256. if (!empty($newval)) { // favour ldap entries that are set
  257. $ldapval = $newval;
  258. }
  259. }
  260. if (!is_null($ldapval)) {
  261. $result[$key] = $ldapval;
  262. }
  263. }
  264. $this->ldap_close();
  265. return $result;
  266. }
  267. /**
  268. * Reads user information from ldap and returns it in an object
  269. *
  270. * @param string $username username (with system magic quotes)
  271. * @return mixed object or false on error
  272. */
  273. function get_userinfo_asobj($username) {
  274. $user_array = $this->get_userinfo($username);
  275. if ($user_array == false) {
  276. return false; //error or not found
  277. }
  278. $user_array = truncate_userinfo($user_array);
  279. $user = new stdClass();
  280. foreach ($user_array as $key=>$value) {
  281. $user->{$key} = $value;
  282. }
  283. return $user;
  284. }
  285. /**
  286. * Returns all usernames from LDAP
  287. *
  288. * get_userlist returns all usernames from LDAP
  289. *
  290. * @return array
  291. */
  292. function get_userlist() {
  293. return $this->ldap_get_userlist("({$this->config->user_attribute}=*)");
  294. }
  295. /**
  296. * Checks if user exists on LDAP
  297. *
  298. * @param string $username
  299. */
  300. function user_exists($username) {
  301. $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
  302. // Returns true if given username exists on ldap
  303. $users = $this->ldap_get_userlist('('.$this->config->user_attribute.'='.ldap_filter_addslashes($extusername).')');
  304. return count($users);
  305. }
  306. /**
  307. * Creates a new user on LDAP.
  308. * By using information in userobject
  309. * Use user_exists to prevent duplicate usernames
  310. *
  311. * @param mixed $userobject Moodle userobject
  312. * @param mixed $plainpass Plaintext password
  313. */
  314. function user_create($userobject, $plainpass) {
  315. $extusername = core_text::convert($userobject->username, 'utf-8', $this->config->ldapencoding);
  316. $extpassword = core_text::convert($plainpass, 'utf-8', $this->config->ldapencoding);
  317. switch ($this->config->passtype) {
  318. case 'md5':
  319. $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
  320. break;
  321. case 'sha1':
  322. $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
  323. break;
  324. case 'plaintext':
  325. default:
  326. break; // plaintext
  327. }
  328. $ldapconnection = $this->ldap_connect();
  329. $attrmap = $this->ldap_attributes();
  330. $newuser = array();
  331. foreach ($attrmap as $key => $values) {
  332. if (!is_array($values)) {
  333. $values = array($values);
  334. }
  335. foreach ($values as $value) {
  336. if (!empty($userobject->$key) ) {
  337. $newuser[$value] = core_text::convert($userobject->$key, 'utf-8', $this->config->ldapencoding);
  338. }
  339. }
  340. }
  341. //Following sets all mandatory and other forced attribute values
  342. //User should be creted as login disabled untill email confirmation is processed
  343. //Feel free to add your user type and send patches to paca@sci.fi to add them
  344. //Moodle distribution
  345. switch ($this->config->user_type) {
  346. case 'edir':
  347. $newuser['objectClass'] = array('inetOrgPerson', 'organizationalPerson', 'person', 'top');
  348. $newuser['uniqueId'] = $extusername;
  349. $newuser['logindisabled'] = 'TRUE';
  350. $newuser['userpassword'] = $extpassword;
  351. $uadd = ldap_add($ldapconnection, $this->config->user_attribute.'='.ldap_addslashes($extusername).','.$this->config->create_context, $newuser);
  352. break;
  353. case 'rfc2307':
  354. case 'rfc2307bis':
  355. // posixAccount object class forces us to specify a uidNumber
  356. // and a gidNumber. That is quite complicated to generate from
  357. // Moodle without colliding with existing numbers and without
  358. // race conditions. As this user is supposed to be only used
  359. // with Moodle (otherwise the user would exist beforehand) and
  360. // doesn't need to login into a operating system, we assign the
  361. // user the uid of user 'nobody' and gid of group 'nogroup'. In
  362. // addition to that, we need to specify a home directory. We
  363. // use the root directory ('/') as the home directory, as this
  364. // is the only one can always be sure exists. Finally, even if
  365. // it's not mandatory, we specify '/bin/false' as the login
  366. // shell, to prevent the user from login in at the operating
  367. // system level (Moodle ignores this).
  368. $newuser['objectClass'] = array('posixAccount', 'inetOrgPerson', 'organizationalPerson', 'person', 'top');
  369. $newuser['cn'] = $extusername;
  370. $newuser['uid'] = $extusername;
  371. $newuser['uidNumber'] = AUTH_UID_NOBODY;
  372. $newuser['gidNumber'] = AUTH_GID_NOGROUP;
  373. $newuser['homeDirectory'] = '/';
  374. $newuser['loginShell'] = '/bin/false';
  375. // IMPORTANT:
  376. // We have to create the account locked, but posixAccount has
  377. // no attribute to achive this reliably. So we are going to
  378. // modify the password in a reversable way that we can later
  379. // revert in user_activate().
  380. //
  381. // Beware that this can be defeated by the user if we are not
  382. // using MD5 or SHA-1 passwords. After all, the source code of
  383. // Moodle is available, and the user can see the kind of
  384. // modification we are doing and 'undo' it by hand (but only
  385. // if we are using plain text passwords).
  386. //
  387. // Also bear in mind that you need to use a binding user that
  388. // can create accounts and has read/write privileges on the
  389. // 'userPassword' attribute for this to work.
  390. $newuser['userPassword'] = '*'.$extpassword;
  391. $uadd = ldap_add($ldapconnection, $this->config->user_attribute.'='.ldap_addslashes($extusername).','.$this->config->create_context, $newuser);
  392. break;
  393. case 'ad':
  394. // User account creation is a two step process with AD. First you
  395. // create the user object, then you set the password. If you try
  396. // to set the password while creating the user, the operation
  397. // fails.
  398. // Passwords in Active Directory must be encoded as Unicode
  399. // strings (UCS-2 Little Endian format) and surrounded with
  400. // double quotes. See http://support.microsoft.com/?kbid=269190
  401. if (!function_exists('mb_convert_encoding')) {
  402. print_error('auth_ldap_no_mbstring', 'auth_ldap');
  403. }
  404. // Check for invalid sAMAccountName characters.
  405. if (preg_match('#[/\\[\]:;|=,+*?<>@"]#', $extusername)) {
  406. print_error ('auth_ldap_ad_invalidchars', 'auth_ldap');
  407. }
  408. // First create the user account, and mark it as disabled.
  409. $newuser['objectClass'] = array('top', 'person', 'user', 'organizationalPerson');
  410. $newuser['sAMAccountName'] = $extusername;
  411. $newuser['userAccountControl'] = AUTH_AD_NORMAL_ACCOUNT |
  412. AUTH_AD_ACCOUNTDISABLE;
  413. $userdn = 'cn='.ldap_addslashes($extusername).','.$this->config->create_context;
  414. if (!ldap_add($ldapconnection, $userdn, $newuser)) {
  415. print_error('auth_ldap_ad_create_req', 'auth_ldap');
  416. }
  417. // Now set the password
  418. unset($newuser);
  419. $newuser['unicodePwd'] = mb_convert_encoding('"' . $extpassword . '"',
  420. 'UCS-2LE', 'UTF-8');
  421. if(!ldap_modify($ldapconnection, $userdn, $newuser)) {
  422. // Something went wrong: delete the user account and error out
  423. ldap_delete ($ldapconnection, $userdn);
  424. print_error('auth_ldap_ad_create_req', 'auth_ldap');
  425. }
  426. $uadd = true;
  427. break;
  428. default:
  429. print_error('auth_ldap_unsupportedusertype', 'auth_ldap', '', $this->config->user_type_name);
  430. }
  431. $this->ldap_close();
  432. return $uadd;
  433. }
  434. /**
  435. * Returns true if plugin allows resetting of password from moodle.
  436. *
  437. * @return bool
  438. */
  439. function can_reset_password() {
  440. return !empty($this->config->stdchangepassword);
  441. }
  442. /**
  443. * Returns true if plugin can be manually set.
  444. *
  445. * @return bool
  446. */
  447. function can_be_manually_set() {
  448. return true;
  449. }
  450. /**
  451. * Returns true if plugin allows signup and user creation.
  452. *
  453. * @return bool
  454. */
  455. function can_signup() {
  456. return (!empty($this->config->auth_user_create) and !empty($this->config->create_context));
  457. }
  458. /**
  459. * Sign up a new user ready for confirmation.
  460. * Password is passed in plaintext.
  461. *
  462. * @param object $user new user object
  463. * @param boolean $notify print notice with link and terminate
  464. * @return boolean success
  465. */
  466. function user_signup($user, $notify=true) {
  467. global $CFG, $DB, $PAGE, $OUTPUT;
  468. require_once($CFG->dirroot.'/user/profile/lib.php');
  469. require_once($CFG->dirroot.'/user/lib.php');
  470. if ($this->user_exists($user->username)) {
  471. print_error('auth_ldap_user_exists', 'auth_ldap');
  472. }
  473. $plainslashedpassword = $user->password;
  474. unset($user->password);
  475. if (! $this->user_create($user, $plainslashedpassword)) {
  476. print_error('auth_ldap_create_error', 'auth_ldap');
  477. }
  478. $user->id = user_create_user($user, false, false);
  479. user_add_password_history($user->id, $plainslashedpassword);
  480. // Save any custom profile field information
  481. profile_save_data($user);
  482. $userinfo = $this->get_userinfo($user->username);
  483. $this->update_user_record($user->username, false, false, $this->is_user_suspended((object) $userinfo));
  484. // This will also update the stored hash to the latest algorithm
  485. // if the existing hash is using an out-of-date algorithm (or the
  486. // legacy md5 algorithm).
  487. update_internal_user_password($user, $plainslashedpassword);
  488. $user = $DB->get_record('user', array('id'=>$user->id));
  489. \core\event\user_created::create_from_userid($user->id)->trigger();
  490. if (! send_confirmation_email($user)) {
  491. print_error('noemail', 'auth_ldap');
  492. }
  493. if ($notify) {
  494. $emailconfirm = get_string('emailconfirm');
  495. $PAGE->set_url('/auth/ldap/auth.php');
  496. $PAGE->navbar->add($emailconfirm);
  497. $PAGE->set_title($emailconfirm);
  498. $PAGE->set_heading($emailconfirm);
  499. echo $OUTPUT->header();
  500. notice(get_string('emailconfirmsent', '', $user->email), "{$CFG->wwwroot}/index.php");
  501. } else {
  502. return true;
  503. }
  504. }
  505. /**
  506. * Returns true if plugin allows confirming of new users.
  507. *
  508. * @return bool
  509. */
  510. function can_confirm() {
  511. return $this->can_signup();
  512. }
  513. /**
  514. * Confirm the new user as registered.
  515. *
  516. * @param string $username
  517. * @param string $confirmsecret
  518. */
  519. function user_confirm($username, $confirmsecret) {
  520. global $DB;
  521. $user = get_complete_user_data('username', $username);
  522. if (!empty($user)) {
  523. if ($user->auth != $this->authtype) {
  524. return AUTH_CONFIRM_ERROR;
  525. } else if ($user->secret === $confirmsecret && $user->confirmed) {
  526. return AUTH_CONFIRM_ALREADY;
  527. } else if ($user->secret === $confirmsecret) { // They have provided the secret key to get in
  528. if (!$this->user_activate($username)) {
  529. return AUTH_CONFIRM_FAIL;
  530. }
  531. $user->confirmed = 1;
  532. user_update_user($user, false);
  533. return AUTH_CONFIRM_OK;
  534. }
  535. } else {
  536. return AUTH_CONFIRM_ERROR;
  537. }
  538. }
  539. /**
  540. * Return number of days to user password expires
  541. *
  542. * If userpassword does not expire it should return 0. If password is already expired
  543. * it should return negative value.
  544. *
  545. * @param mixed $username username
  546. * @return integer
  547. */
  548. function password_expire($username) {
  549. $result = 0;
  550. $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
  551. $ldapconnection = $this->ldap_connect();
  552. $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
  553. $search_attribs = array($this->config->expireattr);
  554. $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
  555. if ($sr) {
  556. $info = ldap_get_entries_moodle($ldapconnection, $sr);
  557. if (!empty ($info)) {
  558. $info = $info[0];
  559. if (isset($info[$this->config->expireattr][0])) {
  560. $expiretime = $this->ldap_expirationtime2unix($info[$this->config->expireattr][0], $ldapconnection, $user_dn);
  561. if ($expiretime != 0) {
  562. $now = time();
  563. if ($expiretime > $now) {
  564. $result = ceil(($expiretime - $now) / DAYSECS);
  565. } else {
  566. $result = floor(($expiretime - $now) / DAYSECS);
  567. }
  568. }
  569. }
  570. }
  571. } else {
  572. error_log($this->errorlogtag.get_string('didtfindexpiretime', 'auth_ldap'));
  573. }
  574. return $result;
  575. }
  576. /**
  577. * Syncronizes user fron external LDAP server to moodle user table
  578. *
  579. * Sync is now using username attribute.
  580. *
  581. * Syncing users removes or suspends users that dont exists anymore in external LDAP.
  582. * Creates new users and updates coursecreator status of users.
  583. *
  584. * @param bool $do_updates will do pull in data updates from LDAP if relevant
  585. */
  586. function sync_users($do_updates=true) {
  587. global $CFG, $DB;
  588. require_once($CFG->dirroot . '/user/profile/lib.php');
  589. print_string('connectingldap', 'auth_ldap');
  590. $ldapconnection = $this->ldap_connect();
  591. $dbman = $DB->get_manager();
  592. /// Define table user to be created
  593. $table = new xmldb_table('tmp_extuser');
  594. $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
  595. $table->add_field('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
  596. $table->add_field('mnethostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
  597. $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
  598. $table->add_index('username', XMLDB_INDEX_UNIQUE, array('mnethostid', 'username'));
  599. print_string('creatingtemptable', 'auth_ldap', 'tmp_extuser');
  600. $dbman->create_temp_table($table);
  601. ////
  602. //// get user's list from ldap to sql in a scalable fashion
  603. ////
  604. // prepare some data we'll need
  605. $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
  606. $servercontrols = array();
  607. $contexts = explode(';', $this->config->contexts);
  608. if (!empty($this->config->create_context)) {
  609. array_push($contexts, $this->config->create_context);
  610. }
  611. $ldappagedresults = ldap_paged_results_supported($this->config->ldap_version, $ldapconnection);
  612. $ldapcookie = '';
  613. foreach ($contexts as $context) {
  614. $context = trim($context);
  615. if (empty($context)) {
  616. continue;
  617. }
  618. do {
  619. if ($ldappagedresults) {
  620. // TODO: Remove the old branch of code once PHP 7.3.0 becomes required (Moodle 3.11).
  621. if (version_compare(PHP_VERSION, '7.3.0', '<')) {
  622. // Before 7.3, use this function that was deprecated in PHP 7.4.
  623. ldap_control_paged_result($ldapconnection, $this->config->pagesize, true, $ldapcookie);
  624. } else {
  625. // PHP 7.3 and up, use server controls.
  626. $servercontrols = array(array(
  627. 'oid' => LDAP_CONTROL_PAGEDRESULTS, 'value' => array(
  628. 'size' => $this->config->pagesize, 'cookie' => $ldapcookie)));
  629. }
  630. }
  631. if ($this->config->search_sub) {
  632. // Use ldap_search to find first user from subtree.
  633. // TODO: Remove the old branch of code once PHP 7.3.0 becomes required (Moodle 3.11).
  634. if (version_compare(PHP_VERSION, '7.3.0', '<')) {
  635. $ldapresult = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute));
  636. } else {
  637. $ldapresult = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute),
  638. 0, -1, -1, LDAP_DEREF_NEVER, $servercontrols);
  639. }
  640. } else {
  641. // Search only in this context.
  642. // TODO: Remove the old branch of code once PHP 7.3.0 becomes required (Moodle 3.11).
  643. if (version_compare(PHP_VERSION, '7.3.0', '<')) {
  644. $ldapresult = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute));
  645. } else {
  646. $ldapresult = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute),
  647. 0, -1, -1, LDAP_DEREF_NEVER, $servercontrols);
  648. }
  649. }
  650. if (!$ldapresult) {
  651. continue;
  652. }
  653. if ($ldappagedresults) {
  654. // Get next server cookie to know if we'll need to continue searching.
  655. $ldapcookie = '';
  656. // TODO: Remove the old branch of code once PHP 7.3.0 becomes required (Moodle 3.11).
  657. if (version_compare(PHP_VERSION, '7.3.0', '<')) {
  658. // Before 7.3, use this function that was deprecated in PHP 7.4.
  659. $pagedresp = ldap_control_paged_result_response($ldapconnection, $ldapresult, $ldapcookie);
  660. // Function ldap_control_paged_result_response() does not overwrite $ldapcookie if it fails, by
  661. // setting this to null we avoid an infinite loop.
  662. if ($pagedresp === false) {
  663. $ldapcookie = null;
  664. }
  665. } else {
  666. // Get next cookie from controls.
  667. ldap_parse_result($ldapconnection, $ldapresult, $errcode, $matcheddn,
  668. $errmsg, $referrals, $controls);
  669. if (isset($controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'])) {
  670. $ldapcookie = $controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'];
  671. }
  672. }
  673. }
  674. if ($entry = @ldap_first_entry($ldapconnection, $ldapresult)) {
  675. do {
  676. $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
  677. $value = core_text::convert($value[0], $this->config->ldapencoding, 'utf-8');
  678. $value = trim($value);
  679. $this->ldap_bulk_insert($value);
  680. } while ($entry = ldap_next_entry($ldapconnection, $entry));
  681. }
  682. unset($ldapresult); // Free mem.
  683. } while ($ldappagedresults && $ldapcookie !== null && $ldapcookie != '');
  684. }
  685. // If LDAP paged results were used, the current connection must be completely
  686. // closed and a new one created, to work without paged results from here on.
  687. if ($ldappagedresults) {
  688. $this->ldap_close(true);
  689. $ldapconnection = $this->ldap_connect();
  690. }
  691. /// preserve our user database
  692. /// if the temp table is empty, it probably means that something went wrong, exit
  693. /// so as to avoid mass deletion of users; which is hard to undo
  694. $count = $DB->count_records_sql('SELECT COUNT(username) AS count, 1 FROM {tmp_extuser}');
  695. if ($count < 1) {
  696. print_string('didntgetusersfromldap', 'auth_ldap');
  697. $dbman->drop_table($table);
  698. $this->ldap_close();
  699. return false;
  700. } else {
  701. print_string('gotcountrecordsfromldap', 'auth_ldap', $count);
  702. }
  703. /// User removal
  704. // Find users in DB that aren't in ldap -- to be removed!
  705. // this is still not as scalable (but how often do we mass delete?)
  706. if ($this->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
  707. $sql = "SELECT u.*
  708. FROM {user} u
  709. LEFT JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
  710. WHERE u.auth = :auth
  711. AND u.deleted = 0
  712. AND e.username IS NULL";
  713. $remove_users = $DB->get_records_sql($sql, array('auth'=>$this->authtype));
  714. if (!empty($remove_users)) {
  715. print_string('userentriestoremove', 'auth_ldap', count($remove_users));
  716. foreach ($remove_users as $user) {
  717. if (delete_user($user)) {
  718. echo "\t"; print_string('auth_dbdeleteuser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
  719. } else {
  720. echo "\t"; print_string('auth_dbdeleteusererror', 'auth_db', $user->username); echo "\n";
  721. }
  722. }
  723. } else {
  724. print_string('nouserentriestoremove', 'auth_ldap');
  725. }
  726. unset($remove_users); // Free mem!
  727. } else if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
  728. $sql = "SELECT u.*
  729. FROM {user} u
  730. LEFT JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
  731. WHERE u.auth = :auth
  732. AND u.deleted = 0
  733. AND u.suspended = 0
  734. AND e.username IS NULL";
  735. $remove_users = $DB->get_records_sql($sql, array('auth'=>$this->authtype));
  736. if (!empty($remove_users)) {
  737. print_string('userentriestoremove', 'auth_ldap', count($remove_users));
  738. foreach ($remove_users as $user) {
  739. $updateuser = new stdClass();
  740. $updateuser->id = $user->id;
  741. $updateuser->suspended = 1;
  742. user_update_user($updateuser, false);
  743. echo "\t"; print_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
  744. \core\session\manager::kill_user_sessions($user->id);
  745. }
  746. } else {
  747. print_string('nouserentriestoremove', 'auth_ldap');
  748. }
  749. unset($remove_users); // Free mem!
  750. }
  751. /// Revive suspended users
  752. if (!empty($this->config->removeuser) and $this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
  753. $sql = "SELECT u.id, u.username
  754. FROM {user} u
  755. JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
  756. WHERE (u.auth = 'nologin' OR (u.auth = ? AND u.suspended = 1)) AND u.deleted = 0";
  757. // Note: 'nologin' is there for backwards compatibility.
  758. $revive_users = $DB->get_records_sql($sql, array($this->authtype));
  759. if (!empty($revive_users)) {
  760. print_string('userentriestorevive', 'auth_ldap', count($revive_users));
  761. foreach ($revive_users as $user) {
  762. $updateuser = new stdClass();
  763. $updateuser->id = $user->id;
  764. $updateuser->auth = $this->authtype;
  765. $updateuser->suspended = 0;
  766. user_update_user($updateuser, false);
  767. echo "\t"; print_string('auth_dbreviveduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
  768. }
  769. } else {
  770. print_string('nouserentriestorevive', 'auth_ldap');
  771. }
  772. unset($revive_users);
  773. }
  774. /// User Updates - time-consuming (optional)
  775. if ($do_updates) {
  776. // Narrow down what fields we need to update
  777. $updatekeys = $this->get_profile_keys();
  778. } else {
  779. print_string('noupdatestobedone', 'auth_ldap');
  780. }
  781. if ($do_updates and !empty($updatekeys)) { // run updates only if relevant
  782. $users = $DB->get_records_sql('SELECT u.username, u.id
  783. FROM {user} u
  784. WHERE u.deleted = 0 AND u.auth = ? AND u.mnethostid = ?',
  785. array($this->authtype, $CFG->mnet_localhost_id));
  786. if (!empty($users)) {
  787. print_string('userentriestoupdate', 'auth_ldap', count($users));
  788. $transaction = $DB->start_delegated_transaction();
  789. $xcount = 0;
  790. $maxxcount = 100;
  791. foreach ($users as $user) {
  792. echo "\t"; print_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id));
  793. $userinfo = $this->get_userinfo($user->username);
  794. if (!$this->update_user_record($user->username, $updatekeys, true,
  795. $this->is_user_suspended((object) $userinfo))) {
  796. echo ' - '.get_string('skipped');
  797. }
  798. echo "\n";
  799. $xcount++;
  800. // Update system roles, if needed.
  801. $this->sync_roles($user);
  802. }
  803. $transaction->allow_commit();
  804. unset($users); // free mem
  805. }
  806. } else { // end do updates
  807. print_string('noupdatestobedone', 'auth_ldap');
  808. }
  809. /// User Additions
  810. // Find users missing in DB that are in LDAP
  811. // and gives me a nifty object I don't want.
  812. // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
  813. $sql = 'SELECT e.id, e.username
  814. FROM {tmp_extuser} e
  815. LEFT JOIN {user} u ON (e.username = u.username AND e.mnethostid = u.mnethostid)
  816. WHERE u.id IS NULL';
  817. $add_users = $DB->get_records_sql($sql);
  818. if (!empty($add_users)) {
  819. print_string('userentriestoadd', 'auth_ldap', count($add_users));
  820. $errors = 0;
  821. $transaction = $DB->start_delegated_transaction();
  822. foreach ($add_users as $user) {
  823. $user = $this->get_userinfo_asobj($user->username);
  824. // Prep a few params
  825. $user->modified = time();
  826. $user->confirmed = 1;
  827. $user->auth = $this->authtype;
  828. $user->mnethostid = $CFG->mnet_localhost_id;
  829. // get_userinfo_asobj() might have replaced $user->username with the value
  830. // from the LDAP server (which can be mixed-case). Make sure it's lowercase
  831. $user->username = trim(core_text::strtolower($user->username));
  832. // It isn't possible to just rely on the configured suspension attribute since
  833. // things like active directory use bit masks, other things using LDAP might
  834. // do different stuff as well.
  835. //
  836. // The cast to int is a workaround for MDL-53959.
  837. $user->suspended = (int)$this->is_user_suspended($user);
  838. if (empty($user->calendartype)) {
  839. $user->calendartype = $CFG->calendartype;
  840. }
  841. // $id = user_create_user($user, false);
  842. try {
  843. $id = user_create_user($user, false);
  844. } catch (Exception $e) {
  845. print_string('invaliduserexception', 'auth_ldap', print_r($user, true) . $e->getMessage());
  846. $errors++;
  847. continue;
  848. }
  849. echo "\t"; print_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username, 'id'=>$id)); echo "\n";
  850. $euser = $DB->get_record('user', array('id' => $id));
  851. if (!empty($this->config->forcechangepassword)) {
  852. set_user_preference('auth_forcepasswordchange', 1, $id);
  853. }
  854. // Save custom profile fields.
  855. $this->update_user_record($user->username, $this->get_profile_keys(true), false);
  856. // Add roles if needed.
  857. $this->sync_roles($euser);
  858. }
  859. // Display number of user creation errors, if any.
  860. if ($errors) {
  861. print_string('invalidusererrors', 'auth_ldap', $errors);
  862. }
  863. $transaction->allow_commit();
  864. unset($add_users); // free mem
  865. } else {
  866. print_string('nouserstobeadded', 'auth_ldap');
  867. }
  868. $dbman->drop_table($table);
  869. $this->ldap_close();
  870. return true;
  871. }
  872. /**
  873. * Bulk insert in SQL's temp table
  874. */
  875. function ldap_bulk_insert($username) {
  876. global $DB, $CFG;
  877. $username = core_text::strtolower($username); // usernames are __always__ lowercase.
  878. $DB->insert_record_raw('tmp_extuser', array('username'=>$username,
  879. 'mnethostid'=>$CFG->mnet_localhost_id), false, true);
  880. echo '.';
  881. }
  882. /**
  883. * Activates (enables) user in external LDAP so user can login
  884. *
  885. * @param mixed $username
  886. * @return boolean result
  887. */
  888. function user_activate($username) {
  889. $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
  890. $ldapconnection = $this->ldap_connect();
  891. $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
  892. switch ($this->config->user_type) {
  893. case 'edir':
  894. $newinfo['loginDisabled'] = 'FALSE';
  895. break;
  896. case 'rfc2307':
  897. case 'rfc2307bis':
  898. // Remember that we add a '*' character in front of the
  899. // external password string to 'disable' the account. We just
  900. // need to remove it.
  901. $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
  902. array('userPassword'));
  903. $info = ldap_get_entries($ldapconnection, $sr);
  904. $info[0] = array_change_key_case($info[0], CASE_LOWER);
  905. $newinfo['userPassword'] = ltrim($info[0]['userpassword'][0], '*');
  906. break;
  907. case 'ad':
  908. // We need to unset the ACCOUNTDISABLE bit in the
  909. // userAccountControl attribute ( see
  910. // http://support.microsoft.com/kb/305144 )
  911. $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
  912. array('userAccountControl'));
  913. $info = ldap_get_entries($ldapconnection, $sr);
  914. $info[0] = array_change_key_case($info[0], CASE_LOWER);
  915. $newinfo['userAccountControl'] = $info[0]['useraccountcontrol'][0]
  916. & (~AUTH_AD_ACCOUNTDISABLE);
  917. break;
  918. default:
  919. print_error('user_activatenotsupportusertype', 'auth_ldap', '', $this->config->user_type_name);
  920. }
  921. $result = ldap_modify($ldapconnection, $userdn, $newinfo);
  922. $this->ldap_close();
  923. return $result;
  924. }
  925. /**
  926. * Returns true if user should be coursecreator.
  927. *
  928. * @param mixed $username username (without system magic quotes)
  929. * @return mixed result null if course creators is not configured, boolean otherwise.
  930. *
  931. * @deprecated since Moodle 3.4 MDL-30634 - please do not use this function any more.
  932. */
  933. function iscreator($username) {
  934. debugging('iscreator() is deprecated. Please use auth_plugin_ldap::is_role() instead.', DEBUG_DEVELOPER);
  935. if (empty($this->config->creators) or empty($this->config->memberattribute)) {
  936. return null;
  937. }
  938. $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
  939. $ldapconnection = $this->ldap_connect();
  940. if ($this->config->memberattribute_isdn) {
  941. if(!($userid = $this->ldap_find_userdn($ldapconnection, $extusername))) {
  942. return false;
  943. }
  944. } else {
  945. $userid = $extusername;
  946. }
  947. $group_dns = explode(';', $this->config->creators);
  948. $creator = ldap_isgroupmember($ldapconnection, $userid, $group_dns, $this->config->memberattribute);
  949. $this->ldap_close();
  950. return $creator;
  951. }
  952. /**
  953. * Check if user has LDAP group membership.
  954. *
  955. * Returns true if user should be assigned role.
  956. *
  957. * @param mixed $username username (without system magic quotes).
  958. * @param array $role Array of role's shortname, localname, and settingname for the config value.
  959. * @return mixed result null if role/LDAP context is not configured, boolean otherwise.
  960. */
  961. private function is_role($username, $role) {
  962. if (empty($this->config->{$role['settingname']}) or empty($this->config->memberattribute)) {
  963. return null;
  964. }
  965. $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
  966. $ldapconnection = $this->ldap_connect();
  967. if ($this->config->memberattribute_isdn) {
  968. if (!($userid = $this->ldap_find_userdn($ldapconnection, $extusername))) {
  969. return false;
  970. }
  971. } else {
  972. $userid = $extusername;
  973. }
  974. $groupdns = explode(';', $this->config->{$role['settingname']});
  975. $isrole = ldap_isgroupmember($ldapconnection, $userid, $groupdns, $this->config->memberattribute);
  976. $this->ldap_close();
  977. return $isrole;
  978. }
  979. /**
  980. * Called when the user record is updated.
  981. *
  982. * Modifies user in external LDAP server. It takes olduser (before
  983. * changes) and newuser (after changes) compares information and
  984. * saves modified information to external LDAP server.
  985. *
  986. * @param mixed $olduser Userobject before modifications (without system magic quotes)
  987. * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
  988. * @return boolean result
  989. *
  990. */
  991. function user_update($olduser, $newuser) {
  992. global $CFG;
  993. require_once($CFG->dirroot . '/user/profile/lib.php');
  994. if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
  995. error_log($this->errorlogtag.get_string('renamingnotallowed', 'auth_ldap'));
  996. return false;
  997. }
  998. if (isset($olduser->auth) and $olduser->auth != $this->authtype) {
  999. return true; // just change auth and skip update
  1000. }
  1001. $attrmap = $this->ldap_attributes();
  1002. // Before doing anything else, make sure we really need to update anything
  1003. // in the external LDAP server.
  1004. $update_external = false;
  1005. foreach ($attrmap as $key => $ldapkeys) {
  1006. if (!empty($this->config->{'field_updateremote_'.$key})) {
  1007. $update_external = true;
  1008. break;
  1009. }
  1010. }
  1011. if (!$update_external) {
  1012. return true;
  1013. }
  1014. $extoldusername = core_text::convert($olduser->username, 'utf-8', $this->config->ldapencoding);
  1015. $ldapconnection = $this->ldap_connect();
  1016. $search_attribs = array();
  1017. foreach ($attrmap as $key => $values) {
  1018. if (!is_array($values)) {
  1019. $values = array($values);
  1020. }
  1021. foreach ($values as $value) {
  1022. if (!in_array($value, $search_attribs)) {
  1023. array_push($search_attribs, $value);
  1024. }
  1025. }
  1026. }
  1027. if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extoldusername))) {
  1028. return false;
  1029. }
  1030. // Load old custom fields.
  1031. $olduserprofilefields = (array) profile_user_record($olduser->id, false);
  1032. $fields = array();
  1033. foreach (profile_get_custom_fields(false) as $field) {
  1034. $fields[$field->shortname] = $field;
  1035. }
  1036. $success = true;
  1037. $user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
  1038. if ($user_info_result) {
  1039. $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
  1040. if (empty($user_entry)) {
  1041. $attribs = join (', ', $search_attribs);
  1042. error_log($this->errorlogtag.get_string('updateusernotfound', 'auth_ldap',
  1043. array('userdn'=>$user_dn,
  1044. 'attribs'=>$attribs)));
  1045. return false; // old user not found!
  1046. } else if (count($user_entry) > 1) {
  1047. error_log($this->errorlogtag.get_string('morethanoneuser', 'auth_ldap'));
  1048. return false;
  1049. }
  1050. $user_entry = $user_entry[0];
  1051. foreach ($attrmap as $key => $ldapkeys) {
  1052. if (preg_match('/^profile_field_(.*)$/', $key, $match)) {
  1053. // Custom field.
  1054. $fieldname = $match[1];
  1055. if (isset($fields[$fieldname])) {
  1056. $class = 'profile_field_' . $fields[$fieldname]->datatype;
  1057. $formfield = new $class($fields[$fieldname]->id, $olduser->id);
  1058. $oldvalue = isset($olduserprofilefields[$fieldname]) ? $olduserprofilefields[$fieldname] : null;
  1059. } else {
  1060. $oldvalue = null;
  1061. }
  1062. $newvalue = $formfield->edit_save_data_preprocess($newuser->{$formfield->inputname}, new stdClass);
  1063. } else {
  1064. // Standard field.
  1065. $oldvalue = isset($olduser->$key) ? $olduser->$key : null;
  1066. $newvalue = isset($newuser->$key) ? $newuser->$key : null;
  1067. }
  1068. if ($newvalue !== null and $newvalue !== $oldvalue and !empty($this->config->{'field_updateremote_' . $key})) {
  1069. // For ldap values that could be in more than one
  1070. // ldap key, we will do our best to match
  1071. // where they came from
  1072. $ambiguous = true;
  1073. $changed = false;
  1074. if (!is_array($ldapkeys)) {
  1075. $ldapkeys = array($ldapkeys);
  1076. }
  1077. if (count($ldapkeys) < 2) {
  1078. $ambiguous = false;
  1079. }
  1080. $nuvalue = core_text::convert($newvalue, 'utf-8', $this->config->ldapencoding);
  1081. empty($nuvalue) ? $nuvalue = array() : $nuvalue;
  1082. $ouvalue = core_text::convert($oldvalue, 'utf-8', $this->config->ldapencoding);
  1083. foreach ($ldapkeys as $ldapkey) {
  1084. // If the field is empty in LDAP there are two options:
  1085. // 1. We get the LDAP field using ldap_first_attribute.
  1086. // 2. LDAP don't send the field using ldap_first_attribute.
  1087. // So, for option 1 we check the if the field is retrieve it.
  1088. // And get the original value of field in LDAP if the field.
  1089. // Otherwise, let value in blank and delegate the check in ldap_modify.
  1090. if (isset($user_entry[$ldapkey][0])) {
  1091. $ldapvalue = $user_entry[$ldapkey][0];
  1092. } else {
  1093. $ldapvalue = '';
  1094. }
  1095. if (!$ambiguous) {
  1096. // Skip update if the values already match
  1097. if ($nuvalue !== $ldapvalue) {
  1098. // This might fail due to schema validation
  1099. if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
  1100. $changed = true;
  1101. continue;
  1102. } else {
  1103. $success = false;
  1104. error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
  1105. array('errno'=>ldap_errno($ldapconnection),
  1106. 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
  1107. 'key'=>$key,
  1108. 'ouvalue'=>$ouvalue,
  1109. 'nuvalue'=>$nuvalue)));
  1110. continue;
  1111. }
  1112. }
  1113. } else {
  1114. // Ambiguous. Value empty before in Moodle (and LDAP) - use
  1115. // 1st ldap candidate field, no need to guess
  1116. if ($ouvalue === '') { // value empty before - use 1st ldap candidate
  1117. // This might fail due to schema validation
  1118. if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
  1119. $changed = true;
  1120. continue;
  1121. } else {
  1122. $success = false;
  1123. error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
  1124. array('errno'=>ldap_errno($ldapconnection),
  1125. 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
  1126. 'key'=>$key,
  1127. 'ouvalue'=>$ouvalue,
  1128. 'nuvalue'=>$nuvalue)));
  1129. continue;
  1130. }
  1131. }
  1132. // We found which ldap key to update!
  1133. if ($ouvalue !== '' and $ouvalue === $ldapvalue ) {
  1134. // This might fail due to schema validation
  1135. if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
  1136. $changed = true;
  1137. continue;
  1138. } else {
  1139. $success = false;
  1140. error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
  1141. array('errno'=>ldap_errno($ldapconnection),
  1142. 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
  1143. 'key'=>$key,
  1144. 'ouvalue'=>$ouvalue,
  1145. 'nuvalue'=>$nuvalue)));
  1146. continue;
  1147. }
  1148. }
  1149. }
  1150. }
  1151. if ($ambiguous and !$changed) {
  1152. $success = false;
  1153. error_log($this->errorlogtag.get_string ('updateremfailamb', 'auth_ldap',
  1154. array('key'=>$key,
  1155. 'ouvalue'=>$ouvalue,
  1156. 'nuvalue'=>$nuvalue)));
  1157. }
  1158. }
  1159. }
  1160. } else {
  1161. error_log($this->errorlogtag.get_string ('usernotfound', 'auth_ldap'));
  1162. $success = false;
  1163. }
  1164. $this->ldap_close();
  1165. return $success;
  1166. }
  1167. /**
  1168. * Changes userpassword in LDAP
  1169. *
  1170. * Called when the user password is updated. It assumes it is
  1171. * called by an admin or that you've otherwise checked the user's
  1172. * credentials
  1173. *
  1174. * @param object $user User table object
  1175. * @param string $newpassword Plaintext password (not crypted/md5'ed)
  1176. * @return boolean result
  1177. *
  1178. */
  1179. function user_update_password($user, $newpassword) {
  1180. global $USER;
  1181. $result = false;
  1182. $username = $user->username;
  1183. $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
  1184. $extpassword = core_text::convert($newpassword, 'utf-8', $this->config->ldapencoding);
  1185. switch ($this->config->passtype) {
  1186. case 'md5':
  1187. $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
  1188. break;
  1189. case 'sha1':
  1190. $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
  1191. break;
  1192. case 'plaintext':
  1193. default:
  1194. break; // plaintext
  1195. }
  1196. $ldapconnection = $this->ldap_connect();
  1197. $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
  1198. if (!$user_dn) {
  1199. error_log($this->errorlogtag.get_string ('nodnforusername', 'auth_ldap', $user->username));
  1200. return false;
  1201. }
  1202. switch ($this->config->user_type) {
  1203. case 'edir':
  1204. // Change password
  1205. $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
  1206. if (!$result) {
  1207. error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
  1208. array('errno'=>ldap_errno($ldapconnection),
  1209. 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
  1210. }
  1211. // Update password expiration time, grace logins count
  1212. $search_attribs = array($this->config->expireattr, 'passwordExpirationInterval', 'loginGraceLimit');
  1213. $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
  1214. if ($sr) {
  1215. $entry = ldap_get_entries_moodle($ldapconnection, $sr);
  1216. $info = $entry[0];
  1217. $newattrs = array();
  1218. if (!empty($info[$this->config->expireattr][0])) {
  1219. // Set expiration time only if passwordExpirationInterval is defined
  1220. if (!empty($info['passwordexpirationinterval'][0])) {
  1221. $expirationtime = time() + $info['passwordexpirationinterval'][0];
  1222. $ldapexpirationtime = $this->ldap_unix2expirationtime($expirationtime);
  1223. $newattrs['passwordExpirationTime'] = $ldapexpirationtime;
  1224. }
  1225. // Set gracelogin count
  1226. if (!empty($info['logingracelimit'][0])) {
  1227. $newattrs['loginGraceRemaining']= $info['logingracelimit'][0];
  1228. }
  1229. // Store attribute changes in LDAP
  1230. $result = ldap_modify($ldapconnection, $user_dn, $newattrs);
  1231. if (!$result) {
  1232. error_log($this->errorlogtag.get_string ('updatepasserrorexpiregrace', 'auth_ldap',
  1233. array('errno'=>ldap_errno($ldapconnection),
  1234. 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
  1235. }
  1236. }
  1237. }
  1238. else {
  1239. error_log($this->errorlogtag.get_string ('updatepasserrorexpire', 'auth_ldap',
  1240. array('errno'=>ldap_errno($ldapconnection),
  1241. 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
  1242. }
  1243. break;
  1244. case 'ad':
  1245. // Passwords in Active Directory must be encoded as Unicode
  1246. // strings (UCS-2 Little Endian format) and surrounded with
  1247. // double quotes. See http://support.microsoft.com/?kbid=269190
  1248. if (!function_exists('mb_convert_encoding')) {
  1249. error_log($this->errorlogtag.get_string ('needmbstring', 'auth_ldap'));
  1250. return false;
  1251. }
  1252. $extpassword = mb_convert_encoding('"'.$extpassword.'"', "UCS-2LE", $this->config->ldapencoding);
  1253. $result = ldap_modify($ldapconnection, $user_dn, array('unicodePwd' => $extpassword));
  1254. if (!$result) {
  1255. error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
  1256. array('errno'=>ldap_errno($ldapconnection),
  1257. 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
  1258. }
  1259. break;
  1260. default:
  1261. // Send LDAP the password in cleartext, it will md5 it itself
  1262. $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
  1263. if (!$result) {
  1264. error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
  1265. array('errno'=>ldap_errno($ldapconnection),
  1266. 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
  1267. }
  1268. }
  1269. $this->ldap_close();
  1270. return $result;
  1271. }
  1272. /**
  1273. * Take expirationtime and return it as unix timestamp in seconds
  1274. *
  1275. * Takes expiration timestamp as read from LDAP and returns it as unix timestamp in seconds
  1276. * Depends on $this->config->user_type variable
  1277. *
  1278. * @param mixed time Time stamp read from LDAP as it is.
  1279. * @param string $ldapconnection Only needed for Active Directory.
  1280. * @param string $user_dn User distinguished name for the user we are checking password expiration (only needed for Active Directory).
  1281. * @return timestamp
  1282. */
  1283. function ldap_expirationtime2unix ($time, $ldapconnection, $user_dn) {
  1284. $result = false;
  1285. switch ($this->config->user_type) {
  1286. case 'edir':
  1287. $yr=substr($time, 0, 4);
  1288. $mo=substr($time, 4, 2);
  1289. $dt=substr($time, 6, 2);
  1290. $hr=substr($time, 8, 2);
  1291. $min=substr($time, 10, 2);
  1292. $sec=substr($time, 12, 2);
  1293. $result = mktime($hr, $min, $sec, $mo, $dt, $yr);
  1294. break;
  1295. case 'rfc2307':
  1296. case 'rfc2307bis':
  1297. $result = $time * DAYSECS; // The shadowExpire contains the number of DAYS between 01/01/1970 and the actual expiration date
  1298. break;
  1299. case 'ad':
  1300. $result = $this->ldap_get_ad_pwdexpire($time, $ldapconnection, $user_dn);
  1301. break;
  1302. default:
  1303. print_error('auth_ldap_usertypeundefined', 'auth_ldap');
  1304. }
  1305. return $result;
  1306. }
  1307. /**
  1308. * Takes unix timestamp and returns it formated for storing in LDAP
  1309. *
  1310. * @param integer unix time stamp
  1311. */
  1312. function ldap_unix2expirationtime($time) {
  1313. $result = false;
  1314. switch ($this->config->user_type) {
  1315. case 'edir':
  1316. $result=date('YmdHis', $time).'Z';
  1317. break;
  1318. case 'rfc2307':
  1319. case 'rfc2307bis':
  1320. $result = $time ; // Already in correct format
  1321. break;
  1322. default:
  1323. print_error('auth_ldap_usertypeundefined2', 'auth_ldap');
  1324. }
  1325. return $result;
  1326. }
  1327. /**
  1328. * Returns user attribute mappings between moodle and LDAP
  1329. *
  1330. * @return array
  1331. */
  1332. function ldap_attributes () {
  1333. $moodleattributes = array();
  1334. // If we have custom fields then merge them with user fields.
  1335. $customfields = $this->get_custom_user_profile_fields();
  1336. if (!empty($customfields) && !empty($this->userfields)) {
  1337. $userfields = array_merge($this->userfields, $customfields);
  1338. } else {
  1339. $userfields = $this->userfields;
  1340. }
  1341. foreach ($userfields as $field) {
  1342. if (!empty($this->config->{"field_map_$field"})) {
  1343. $moodleattributes[$field] = core_text::strtolower(trim($this->config->{"field_map_$field"}));
  1344. if (preg_match('/,/', $moodleattributes[$field])) {
  1345. $moodleattributes[$field] = explode(',', $moodleattributes[$field]); // split ?
  1346. }
  1347. }
  1348. }
  1349. $moodleattributes['username'] = core_text::strtolower(trim($this->config->user_attribute));
  1350. $moodleattributes['suspended'] = core_text::strtolower(trim($this->config->suspended_attribute));
  1351. return $moodleattributes;
  1352. }
  1353. /**
  1354. * Returns all usernames from LDAP
  1355. *
  1356. * @param $filter An LDAP search filter to select desired users
  1357. * @return array of LDAP user names converted to UTF-8
  1358. */
  1359. function ldap_get_userlist($filter='*') {
  1360. $fresult = array();
  1361. $ldapconnection = $this->ldap_connect();
  1362. if ($filter == '*') {
  1363. $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
  1364. }
  1365. $servercontrols = array();
  1366. $contexts = explode(';', $this->config->contexts);
  1367. if (!empty($this->config->create_context)) {
  1368. array_push($contexts, $this->config->create_context);
  1369. }
  1370. $ldap_cookie = '';
  1371. $ldap_pagedresults = ldap_paged_results_supported($this->config->ldap_version, $ldapconnection);
  1372. foreach ($contexts as $context) {
  1373. $context = trim($context);
  1374. if (empty($context)) {
  1375. continue;
  1376. }
  1377. do {
  1378. if ($ldap_pagedresults) {
  1379. // TODO: Remove the old branch of code once PHP 7.3.0 becomes required (Moodle 3.11).
  1380. if (version_compare(PHP_VERSION, '7.3.0', '<')) {
  1381. // Before 7.3, use this function that was deprecated in PHP 7.4.
  1382. ldap_control_paged_result($ldapconnection, $this->config->pagesize, true, $ldap_cookie);
  1383. } else {
  1384. // PHP 7.3 and up, use server controls.
  1385. $servercontrols = array(array(
  1386. 'oid' => LDAP_CONTROL_PAGEDRESULTS, 'value' => array(
  1387. 'size' => $this->config->pagesize, 'cookie' => $ldap_cookie)));
  1388. }
  1389. }
  1390. if ($this->config->search_sub) {
  1391. // Use ldap_search to find first user from subtree.
  1392. // TODO: Remove the old branch of code once PHP 7.3.0 becomes required (Moodle 3.11).
  1393. if (version_compare(PHP_VERSION, '7.3.0', '<')) {
  1394. $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute));
  1395. } else {
  1396. $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute),
  1397. 0, -1, -1, LDAP_DEREF_NEVER, $servercontrols);
  1398. }
  1399. } else {
  1400. // Search only in this context.
  1401. // TODO: Remove the old branch of code once PHP 7.3.0 becomes required (Moodle 3.11).
  1402. if (version_compare(PHP_VERSION, '7.3.0', '<')) {
  1403. $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute));
  1404. } else {
  1405. $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute),
  1406. 0, -1, -1, LDAP_DEREF_NEVER, $servercontrols);
  1407. }
  1408. }
  1409. if(!$ldap_result) {
  1410. continue;
  1411. }
  1412. if ($ldap_pagedresults) {
  1413. // Get next server cookie to know if we'll need to continue searching.
  1414. $ldap_cookie = '';
  1415. // TODO: Remove the old branch of code once PHP 7.3.0 becomes required (Moodle 3.11).
  1416. if (version_compare(PHP_VERSION, '7.3.0', '<')) {
  1417. // Before 7.3, use this function that was deprecated in PHP 7.4.
  1418. ldap_control_paged_result_response($ldapconnection, $ldap_result, $ldap_cookie);
  1419. } else {
  1420. // Get next cookie from controls.
  1421. ldap_parse_result($ldapconnection, $ldap_result, $errcode, $matcheddn,
  1422. $errmsg, $referrals, $controls);
  1423. if (isset($controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'])) {
  1424. $ldap_cookie = $controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'];
  1425. }
  1426. }
  1427. }
  1428. $users = ldap_get_entries_moodle($ldapconnection, $ldap_result);
  1429. // Add found users to list.
  1430. for ($i = 0; $i < count($users); $i++) {
  1431. $extuser = core_text::convert($users[$i][$this->config->user_attribute][0],
  1432. $this->config->ldapencoding, 'utf-8');
  1433. array_push($fresult, $extuser);
  1434. }
  1435. unset($ldap_result); // Free mem.
  1436. } while ($ldap_pagedresults && !empty($ldap_cookie));
  1437. }
  1438. // If paged results were used, make sure the current connection is completely closed
  1439. $this->ldap_close($ldap_pagedresults);
  1440. return $fresult;
  1441. }
  1442. /**
  1443. * Indicates if password hashes should be stored in local moodle database.
  1444. *
  1445. * @return bool true means flag 'not_cached' stored instead of password hash
  1446. */
  1447. function prevent_local_passwords() {
  1448. return !empty($this->config->preventpassindb);
  1449. }
  1450. /**
  1451. * Returns true if this authentication plugin is 'internal'.
  1452. *
  1453. * @return bool
  1454. */
  1455. function is_internal() {
  1456. return false;
  1457. }
  1458. /**
  1459. * Returns true if this authentication plugin can change the user's
  1460. * password.
  1461. *
  1462. * @return bool
  1463. */
  1464. function can_change_password() {
  1465. return !empty($this->config->stdchangepassword) or !empty($this->config->changepasswordurl);
  1466. }
  1467. /**
  1468. * Returns the URL for changing the user's password, or empty if the default can
  1469. * be used.
  1470. *
  1471. * @return moodle_url
  1472. */
  1473. function change_password_url() {
  1474. if (empty($this->config->stdchangepassword)) {
  1475. if (!empty($this->config->changepasswordurl)) {
  1476. return new moodle_url($this->config->changepasswordurl);
  1477. } else {
  1478. return null;
  1479. }
  1480. } else {
  1481. return null;
  1482. }
  1483. }
  1484. /**
  1485. * Will get called before the login page is shownr. Ff NTLM SSO
  1486. * is enabled, and the user is in the right network, we'll redirect
  1487. * to the magic NTLM page for SSO...
  1488. *
  1489. */
  1490. function loginpage_hook() {
  1491. global $CFG, $SESSION;
  1492. // HTTPS is potentially required
  1493. //httpsrequired(); - this must be used before setting the URL, it is already done on the login/index.php
  1494. if (($_SERVER['REQUEST_METHOD'] === 'GET' // Only on initial GET of loginpage
  1495. || ($_SERVER['REQUEST_METHOD'] === 'POST'
  1496. && (get_local_referer() != strip_querystring(qualified_me()))))
  1497. // Or when POSTed from another place
  1498. // See MDL-14071
  1499. && !empty($this->config->ntlmsso_enabled) // SSO enabled
  1500. && !empty($this->config->ntlmsso_subnet) // have a subnet to test for
  1501. && empty($_GET['authldap_skipntlmsso']) // haven't failed it yet
  1502. && (isguestuser() || !isloggedin()) // guestuser or not-logged-in users
  1503. && address_in_subnet(getremoteaddr(), $this->config->ntlmsso_subnet)) {
  1504. // First, let's remember where we were trying to get to before we got here
  1505. if (empty($SESSION->wantsurl)) {
  1506. $SESSION->wantsurl = null;
  1507. $referer = get_local_referer(false);
  1508. if ($referer &&
  1509. $referer != $CFG->wwwroot &&
  1510. $referer != $CFG->wwwroot . '/' &&
  1511. $referer != $CFG->wwwroot . '/login/' &&
  1512. $referer != $CFG->wwwroot . '/login/index.php') {
  1513. $SESSION->wantsurl = $referer;
  1514. }
  1515. }
  1516. // Now start the whole NTLM machinery.
  1517. if($this->config->ntlmsso_ie_fastpath == AUTH_NTLM_FASTPATH_YESATTEMPT ||
  1518. $this->config->ntlmsso_ie_fastpath == AUTH_NTLM_FASTPATH_YESFORM) {
  1519. if (core_useragent::is_ie()) {
  1520. $sesskey = sesskey();
  1521. redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_magic.php?sesskey='.$sesskey);
  1522. } else if ($this->config->ntlmsso_ie_fastpath == AUTH_NTLM_FASTPATH_YESFORM) {
  1523. redirect($CFG->wwwroot.'/login/index.php?authldap_skipntlmsso=1');
  1524. }
  1525. }
  1526. redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_attempt.php');
  1527. }
  1528. // No NTLM SSO, Use the normal login page instead.
  1529. // If $SESSION->wantsurl is empty and we have a 'Referer:' header, the login
  1530. // page insists on redirecting us to that page after user validation. If
  1531. // we clicked on the redirect link at the ntlmsso_finish.php page (instead
  1532. // of waiting for the redirection to happen) then we have a 'Referer:' header
  1533. // we don't want to use at all. As we can't get rid of it, just point
  1534. // $SESSION->wantsurl to $CFG->wwwroot (after all, we came from there).
  1535. if (empty($SESSION->wantsurl)
  1536. && (get_local_referer() == $CFG->wwwroot.'/auth/ldap/ntlmsso_finish.php')) {
  1537. $SESSION->wantsurl = $CFG->wwwroot;
  1538. }
  1539. }
  1540. /**
  1541. * To be called from a page running under NTLM's
  1542. * "Integrated Windows Authentication".
  1543. *
  1544. * If successful, it will set a special "cookie" (not an HTTP cookie!)
  1545. * in cache_flags under the $this->pluginconfig/ntlmsess "plugin" and return true.
  1546. * The "cookie" will be picked up by ntlmsso_finish() to complete the
  1547. * process.
  1548. *
  1549. * On failure it will return false for the caller to display an appropriate
  1550. * error message (probably saying that Integrated Windows Auth isn't enabled!)
  1551. *
  1552. * NOTE that this code will execute under the OS user credentials,
  1553. * so we MUST avoid dealing with files -- such as session files.
  1554. * (The caller should define('NO_MOODLE_COOKIES', true) before including config.php)
  1555. *
  1556. */
  1557. function ntlmsso_magic($sesskey) {
  1558. if (isset($_SERVER['REMOTE_USER']) && !empty($_SERVER['REMOTE_USER'])) {
  1559. // HTTP __headers__ seem to be sent in ISO-8859-1 encoding
  1560. // (according to my reading of RFC-1945, RFC-2616 and RFC-2617 and
  1561. // my local tests), so we need to convert the REMOTE_USER value
  1562. // (i.e., what we got from the HTTP WWW-Authenticate header) into UTF-8
  1563. $username = core_text::convert($_SERVER['REMOTE_USER'], 'iso-8859-1', 'utf-8');
  1564. switch ($this->config->ntlmsso_type) {
  1565. case 'ntlm':
  1566. // The format is now configurable, so try to extract the username
  1567. $username = $this->get_ntlm_remote_user($username);
  1568. if (empty($username)) {
  1569. return false;
  1570. }
  1571. break;
  1572. case 'kerberos':
  1573. // Format is username@DOMAIN
  1574. $username = substr($username, 0, strpos($username, '@'));
  1575. break;
  1576. default:
  1577. error_log($this->errorlogtag.get_string ('ntlmsso_unknowntype', 'auth_ldap'));
  1578. return false; // Should never happen!
  1579. }
  1580. $username = core_text::strtolower($username); // Compatibility hack
  1581. set_cache_flag($this->pluginconfig.'/ntlmsess', $sesskey, $username, AUTH_NTLMTIMEOUT);
  1582. return true;
  1583. }
  1584. return false;
  1585. }
  1586. /**
  1587. * Find the session set by ntlmsso_magic(), validate it and
  1588. * call authenticate_user_login() to authenticate the user through
  1589. * the auth machinery.
  1590. *
  1591. * It is complemented by a similar check in user_login().
  1592. *
  1593. * If it succeeds, it never returns.
  1594. *
  1595. */
  1596. function ntlmsso_finish() {
  1597. global $CFG, $USER, $SESSION;
  1598. $key = sesskey();
  1599. $username = get_cache_flag($this->pluginconfig.'/ntlmsess', $key);
  1600. if (empty($username)) {
  1601. return false;
  1602. }
  1603. // Here we want to trigger the whole authentication machinery
  1604. // to make sure no step is bypassed...
  1605. $reason = null;
  1606. $user = authenticate_user_login($username, $key, false, $reason, false);
  1607. if ($user) {
  1608. complete_user_login($user);
  1609. // Cleanup the key to prevent reuse...
  1610. // and to allow re-logins with normal credentials
  1611. unset_cache_flag($this->pluginconfig.'/ntlmsess', $key);
  1612. // Redirection
  1613. if (user_not_fully_set_up($USER, true)) {
  1614. $urltogo = $CFG->wwwroot.'/user/edit.php';
  1615. // We don't delete $SESSION->wantsurl yet, so we get there later
  1616. } else if (isset($SESSION->wantsurl) and (strpos($SESSION->wantsurl, $CFG->wwwroot) === 0)) {
  1617. $urltogo = $SESSION->wantsurl; // Because it's an address in this site
  1618. unset($SESSION->wantsurl);
  1619. } else {
  1620. // No wantsurl stored or external - go to homepage
  1621. $urltogo = $CFG->wwwroot.'/';
  1622. unset($SESSION->wantsurl);
  1623. }
  1624. // We do not want to redirect if we are in a PHPUnit test.
  1625. if (!PHPUNIT_TEST) {
  1626. redirect($urltogo);
  1627. }
  1628. }
  1629. // Should never reach here.
  1630. return false;
  1631. }
  1632. /**
  1633. * Sync roles for this user.
  1634. *
  1635. * @param object $user The user to sync (without system magic quotes).
  1636. */
  1637. function sync_roles($user) {
  1638. global $DB;
  1639. $roles = get_ldap_assignable_role_names(2); // Admin user.
  1640. foreach ($roles as $role) {
  1641. $isrole = $this->is_role($user->username, $role);
  1642. if ($isrole === null) {
  1643. continue; // Nothing to sync - role/LDAP contexts not configured.
  1644. }
  1645. // Sync user.
  1646. $systemcontext = context_system::instance();
  1647. if ($isrole) {
  1648. // Following calls will not create duplicates.
  1649. role_assign($role['id'], $user->id, $systemcontext->id, $this->roleauth);
  1650. } else {
  1651. // Unassign only if previously assigned by this plugin.
  1652. role_unassign($role['id'], $user->id, $systemcontext->id, $this->roleauth);
  1653. }
  1654. }
  1655. }
  1656. /**
  1657. * Get password expiration time for a given user from Active Directory
  1658. *
  1659. * @param string $pwdlastset The time last time we changed the password.
  1660. * @param resource $lcapconn The open LDAP connection.
  1661. * @param string $user_dn The distinguished name of the user we are checking.
  1662. *
  1663. * @return string $unixtime
  1664. */
  1665. function ldap_get_ad_pwdexpire($pwdlastset, $ldapconn, $user_dn){
  1666. global $CFG;
  1667. if (!function_exists('bcsub')) {
  1668. error_log($this->errorlogtag.get_string ('needbcmath', 'auth_ldap'));
  1669. return 0;
  1670. }
  1671. // If UF_DONT_EXPIRE_PASSWD flag is set in user's
  1672. // userAccountControl attribute, the password doesn't expire.
  1673. $sr = ldap_read($ldapconn, $user_dn, '(objectClass=*)',
  1674. array('userAccountControl'));
  1675. if (!$sr) {
  1676. error_log($this->errorlogtag.get_string ('useracctctrlerror', 'auth_ldap', $user_dn));
  1677. // Don't expire password, as we are not sure if it has to be
  1678. // expired or not.
  1679. return 0;
  1680. }
  1681. $entry = ldap_get_entries_moodle($ldapconn, $sr);
  1682. $info = $entry[0];
  1683. $useraccountcontrol = $info['useraccountcontrol'][0];
  1684. if ($useraccountcontrol & UF_DONT_EXPIRE_PASSWD) {
  1685. // Password doesn't expire.
  1686. return 0;
  1687. }
  1688. // If pwdLastSet is zero, the user must change his/her password now
  1689. // (unless UF_DONT_EXPIRE_PASSWD flag is set, but we already
  1690. // tested this above)
  1691. if ($pwdlastset === '0') {
  1692. // Password has expired
  1693. return -1;
  1694. }
  1695. // ----------------------------------------------------------------
  1696. // Password expiration time in Active Directory is the composition of
  1697. // two values:
  1698. //
  1699. // - User's pwdLastSet attribute, that stores the last time
  1700. // the password was changed.
  1701. //
  1702. // - Domain's maxPwdAge attribute, that sets how long
  1703. // passwords last in this domain.
  1704. //
  1705. // We already have the first value (passed in as a parameter). We
  1706. // need to get the second one. As we don't know the domain DN, we
  1707. // have to query rootDSE's defaultNamingContext attribute to get
  1708. // it. Then we have to query that DN's maxPwdAge attribute to get
  1709. // the real value.
  1710. //
  1711. // Once we have both values, we just need to combine them. But MS
  1712. // chose to use a different base and unit for time measurements.
  1713. // So we need to convert the values to Unix timestamps (see
  1714. // details below).
  1715. // ----------------------------------------------------------------
  1716. $sr = ldap_read($ldapconn, ROOTDSE, '(objectClass=*)',
  1717. array('defaultNamingContext'));
  1718. if (!$sr) {
  1719. error_log($this->errorlogtag.get_string ('rootdseerror', 'auth_ldap'));
  1720. return 0;
  1721. }
  1722. $entry = ldap_get_entries_moodle($ldapconn, $sr);
  1723. $info = $entry[0];
  1724. $domaindn = $info['defaultnamingcontext'][0];
  1725. $sr = ldap_read ($ldapconn, $domaindn, '(objectClass=*)',
  1726. array('maxPwdAge'));
  1727. $entry = ldap_get_entries_moodle($ldapconn, $sr);
  1728. $info = $entry[0];
  1729. $maxpwdage = $info['maxpwdage'][0];
  1730. if ($sr = ldap_read($ldapconn, $user_dn, '(objectClass=*)', array('msDS-ResultantPSO'))) {
  1731. if ($entry = ldap_get_entries_moodle($ldapconn, $sr)) {
  1732. $info = $entry[0];
  1733. $userpso = $info['msds-resultantpso'][0];
  1734. // If a PSO exists, FGPP is being utilized.
  1735. // Grab the new maxpwdage from the msDS-MaximumPasswordAge attribute of the PSO.
  1736. if (!empty($userpso)) {
  1737. $sr = ldap_read($ldapconn, $userpso, '(objectClass=*)', array('msDS-MaximumPasswordAge'));
  1738. if ($entry = ldap_get_entries_moodle($ldapconn, $sr)) {
  1739. $info = $entry[0];
  1740. // Default value of msds-maximumpasswordage is 42 and is always set.
  1741. $maxpwdage = $info['msds-maximumpasswordage'][0];
  1742. }
  1743. }
  1744. }
  1745. }
  1746. // ----------------------------------------------------------------
  1747. // MSDN says that "pwdLastSet contains the number of 100 nanosecond
  1748. // intervals since January 1, 1601 (UTC), stored in a 64 bit integer".
  1749. //
  1750. // According to Perl's Date::Manip, the number of seconds between
  1751. // this date and Unix epoch is 11644473600. So we have to
  1752. // substract this value to calculate a Unix time, once we have
  1753. // scaled pwdLastSet to seconds. This is the script used to
  1754. // calculate the value shown above:
  1755. //
  1756. // #!/usr/bin/perl -w
  1757. //
  1758. // use Date::Manip;
  1759. //
  1760. // $date1 = ParseDate ("160101010000 UTC");
  1761. // $date2 = ParseDate ("197001010000 UTC");
  1762. // $delta = DateCalc($date1, $date2, \$err);
  1763. // $secs = Delta_Format($delta, 0, "%st");
  1764. // print "$secs \n";
  1765. //
  1766. // MSDN also says that "maxPwdAge is stored as a large integer that
  1767. // represents the number of 100 nanosecond intervals from the time
  1768. // the password was set before the password expires." We also need
  1769. // to scale this to seconds. Bear in mind that this value is stored
  1770. // as a _negative_ quantity (at least in my AD domain).
  1771. //
  1772. // As a last remark, if the low 32 bits of maxPwdAge are equal to 0,
  1773. // the maximum password age in the domain is set to 0, which means
  1774. // passwords do not expire (see
  1775. // http://msdn2.microsoft.com/en-us/library/ms974598.aspx)
  1776. //
  1777. // As the quantities involved are too big for PHP integers, we
  1778. // need to use BCMath functions to work with arbitrary precision
  1779. // numbers.
  1780. // ----------------------------------------------------------------
  1781. // If the low order 32 bits are 0, then passwords do not expire in
  1782. // the domain. Just do '$maxpwdage mod 2^32' and check the result
  1783. // (2^32 = 4294967296)
  1784. if (bcmod ($maxpwdage, 4294967296) === '0') {
  1785. return 0;
  1786. }
  1787. // Add up pwdLastSet and maxPwdAge to get password expiration
  1788. // time, in MS time units. Remember maxPwdAge is stored as a
  1789. // _negative_ quantity, so we need to substract it in fact.
  1790. $pwdexpire = bcsub ($pwdlastset, $maxpwdage);
  1791. // Scale the result to convert it to Unix time units and return
  1792. // that value.
  1793. return bcsub( bcdiv($pwdexpire, '10000000'), '11644473600');
  1794. }
  1795. /**
  1796. * Connect to the LDAP server, using the plugin configured
  1797. * settings. It's actually a wrapper around ldap_connect_moodle()
  1798. *
  1799. * @return resource A valid LDAP connection (or dies if it can't connect)
  1800. */
  1801. function ldap_connect() {
  1802. // Cache ldap connections. They are expensive to set up
  1803. // and can drain the TCP/IP ressources on the server if we
  1804. // are syncing a lot of users (as we try to open a new connection
  1805. // to get the user details). This is the least invasive way
  1806. // to reuse existing connections without greater code surgery.
  1807. if(!empty($this->ldapconnection)) {
  1808. $this->ldapconns++;
  1809. return $this->ldapconnection;
  1810. }
  1811. if($ldapconnection = ldap_connect_moodle($this->config->host_url, $this->config->ldap_version,
  1812. $this->config->user_type, $this->config->bind_dn,
  1813. $this->config->bind_pw, $this->config->opt_deref,
  1814. $debuginfo, $this->config->start_tls)) {
  1815. $this->ldapconns = 1;
  1816. $this->ldapconnection = $ldapconnection;
  1817. return $ldapconnection;
  1818. }
  1819. print_error('auth_ldap_noconnect_all', 'auth_ldap', '', $debuginfo);
  1820. }
  1821. /**
  1822. * Disconnects from a LDAP server
  1823. *
  1824. * @param force boolean Forces closing the real connection to the LDAP server, ignoring any
  1825. * cached connections. This is needed when we've used paged results
  1826. * and want to use normal results again.
  1827. */
  1828. function ldap_close($force=false) {
  1829. $this->ldapconns--;
  1830. if (($this->ldapconns == 0) || ($force)) {
  1831. $this->ldapconns = 0;
  1832. @ldap_close($this->ldapconnection);
  1833. unset($this->ldapconnection);
  1834. }
  1835. }
  1836. /**
  1837. * Search specified contexts for username and return the user dn
  1838. * like: cn=username,ou=suborg,o=org. It's actually a wrapper
  1839. * around ldap_find_userdn().
  1840. *
  1841. * @param resource $ldapconnection a valid LDAP connection
  1842. * @param string $extusername the username to search (in external LDAP encoding, no db slashes)
  1843. * @return mixed the user dn (external LDAP encoding) or false
  1844. */
  1845. function ldap_find_userdn($ldapconnection, $extusername) {
  1846. $ldap_contexts = explode(';', $this->config->contexts);
  1847. if (!empty($this->config->create_context)) {
  1848. array_push($ldap_contexts, $this->config->create_context);
  1849. }
  1850. return ldap_find_userdn($ldapconnection, $extusername, $ldap_contexts, $this->config->objectclass,
  1851. $this->config->user_attribute, $this->config->search_sub);
  1852. }
  1853. /**
  1854. * When using NTLM SSO, the format of the remote username we get in
  1855. * $_SERVER['REMOTE_USER'] may vary, depending on where from and how the web
  1856. * server gets the data. So we let the admin configure the format using two
  1857. * place holders (%domain% and %username%). This function tries to extract
  1858. * the username (stripping the domain part and any separators if they are
  1859. * present) from the value present in $_SERVER['REMOTE_USER'], using the
  1860. * configured format.
  1861. *
  1862. * @param string $remoteuser The value from $_SERVER['REMOTE_USER'] (converted to UTF-8)
  1863. *
  1864. * @return string The remote username (without domain part or
  1865. * separators). Empty string if we can't extract the username.
  1866. */
  1867. protected function get_ntlm_remote_user($remoteuser) {
  1868. if (empty($this->config->ntlmsso_remoteuserformat)) {
  1869. $format = AUTH_NTLM_DEFAULT_FORMAT;
  1870. } else {
  1871. $format = $this->config->ntlmsso_remoteuserformat;
  1872. }
  1873. $format = preg_quote($format);
  1874. $formatregex = preg_replace(array('#%domain%#', '#%username%#'),
  1875. array('('.AUTH_NTLM_VALID_DOMAINNAME.')', '('.AUTH_NTLM_VALID_USERNAME.')'),
  1876. $format);
  1877. if (preg_match('#^'.$formatregex.'$#', $remoteuser, $matches)) {
  1878. $user = end($matches);
  1879. return $user;
  1880. }
  1881. /* We are unable to extract the username with the configured format. Probably
  1882. * the format specified is wrong, so log a warning for the admin and return
  1883. * an empty username.
  1884. */
  1885. error_log($this->errorlogtag.get_string ('auth_ntlmsso_maybeinvalidformat', 'auth_ldap'));
  1886. return '';
  1887. }
  1888. /**
  1889. * Check if the diagnostic message for the LDAP login error tells us that the
  1890. * login is denied because the user password has expired or the password needs
  1891. * to be changed on first login (using interactive SMB/Windows logins, not
  1892. * LDAP logins).
  1893. *
  1894. * @param string the diagnostic message for the LDAP login error
  1895. * @return bool true if the password has expired or the password must be changed on first login
  1896. */
  1897. protected function ldap_ad_pwdexpired_from_diagmsg($diagmsg) {
  1898. // The format of the diagnostic message is (actual examples from W2003 and W2008):
  1899. // "80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece" (W2003)
  1900. // "80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 773, vece" (W2003)
  1901. // "80090308: LdapErr: DSID-0C0903AA, comment: AcceptSecurityContext error, data 52e, v1771" (W2008)
  1902. // "80090308: LdapErr: DSID-0C0903AA, comment: AcceptSecurityContext error, data 773, v1771" (W2008)
  1903. // We are interested in the 'data nnn' part.
  1904. // if nnn == 773 then user must change password on first login
  1905. // if nnn == 532 then user password has expired
  1906. $diagmsg = explode(',', $diagmsg);
  1907. if (preg_match('/data (773|532)/i', trim($diagmsg[2]))) {
  1908. return true;
  1909. }
  1910. return false;
  1911. }
  1912. /**
  1913. * Check if a user is suspended. This function is intended to be used after calling
  1914. * get_userinfo_asobj. This is needed because LDAP doesn't have a notion of disabled
  1915. * users, however things like MS Active Directory support it and expose information
  1916. * through a field.
  1917. *
  1918. * @param object $user the user object returned by get_userinfo_asobj
  1919. * @return boolean
  1920. */
  1921. protected function is_user_suspended($user) {
  1922. if (!$this->config->suspended_attribute || !isset($user->suspended)) {
  1923. return false;
  1924. }
  1925. if ($this->config->suspended_attribute == 'useraccountcontrol' && $this->config->user_type == 'ad') {
  1926. return (bool)($user->suspended & AUTH_AD_ACCOUNTDISABLE);
  1927. }
  1928. return (bool)$user->suspended;
  1929. }
  1930. /**
  1931. * Test a DN
  1932. *
  1933. * @param resource $ldapconn
  1934. * @param string $dn The DN to check for existence
  1935. * @param string $message The identifier of a string as in get_string()
  1936. * @param string|object|array $a An object, string or number that can be used
  1937. * within translation strings as in get_string()
  1938. * @return true or a message in case of error
  1939. */
  1940. private function test_dn($ldapconn, $dn, $message, $a = null) {
  1941. $ldapresult = @ldap_read($ldapconn, $dn, '(objectClass=*)', array());
  1942. if (!$ldapresult) {
  1943. if (ldap_errno($ldapconn) == 32) {
  1944. // No such object.
  1945. return get_string($message, 'auth_ldap', $a);
  1946. }
  1947. $a = array('code' => ldap_errno($ldapconn), 'subject' => $a, 'message' => ldap_error($ldapconn));
  1948. return get_string('diag_genericerror', 'auth_ldap', $a);
  1949. }
  1950. return true;
  1951. }
  1952. /**
  1953. * Test if settings are correct, print info to output.
  1954. */
  1955. public function test_settings() {
  1956. global $OUTPUT;
  1957. if (!function_exists('ldap_connect')) { // Is php-ldap really there?
  1958. echo $OUTPUT->notification(get_string('auth_ldap_noextension', 'auth_ldap'), \core\output\notification::NOTIFY_ERROR);
  1959. return;
  1960. }
  1961. // Check to see if this is actually configured.
  1962. if (empty($this->config->host_url)) {
  1963. // LDAP is not even configured.
  1964. echo $OUTPUT->notification(get_string('ldapnotconfigured', 'auth_ldap'), \core\output\notification::NOTIFY_ERROR);
  1965. return;
  1966. }
  1967. if ($this->config->ldap_version != 3) {
  1968. echo $OUTPUT->notification(get_string('diag_toooldversion', 'auth_ldap'), \core\output\notification::NOTIFY_WARNING);
  1969. }
  1970. try {
  1971. $ldapconn = $this->ldap_connect();
  1972. } catch (Exception $e) {
  1973. echo $OUTPUT->notification($e->getMessage(), \core\output\notification::NOTIFY_ERROR);
  1974. return;
  1975. }
  1976. // Display paged file results.
  1977. if (!ldap_paged_results_supported($this->config->ldap_version, $ldapconn)) {
  1978. echo $OUTPUT->notification(get_string('pagedresultsnotsupp', 'auth_ldap'), \core\output\notification::NOTIFY_INFO);
  1979. }
  1980. // Check contexts.
  1981. foreach (explode(';', $this->config->contexts) as $context) {
  1982. $context = trim($context);
  1983. if (empty($context)) {
  1984. echo $OUTPUT->notification(get_string('diag_emptycontext', 'auth_ldap'), \core\output\notification::NOTIFY_WARNING);
  1985. continue;
  1986. }
  1987. $message = $this->test_dn($ldapconn, $context, 'diag_contextnotfound', $context);
  1988. if ($message !== true) {
  1989. echo $OUTPUT->notification($message, \core\output\notification::NOTIFY_WARNING);
  1990. }
  1991. }
  1992. // Create system role mapping field for each assignable system role.
  1993. $roles = get_ldap_assignable_role_names();
  1994. foreach ($roles as $role) {
  1995. foreach (explode(';', $this->config->{$role['settingname']}) as $groupdn) {
  1996. if (empty($groupdn)) {
  1997. continue;
  1998. }
  1999. $role['group'] = $groupdn;
  2000. $message = $this->test_dn($ldapconn, $groupdn, 'diag_rolegroupnotfound', $role);
  2001. if ($message !== true) {
  2002. echo $OUTPUT->notification($message, \core\output\notification::NOTIFY_WARNING);
  2003. }
  2004. }
  2005. }
  2006. $this->ldap_close(true);
  2007. // We were able to connect successfuly.
  2008. echo $OUTPUT->notification(get_string('connectingldapsuccess', 'auth_ldap'), \core\output\notification::NOTIFY_SUCCESS);
  2009. }
  2010. /**
  2011. * Get the list of profile fields.
  2012. *
  2013. * @param bool $fetchall Fetch all, not just those for update.
  2014. * @return array
  2015. */
  2016. protected function get_profile_keys($fetchall = false) {
  2017. $keys = array_keys(get_object_vars($this->config));
  2018. $updatekeys = [];
  2019. foreach ($keys as $key) {
  2020. if (preg_match('/^field_updatelocal_(.+)$/', $key, $match)) {
  2021. // If we have a field to update it from and it must be updated 'onlogin' we update it on cron.
  2022. if (!empty($this->config->{'field_map_'.$match[1]})) {
  2023. if ($fetchall || $this->config->{$match[0]} === 'onlogin') {
  2024. array_push($updatekeys, $match[1]); // the actual key name
  2025. }
  2026. }
  2027. }
  2028. }
  2029. if ($this->config->suspended_attribute && $this->config->sync_suspended) {
  2030. $updatekeys[] = 'suspended';
  2031. }
  2032. return $updatekeys;
  2033. }
  2034. }