PageRenderTime 32ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/moodle/auth/ldap/auth.php

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