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