PageRenderTime 35ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/auth/ldap/auth.php

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