PageRenderTime 28ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/auth/ldap/auth.php

http://github.com/moodle/moodle
PHP | 2282 lines | 1372 code | 257 blank | 653 comment | 307 complexity | 3a42e7be2a7e0b55cf1d4f5293cb9f3c MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  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 4.1).
  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 4.1).
  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 4.1).
  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 4.1).
  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. $transaction = $DB->start_delegated_transaction();
  821. foreach ($add_users as $user) {
  822. $user = $this->get_userinfo_asobj($user->username);
  823. // Prep a few params
  824. $user->modified = time();
  825. $user->confirmed = 1;
  826. $user->auth = $this->authtype;
  827. $user->mnethostid = $CFG->mnet_localhost_id;
  828. // get_userinfo_asobj() might have replaced $user->username with the value
  829. // from the LDAP server (which can be mixed-case). Make sure it's lowercase
  830. $user->username = trim(core_text::strtolower($user->username));
  831. // It isn't possible to just rely on the configured suspension attribute since
  832. // things like active directory use bit masks, other things using LDAP might
  833. // do different stuff as well.
  834. //
  835. // The cast to int is a workaround for MDL-53959.
  836. $user->suspended = (int)$this->is_user_suspended($user);
  837. if (empty($user->lang)) {
  838. $user->lang = $CFG->lang;
  839. }
  840. if (empty($user->calendartype)) {
  841. $user->calendartype = $CFG->calendartype;
  842. }
  843. $id = user_create_user($user, false);
  844. echo "\t"; print_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username, 'id'=>$id)); echo "\n";
  845. $euser = $DB->get_record('user', array('id' => $id));
  846. if (!empty($this->config->forcechangepassword)) {
  847. set_user_preference('auth_forcepasswordchange', 1, $id);
  848. }
  849. // Save custom profile fields.
  850. $this->update_user_record($user->username, $this->get_profile_keys(true), false);
  851. // Add roles if needed.
  852. $this->sync_roles($euser);
  853. }
  854. $transaction->allow_commit();
  855. unset($add_users); // free mem
  856. } else {
  857. print_string('nouserstobeadded', 'auth_ldap');
  858. }
  859. $dbman->drop_table($table);
  860. $this->ldap_close();
  861. return true;
  862. }
  863. /**
  864. * Bulk insert in SQL's temp table
  865. */
  866. function ldap_bulk_insert($username) {
  867. global $DB, $CFG;
  868. $username = core_text::strtolower($username); // usernames are __always__ lowercase.
  869. $DB->insert_record_raw('tmp_extuser', array('username'=>$username,
  870. 'mnethostid'=>$CFG->mnet_localhost_id), false, true);
  871. echo '.';
  872. }
  873. /**
  874. * Activates (enables) user in external LDAP so user can login
  875. *
  876. * @param mixed $username
  877. * @return boolean result
  878. */
  879. function user_activate($username) {
  880. $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
  881. $ldapconnection = $this->ldap_connect();
  882. $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
  883. switch ($this->config->user_type) {
  884. case 'edir':
  885. $newinfo['loginDisabled'] = 'FALSE';
  886. break;
  887. case 'rfc2307':
  888. case 'rfc2307bis':
  889. // Remember that we add a '*' character in front of the
  890. // external password string to 'disable' the account. We just
  891. // need to remove it.
  892. $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
  893. array('userPassword'));
  894. $info = ldap_get_entries($ldapconnection, $sr);
  895. $info[0] = array_change_key_case($info[0], CASE_LOWER);
  896. $newinfo['userPassword'] = ltrim($info[0]['userpassword'][0], '*');
  897. break;
  898. case 'ad':
  899. // We need to unset the ACCOUNTDISABLE bit in the
  900. // userAccountControl attribute ( see
  901. // http://support.microsoft.com/kb/305144 )
  902. $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
  903. array('userAccountControl'));
  904. $info = ldap_get_entries($ldapconnection, $sr);
  905. $info[0] = array_change_key_case($info[0], CASE_LOWER);
  906. $newinfo['userAccountControl'] = $info[0]['useraccountcontrol'][0]
  907. & (~AUTH_AD_ACCOUNTDISABLE);
  908. break;
  909. default:
  910. print_error('user_activatenotsupportusertype', 'auth_ldap', '', $this->config->user_type_name);
  911. }
  912. $result = ldap_modify($ldapconnection, $userdn, $newinfo);
  913. $this->ldap_close();
  914. return $result;
  915. }
  916. /**
  917. * Returns true if user should be coursecreator.
  918. *
  919. * @param mixed $username username (without system magic quotes)
  920. * @return mixed result null if course creators is not configured, boolean otherwise.
  921. *
  922. * @deprecated since Moodle 3.4 MDL-30634 - please do not use this function any more.
  923. */
  924. function iscreator($username) {
  925. debugging('iscreator() is deprecated. Please use auth_plugin_ldap::is_role() instead.', DEBUG_DEVELOPER);
  926. if (empty($this->config->creators) or empty($this->config->memberattribute)) {
  927. return null;
  928. }
  929. $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
  930. $ldapconnection = $this->ldap_connect();
  931. if ($this->config->memberattribute_isdn) {
  932. if(!($userid = $this->ldap_find_userdn($ldapconnection, $extusername))) {
  933. return false;
  934. }
  935. } else {
  936. $userid = $extusername;
  937. }
  938. $group_dns = explode(';', $this->config->creators);
  939. $creator = ldap_isgroupmember($ldapconnection, $userid, $group_dns, $this->config->memberattribute);
  940. $this->ldap_close();
  941. return $creator;
  942. }
  943. /**
  944. * Check if user has LDAP group membership.
  945. *
  946. * Returns true if user should be assigned role.
  947. *
  948. * @param mixed $username username (without system magic quotes).
  949. * @param array $role Array of role's shortname, localname, and settingname for the config value.
  950. * @return mixed result null if role/LDAP context is not configured, boolean otherwise.
  951. */
  952. private function is_role($username, $role) {
  953. if (empty($this->config->{$role['settingname']}) or empty($this->config->memberattribute)) {
  954. return null;
  955. }
  956. $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
  957. $ldapconnection = $this->ldap_connect();
  958. if ($this->config->memberattribute_isdn) {
  959. if (!($userid = $this->ldap_find_userdn($ldapconnection, $extusername))) {
  960. return false;
  961. }
  962. } else {
  963. $userid = $extusername;
  964. }
  965. $groupdns = explode(';', $this->config->{$role['settingname']});
  966. $isrole = ldap_isgroupmember($ldapconnection, $userid, $groupdns, $this->config->memberattribute);
  967. $this->ldap_close();
  968. return $isrole;
  969. }
  970. /**
  971. * Called when the user record is updated.
  972. *
  973. * Modifies user in external LDAP server. It takes olduser (before
  974. * changes) and newuser (after changes) compares information and
  975. * saves modified information to external LDAP server.
  976. *
  977. * @param mixed $olduser Userobject before modifications (without system magic quotes)
  978. * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
  979. * @return boolean result
  980. *
  981. */
  982. function user_update($olduser, $newuser) {
  983. global $CFG;
  984. require_once($CFG->dirroot . '/user/profile/lib.php');
  985. if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
  986. error_log($this->errorlogtag.get_string('renamingnotallowed', 'auth_ldap'));
  987. return false;
  988. }
  989. if (isset($olduser->auth) and $olduser->auth != $this->authtype) {
  990. return true; // just change auth and skip update
  991. }
  992. $attrmap = $this->ldap_attributes();
  993. // Before doing anything else, make sure we really need to update anything
  994. // in the external LDAP server.
  995. $update_external = false;
  996. foreach ($attrmap as $key => $ldapkeys) {
  997. if (!empty($this->config->{'field_updateremote_'.$key})) {
  998. $update_external = true;
  999. break;
  1000. }
  1001. }
  1002. if (!$update_external) {
  1003. return true;
  1004. }
  1005. $extoldusername = core_text::convert($olduser->username, 'utf-8', $this->config->ldapencoding);
  1006. $ldapconnection = $this->ldap_connect();
  1007. $search_attribs = array();
  1008. foreach ($attrmap as $key => $values) {
  1009. if (!is_array($values)) {
  1010. $values = array($values);
  1011. }
  1012. foreach ($values as $value) {
  1013. if (!in_array($value, $search_attribs)) {
  1014. array_push($search_attribs, $value);
  1015. }
  1016. }
  1017. }
  1018. if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extoldusername))) {
  1019. return false;
  1020. }
  1021. // Load old custom fields.
  1022. $olduserprofilefields = (array) profile_user_record($olduser->id, false);
  1023. $fields = array();
  1024. foreach (profile_get_custom_fields(false) as $field) {
  1025. $fields[$field->shortname] = $field;
  1026. }
  1027. $success = true;
  1028. $user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
  1029. if ($user_info_result) {
  1030. $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
  1031. if (empty($user_entry)) {
  1032. $attribs = join (', ', $search_attribs);
  1033. error_log($this->errorlogtag.get_string('updateusernotfound', 'auth_ldap',
  1034. array('userdn'=>$user_dn,
  1035. 'attribs'=>$attribs)));
  1036. return false; // old user not found!
  1037. } else if (count($user_entry) > 1) {
  1038. error_log($this->errorlogtag.get_string('morethanoneuser', 'auth_ldap'));
  1039. return false;
  1040. }
  1041. $user_entry = $user_entry[0];
  1042. foreach ($attrmap as $key => $ldapkeys) {
  1043. if (preg_match('/^profile_field_(.*)$/', $key, $match)) {
  1044. // Custom field.
  1045. $fieldname = $match[1];
  1046. if (isset($fields[$fieldname])) {
  1047. $class = 'profile_field_' . $fields[$fieldname]->datatype;
  1048. $formfield = new $class($fields[$fieldname]->id, $olduser->id);
  1049. $oldvalue = isset($olduserprofilefields[$fieldname]) ? $olduserprofilefields[$fieldname] : null;
  1050. } else {
  1051. $oldvalue = null;
  1052. }
  1053. $newvalue = $

Large files files are truncated, but you can click here to view the full file