MDL-55707 grades: Stop infinite loop when regrading.
[moodle.git] / lib / ldaplib.php
blobec18f6f23a7cee8e51c7a67df898ddb71ebb2260
1 <?php
3 /**
4 * ldaplib.php - LDAP functions & data library
6 * Library file of miscellaneous general-purpose LDAP functions and
7 * data structures, useful for both ldap authentication (or ldap based
8 * authentication like CAS) and enrolment plugins.
10 * @author Iñaki Arenaza
11 * @package core
12 * @subpackage lib
13 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
14 * @copyright 2010 onwards Iñaki Arenaza
15 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
18 defined('MOODLE_INTERNAL') || die();
20 // rootDSE is defined as the root of the directory data tree on a directory server.
21 if (!defined('ROOTDSE')) {
22 define ('ROOTDSE', '');
25 // Default page size when using LDAP paged results
26 if (!defined('LDAP_DEFAULT_PAGESIZE')) {
27 define('LDAP_DEFAULT_PAGESIZE', 250);
30 /**
31 * Returns predefined user types
33 * @return array of predefined user types
35 function ldap_supported_usertypes() {
36 $types = array();
37 $types['edir'] = 'Novell Edirectory';
38 $types['rfc2307'] = 'posixAccount (rfc2307)';
39 $types['rfc2307bis'] = 'posixAccount (rfc2307bis)';
40 $types['samba'] = 'sambaSamAccount (v.3.0.7)';
41 $types['ad'] = 'MS ActiveDirectory';
42 $types['default'] = get_string('default');
43 return $types;
46 /**
47 * Initializes needed variables for ldap-module
49 * Uses names defined in ldap_supported_usertypes.
50 * $default is first defined as:
51 * $default['pseudoname'] = array(
52 * 'typename1' => 'value',
53 * 'typename2' => 'value'
54 * ....
55 * );
57 * @return array of default values
59 function ldap_getdefaults() {
60 // All the values have to be written in lowercase, even if the
61 // standard LDAP attributes are mixed-case
62 $default['objectclass'] = array(
63 'edir' => 'user',
64 'rfc2307' => 'posixaccount',
65 'rfc2307bis' => 'posixaccount',
66 'samba' => 'sambasamaccount',
67 'ad' => '(samaccounttype=805306368)',
68 'default' => '*'
70 $default['user_attribute'] = array(
71 'edir' => 'cn',
72 'rfc2307' => 'uid',
73 'rfc2307bis' => 'uid',
74 'samba' => 'uid',
75 'ad' => 'cn',
76 'default' => 'cn'
78 $default['suspended_attribute'] = array(
79 'edir' => '',
80 'rfc2307' => '',
81 'rfc2307bis' => '',
82 'samba' => '',
83 'ad' => '',
84 'default' => ''
86 $default['memberattribute'] = array(
87 'edir' => 'member',
88 'rfc2307' => 'member',
89 'rfc2307bis' => 'member',
90 'samba' => 'member',
91 'ad' => 'member',
92 'default' => 'member'
94 $default['memberattribute_isdn'] = array(
95 'edir' => '1',
96 'rfc2307' => '0',
97 'rfc2307bis' => '1',
98 'samba' => '0', // is this right?
99 'ad' => '1',
100 'default' => '0'
102 $default['expireattr'] = array (
103 'edir' => 'passwordexpirationtime',
104 'rfc2307' => 'shadowexpire',
105 'rfc2307bis' => 'shadowexpire',
106 'samba' => '', // No support yet
107 'ad' => 'pwdlastset',
108 'default' => ''
110 return $default;
114 * Checks if user belongs to specific group(s) or is in a subtree.
116 * Returns true if user belongs to a group in grupdns string OR if the
117 * DN of the user is in a subtree of the DN provided as "group"
119 * @param mixed $ldapconnection A valid LDAP connection.
120 * @param string $userid LDAP user id (dn/cn/uid/...) to test membership for.
121 * @param array $group_dns arrary of group dn
122 * @param string $member_attrib the name of the membership attribute.
123 * @return boolean
126 function ldap_isgroupmember($ldapconnection, $userid, $group_dns, $member_attrib) {
127 if (empty($ldapconnection) || empty($userid) || empty($group_dns) || empty($member_attrib)) {
128 return false;
131 $result = false;
132 foreach ($group_dns as $group) {
133 $group = trim($group);
134 if (empty($group)) {
135 continue;
138 // Check cheaply if the user's DN sits in a subtree of the
139 // "group" DN provided. Granted, this isn't a proper LDAP
140 // group, but it's a popular usage.
141 if (stripos(strrev(strtolower($userid)), strrev(strtolower($group))) === 0) {
142 $result = true;
143 break;
146 $search = ldap_read($ldapconnection, $group,
147 '('.$member_attrib.'='.ldap_filter_addslashes($userid).')',
148 array($member_attrib));
150 if (!empty($search) && ldap_count_entries($ldapconnection, $search)) {
151 $info = ldap_get_entries_moodle($ldapconnection, $search);
152 if (count($info) > 0 ) {
153 // User is member of group
154 $result = true;
155 break;
160 return $result;
164 * Tries connect to specified ldap servers. Returns a valid LDAP
165 * connection or false.
167 * @param string $host_url
168 * @param integer $ldap_version either 2 (LDAPv2) or 3 (LDAPv3).
169 * @param string $user_type the configured user type for this connection.
170 * @param string $bind_dn the binding user dn. If an emtpy string, anonymous binding is used.
171 * @param string $bind_pw the password for the binding user. Ignored for anonymous bindings.
172 * @param boolean $opt_deref whether to set LDAP_OPT_DEREF on this connection or not.
173 * @param string &$debuginfo the debugging information in case the connection fails.
174 * @param boolean $start_tls whether to use LDAP with TLS (not to be confused with LDAP+SSL)
175 * @return mixed connection result or false.
177 function ldap_connect_moodle($host_url, $ldap_version, $user_type, $bind_dn, $bind_pw, $opt_deref, &$debuginfo, $start_tls=false) {
178 if (empty($host_url) || empty($ldap_version) || empty($user_type)) {
179 $debuginfo = 'No LDAP Host URL, Version or User Type specified in your LDAP settings';
180 return false;
183 $debuginfo = '';
184 $urls = explode(';', $host_url);
185 foreach ($urls as $server) {
186 $server = trim($server);
187 if (empty($server)) {
188 continue;
191 $connresult = ldap_connect($server); // ldap_connect returns ALWAYS true
193 if (!empty($ldap_version)) {
194 ldap_set_option($connresult, LDAP_OPT_PROTOCOL_VERSION, $ldap_version);
197 // Fix MDL-10921
198 if ($user_type === 'ad') {
199 ldap_set_option($connresult, LDAP_OPT_REFERRALS, 0);
202 if (!empty($opt_deref)) {
203 ldap_set_option($connresult, LDAP_OPT_DEREF, $opt_deref);
206 if ($start_tls && (!ldap_start_tls($connresult))) {
207 $debuginfo .= "Server: '$server', Connection: '$connresult', STARTTLS failed.\n";
208 continue;
211 if (!empty($bind_dn)) {
212 $bindresult = @ldap_bind($connresult, $bind_dn, $bind_pw);
213 } else {
214 // Bind anonymously
215 $bindresult = @ldap_bind($connresult);
218 if ($bindresult) {
219 return $connresult;
222 $debuginfo .= "Server: '$server', Connection: '$connresult', Bind result: '$bindresult'\n";
225 // If any of servers were alive we have already returned connection.
226 return false;
230 * Search specified contexts for username and return the user dn like:
231 * cn=username,ou=suborg,o=org
233 * @param mixed $ldapconnection a valid LDAP connection.
234 * @param mixed $username username (external LDAP encoding, no db slashes).
235 * @param array $contexts contexts to look for the user.
236 * @param string $objectclass objectlass of the user (in LDAP filter syntax).
237 * @param string $search_attrib the attribute use to look for the user.
238 * @param boolean $search_sub whether to search subcontexts or not.
239 * @return mixed the user dn (external LDAP encoding, no db slashes) or false
242 function ldap_find_userdn($ldapconnection, $username, $contexts, $objectclass, $search_attrib, $search_sub) {
243 if (empty($ldapconnection) || empty($username) || empty($contexts) || empty($objectclass) || empty($search_attrib)) {
244 return false;
247 // Default return value
248 $ldap_user_dn = false;
250 // Get all contexts and look for first matching user
251 foreach ($contexts as $context) {
252 $context = trim($context);
253 if (empty($context)) {
254 continue;
257 if ($search_sub) {
258 $ldap_result = @ldap_search($ldapconnection, $context,
259 '(&'.$objectclass.'('.$search_attrib.'='.ldap_filter_addslashes($username).'))',
260 array($search_attrib));
261 } else {
262 $ldap_result = @ldap_list($ldapconnection, $context,
263 '(&'.$objectclass.'('.$search_attrib.'='.ldap_filter_addslashes($username).'))',
264 array($search_attrib));
267 if (!$ldap_result) {
268 continue; // Not found in this context.
271 $entry = ldap_first_entry($ldapconnection, $ldap_result);
272 if ($entry) {
273 $ldap_user_dn = ldap_get_dn($ldapconnection, $entry);
274 break;
278 return $ldap_user_dn;
282 * Normalise the supplied objectclass filter.
284 * This normalisation is a rudimentary attempt to format the objectclass filter correctly.
286 * @param string $objectclass The objectclass to normalise
287 * @param string $default The default objectclass value to use if no objectclass was supplied
288 * @return string The normalised objectclass.
290 function ldap_normalise_objectclass($objectclass, $default = '*') {
291 if (empty($objectclass)) {
292 // Can't send empty filter.
293 $return = sprintf('(objectClass=%s)', $default);
294 } else if (stripos($objectclass, 'objectClass=') === 0) {
295 // Value is 'objectClass=some-string-here', so just add () around the value (filter _must_ have them).
296 $return = sprintf('(%s)', $objectclass);
297 } else if (stripos($objectclass, '(') !== 0) {
298 // Value is 'some-string-not-starting-with-left-parentheses', which is assumed to be the objectClass matching value.
299 // Build a valid filter using the value it.
300 $return = sprintf('(objectClass=%s)', $objectclass);
301 } else {
302 // There is an additional possible value '(some-string-here)', that can be used to specify any valid filter
303 // string, to select subsets of users based on any criteria.
305 // For example, we could select the users whose objectClass is 'user' and have the 'enabledMoodleUser'
306 // attribute, with something like:
308 // (&(objectClass=user)(enabledMoodleUser=1))
310 // In this particular case we don't need to do anything, so leave $this->config->objectclass as is.
311 $return = $objectclass;
314 return $return;
318 * Returns values like ldap_get_entries but is binary compatible and
319 * returns all attributes as array.
321 * @param mixed $ldapconnection A valid LDAP connection
322 * @param mixed $searchresult A search result from ldap_search, ldap_list, etc.
323 * @return array ldap-entries with lower-cased attributes as indexes
325 function ldap_get_entries_moodle($ldapconnection, $searchresult) {
326 if (empty($ldapconnection) || empty($searchresult)) {
327 return array();
330 $i = 0;
331 $result = array();
332 $entry = ldap_first_entry($ldapconnection, $searchresult);
333 if (!$entry) {
334 return array();
336 do {
337 $attributes = array_change_key_case(ldap_get_attributes($ldapconnection, $entry), CASE_LOWER);
338 for ($j = 0; $j < $attributes['count']; $j++) {
339 $values = ldap_get_values_len($ldapconnection, $entry, $attributes[$j]);
340 if (is_array($values)) {
341 $result[$i][$attributes[$j]] = $values;
342 } else {
343 $result[$i][$attributes[$j]] = array($values);
346 $i++;
347 } while ($entry = ldap_next_entry($ldapconnection, $entry));
349 return ($result);
353 * Quote control characters in texts used in LDAP filters - see RFC 4515/2254
355 * @param string filter string to quote
356 * @return string the filter string quoted
358 function ldap_filter_addslashes($text) {
359 $text = str_replace('\\', '\\5c', $text);
360 $text = str_replace(array('*', '(', ')', "\0"),
361 array('\\2a', '\\28', '\\29', '\\00'), $text);
362 return $text;
365 if(!defined('LDAP_DN_SPECIAL_CHARS')) {
366 define('LDAP_DN_SPECIAL_CHARS', 0);
368 if(!defined('LDAP_DN_SPECIAL_CHARS_QUOTED_NUM')) {
369 define('LDAP_DN_SPECIAL_CHARS_QUOTED_NUM', 1);
371 if(!defined('LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA')) {
372 define('LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA', 2);
374 if(!defined('LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA_REGEX')) {
375 define('LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA_REGEX', 3);
379 * The order of the special characters in these arrays _IS IMPORTANT_.
380 * Make sure '\\5C' (and '\\') are the first elements of the arrays.
381 * Otherwise we'll double replace '\' with '\5C' which is Bad(tm)
383 function ldap_get_dn_special_chars() {
384 static $specialchars = null;
386 if ($specialchars !== null) {
387 return $specialchars;
390 $specialchars = array (
391 LDAP_DN_SPECIAL_CHARS => array('\\', ' ', '"', '#', '+', ',', ';', '<', '=', '>', "\0"),
392 LDAP_DN_SPECIAL_CHARS_QUOTED_NUM => array('\\5c','\\20','\\22','\\23','\\2b','\\2c','\\3b','\\3c','\\3d','\\3e','\\00'),
393 LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA => array('\\\\','\\ ', '\\"', '\\#', '\\+', '\\,', '\\;', '\\<', '\\=', '\\>', '\\00'),
395 $alpharegex = implode('|', array_map (function ($expr) { return preg_quote($expr); },
396 $specialchars[LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA]));
397 $specialchars[LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA_REGEX] = $alpharegex;
399 return $specialchars;
403 * Quote control characters in AttributeValue parts of a RelativeDistinguishedName
404 * used in LDAP distinguished names - See RFC 4514/2253
406 * @param string the AttributeValue to quote
407 * @return string the AttributeValue quoted
409 function ldap_addslashes($text) {
410 $special_dn_chars = ldap_get_dn_special_chars();
412 // Use the preferred/universal quotation method: ESC HEX HEX
413 // (i.e., the 'numerically' quoted characters)
414 $text = str_replace ($special_dn_chars[LDAP_DN_SPECIAL_CHARS],
415 $special_dn_chars[LDAP_DN_SPECIAL_CHARS_QUOTED_NUM],
416 $text);
417 return $text;
421 * Unquote control characters in AttributeValue parts of a RelativeDistinguishedName
422 * used in LDAP distinguished names - See RFC 4514/2253
424 * @param string the AttributeValue quoted
425 * @return string the AttributeValue unquoted
427 function ldap_stripslashes($text) {
428 $specialchars = ldap_get_dn_special_chars();
430 // We can't unquote in two steps, as we end up unquoting too much in certain cases. So
431 // we need to build a regexp containing both the 'numerically' and 'alphabetically'
432 // quoted characters. We don't use LDAP_DN_SPECIAL_CHARS_QUOTED_NUM because the
433 // standard allows us to quote any character with this encoding, not just the special
434 // ones.
435 // @TODO: This still misses some special (and rarely used) cases, but we need
436 // a full state machine to handle them.
437 $quoted = '/(\\\\[0-9A-Fa-f]{2}|' . $specialchars[LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA_REGEX] . ')/';
438 $text = preg_replace_callback($quoted,
439 function ($match) use ($specialchars) {
440 if (ctype_xdigit(ltrim($match[1], '\\'))) {
441 return chr(hexdec($match[1]));
442 } else {
443 return str_replace($specialchars[LDAP_DN_SPECIAL_CHARS_QUOTED_ALPHA],
444 $specialchars[LDAP_DN_SPECIAL_CHARS],
445 $match[1]);
448 $text);
450 return $text;
455 * Check if we use LDAP version 3, otherwise the server cannot use them.
457 * @param ldapversion integer The LDAP protocol version we use.
459 * @return boolean true is paged results can be used, false otherwise.
461 function ldap_paged_results_supported($ldapversion) {
462 if ((int)$ldapversion === 3) {
463 return true;
466 return false;