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

/auth/ldap/auth.php

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