Projet

Général

Profil

Paste
Télécharger (12,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / ldap / ldap_servers / ldap_servers.functions.inc @ 32700c57

1
<?php
2

    
3
/**
4
 * @file
5
 * Collection of functions that don't belong in server object.
6
 */
7

    
8
/**
9
 * Modify an LDAP Entry.
10
 *
11
 * This has been depracated in favor or $ldap_server->modifyLdapEntry($dn, $attributes)
12
 * which handles empty attributes better.
13
 */
14
function ldap_user_modify($dn, $attributes, $ldap_server) {
15
  $result = ldap_modify($ldap_server->connection, $dn, $attributes);
16
  if (!$result) {
17
    $error = "LDAP Server ldap_modify(%dn) in ldap_user_modify() Error Server ID = %sid, LDAP Err No: %ldap_errno LDAP Err Message: %ldap_err2str ";
18
    $tokens = ['%dn' => $dn, '%sid' => $this->sid, '%ldap_errno' => ldap_errno($this->connection), '%ldap_err2str' => ldap_err2str(ldap_errno($this->connection))];
19
    watchdog('ldap_servers', $error, $tokens, WATCHDOG_ERROR);
20
  }
21
  return $result;
22
}
23

    
24
/**
25
 * Modify a password.
26
 */
27
function ldap_password_modify($userdn, $new_password, $ldap_server) {
28

    
29
  $new_password = "\"" . $new_password . "\"";
30
  $len = drupal_strlen($new_password);
31
  $new_pass = NULL;
32
  for ($i = 0; $i < $len; $i++) {
33
    $new_pass .= "{$new_password{$i}}\000";
34
  }
35

    
36
  $status = ldap_mod_replace($ldap_server->connection, $userdn, ['unicodePwd' => $new_pass]);
37
  if (!$status) {
38
    watchdog(
39
      'ldap_servers',
40
      'Error: password_modify() failed to modify ldap password w/ base DN "!dn"',
41
      ['!dn' => $userdn],
42
      WATCHDOG_ERROR
43
    );
44
  }
45

    
46
  return $status;
47
}
48

    
49
/**
50
 * Converts a password to the format that Active Directory supports (for the
51
 * purpose of changing or setting).  Note that AD needs the field to be called
52
 * unicodePwd (as opposed to userPassword)
53
 *
54
 * @param string $password
55
 *   The password that is being formatted for Active Directory unicodePwd field.
56
 *
57
 * @return string
58
 *   $password surrounded with quotes and in UTF-16LE encoding
59
 */
60
function ldap_servers_convert_password_for_active_directory_unicodePwd($password) {
61
  // This function can be called with $attributes['unicodePwd'] as an array.
62
  if (!is_array($password)) {
63
    return mb_convert_encoding("\"{$password}\"", "UTF-16LE");
64
  }
65
  else {
66
    // Presumably there is no use case for there being more than one password in
67
    // the $attributes array, hence it will be at index 0 and we return in kind.
68
    return [mb_convert_encoding("\"{$password[0]}\"", "UTF-16LE")];
69
  }
70
}
71

    
72
/**
73
 * This attempts to find bad dns, but should only be used as warnings
74
 *  as the ldap spec allows for any old character to be escaped and ldap
75
 *  implementations may not follow the spec.
76
 *
77
 *  Http://www.ietf.org/rfc/rfc2253.txt.
78
 */
79
function ldap_baddn($dn, $dn_name) {
80
  $result = [];
81
  $valid_attr_name = '[_a-zA-Z\d\s]';
82
  $valid_attr_values = '[_\-a-zA-Z\d\s]';
83
  $regex = '/^(' . $valid_attr_name . '*\=' . $valid_attr_values . '*[,]{1})*(' . $valid_attr_name . '*\=' . $valid_attr_values . '*){1}$/';
84
  $match = (preg_match($regex, $dn)) ? TRUE : FALSE;
85
  $result['boolean'] = $match;
86
  if (!$match) {
87
    $tokens = ['%dn' => htmlspecialchars($dn), '%dn_name' => $dn_name];
88
    $result['text'] = t('Possible invalid format for:', $tokens)
89
    . '<em>' . $tokens['%dn'] . '</em>.<br/>  ' .
90
    t('The format may be correct for your ldap, but please double check.', $tokens);
91
  }
92
  return $result;
93
}
94

    
95
/**
96
 * This attempts to find bad dns, but should only be used as warningswe
97
 *  as the ldap spec allows for any old character to be escaped and ldap
98
 *  implementations may not follow the spec.
99
 *
100
 *  Http://www.ietf.org/rfc/rfc2253.txt.
101
 */
102
function ldap_badattr($attr, $attr_name) {
103
  $result = [];
104
  $valid_attr_name = '[_a-zA-Z\d\s]';
105
  $regex = '/^(' . $valid_attr_name . '){1,}$/';
106
  $match = (preg_match($regex, $attr)) ? TRUE : FALSE;
107
  $result['boolean'] = $match;
108
  if (!$match) {
109
    $tokens = ['%attr' => htmlspecialchars($attr), '%attr_name' => $attr_name];
110
    $result['text'] = t('Possible invalid format for %attr_name:', $tokens) . ' <code><em>' . $tokens['%attr']
111
      . '</em></code><br/>' . t('The format may be correct for your ldap, but please double check.', $tokens);
112
  }
113
  return $result;
114
}
115

    
116
/**
117
 * Get array of required attributes for an ldap query.
118
 *
119
 * @param string $sid
120
 *   server id or ldap server object being used.
121
 * @param string $direction
122
 *   LDAP_USER_PROV_DIRECTION_* constant.
123
 * @param string $ldap_context
124
 * @param bool $reset
125
 *   cache.
126
 */
127
function ldap_servers_attributes_needed($sid, $ldap_context = 'all', $reset = TRUE) {
128

    
129
  static $attributes;
130
  $sid = is_object($sid) ? $sid->sid : $sid;
131
  $static_cache_id = ($sid) ? $ldap_context . '__' . $sid : $ldap_context;
132
  if (!is_array($attributes)) {
133
    $attributes = [];
134
  }
135
  if (!isset($attributes[$static_cache_id]) || $reset) {
136
    $params = [
137
      'sid' => $sid,
138
      'ldap_context' => $ldap_context,
139
    ];
140
    drupal_alter('ldap_attributes_needed', $attributes[$static_cache_id], $params);
141
  }
142
  $return = $attributes[$static_cache_id];
143

    
144
  return $return;
145
}
146

    
147
/**
148
 * Function to massage (change case, escape, unescape) ldap attribute names
149
 * and values.  The primary purpose of this is to articulate and ensure
150
 * consistency across ldap modules.
151
 *
152
 * @param mixed $value
153
 *   to be massaged.
154
 * @param string $value_type
155
 *   = 'attr_name' or 'attr_value;.
156
 * @param enum $context
157
 *   ...see LDAP_SERVER_MASSAGE_* constants
158
 *
159
 *   .e.g. ldap_server_massage_text($value, 'attr_value',
160
 *   LDAP_SERVER_MASSAGE_QUERY_LDAP)
161
 *
162
 * @return array|mixed|string
163
 */
164
function ldap_server_massage_text($value, $value_type, $context) {
165

    
166
  $scalar = is_scalar($value);
167

    
168
  if ($value_type == 'attr_value') {
169

    
170
    if ($context == LDAP_SERVER_MASSAGE_QUERY_LDAP) {
171
      $value = ldap_pear_escape_filter_value($value);
172
    }
173
    elseif ($context == LDAP_SERVER_MASSAGE_STORE_LDAP) {
174
      $value = ldap_pear_escape_dn_value($value);
175
    }
176

    
177
    switch ($context) {
178

    
179
      case LDAP_SERVER_MASSAGE_DISPLAY:
180
      case LDAP_SERVER_MASSAGE_TOKEN_REPLACE:
181

    
182
      case LDAP_SERVER_MASSAGE_QUERY_LDAP:
183
      case LDAP_SERVER_MASSAGE_QUERY_DB:
184
      case LDAP_SERVER_MASSAGE_QUERY_ARRAY:
185
      case LDAP_SERVER_MASSAGE_QUERY_PROPERTY:
186

    
187
      case LDAP_SERVER_MASSAGE_STORE_LDAP:
188
      case LDAP_SERVER_MASSAGE_STORE_DB:
189
      case LDAP_SERVER_MASSAGE_STORE_ARRAY:
190
      case LDAP_SERVER_MASSAGE_STORE_PROPERTY:
191

    
192
        break;
193

    
194
    }
195
  }
196
  // attr_name.
197
  elseif ($value_type == 'attr_name') {
198
    switch ($context) {
199

    
200
      case LDAP_SERVER_MASSAGE_DISPLAY:
201
        break;
202

    
203
      case LDAP_SERVER_MASSAGE_TOKEN_REPLACE:
204

    
205
      case LDAP_SERVER_MASSAGE_QUERY_LDAP:
206
      case LDAP_SERVER_MASSAGE_QUERY_DB:
207
      case LDAP_SERVER_MASSAGE_QUERY_ARRAY:
208
      case LDAP_SERVER_MASSAGE_QUERY_PROPERTY:
209

    
210
      case LDAP_SERVER_MASSAGE_STORE_LDAP:
211
      case LDAP_SERVER_MASSAGE_STORE_DB:
212
      case LDAP_SERVER_MASSAGE_STORE_ARRAY:
213
      case LDAP_SERVER_MASSAGE_STORE_PROPERTY:
214
        if ($scalar) {
215
          $value = drupal_strtolower($value);
216
        }
217
        elseif (is_array($value)) {
218
          foreach ($value as $i => $val) {
219
            $value[$i] = drupal_strtolower($val);
220
          }
221
        }
222
        else {
223
          // Neither scalar nor array $value.
224
        }
225
        break;
226

    
227
    }
228
  }
229

    
230
  return $value;
231

    
232
}
233

    
234
/**
235
 * From pear net_ldap2-2.0.11.
236
 *
237
 * Escapes the given VALUES according to RFC 2254 so that they can be safely used in LDAP filters.
238
 *
239
 * Any control characters with an ACII code < 32 as well as the characters with special meaning in
240
 * LDAP filters "*", "(", ")", and "\" (the backslash) are converted into the representation of a
241
 * backslash followed by two hex digits representing the hexadecimal value of the character.
242
 *
243
 * @param array $values
244
 *   Array of values to escape.
245
 *
246
 * @static
247
 *
248
 * @return array Array $values, but escaped
249
 */
250
function ldap_pear_escape_filter_value($values = []) {
251
  // Parameter validation.
252
  $is_scalar = is_scalar($values);
253
  if ($is_scalar) {
254
    $values = [$values];
255
  }
256
  if ($values === NULL) {
257
    return NULL;
258
  }
259

    
260
  foreach ($values as $key => $val) {
261
    // Escaping of filter meta characters.
262
    $val = str_replace('\\', '\5c', $val);
263
    $val = str_replace('*', '\2a', $val);
264
    $val = str_replace('(', '\28', $val);
265
    $val = str_replace(')', '\29', $val);
266

    
267
    // ASCII < 32 escaping.
268
    $val = ldap_pear_asc2hex32($val);
269

    
270
    if (NULL === $val) {
271
      $val = '\0';
272
    }  // apply escaped "null" if string is empty
273

    
274
    $values[$key] = $val;
275
  }
276

    
277
  return ($is_scalar) ? $values[0] : $values;
278
}
279

    
280
/**
281
 * Undoes the conversion done by {@link escape_filter_value()}.
282
 *
283
 * Converts any sequences of a backslash followed by two hex digits into the corresponding character.
284
 *
285
 * @param array $values
286
 *   Array of values to escape.
287
 *
288
 * @static
289
 *
290
 * @return array Array $values, but unescaped
291
 */
292
function ldap_pear_unescape_filter_value($values = []) {
293
  // Parameter validation.
294
  $is_scalar = is_scalar($values);
295
  if (!is_array($values)) {
296
    $values = [$values];
297
  }
298

    
299
  foreach ($values as $key => $value) {
300
    // Translate hex code into ascii.
301
    $values[$key] = ldap_pear_hex2asc($value);
302
  }
303

    
304
  return ($is_scalar) ? $values[0] : $values;
305
}
306

    
307
/**
308
 * Escapes a DN value according to RFC 2253.
309
 *
310
 * Escapes the given VALUES according to RFC 2253 so that they can be safely used in LDAP DNs.
311
 * The characters ",", "+", """, "\", "<", ">", ";", "#", "=" with a special meaning in RFC 2252
312
 * are preceeded by ba backslash. Control characters with an ASCII code < 32 are represented as \hexpair.
313
 * Finally all leading and trailing spaces are converted to sequences of \20.
314
 *
315
 * @param array $values
316
 *   An array containing the DN values that should be escaped.
317
 *
318
 * @static
319
 *
320
 * @return array The array $values, but escaped
321
 */
322
function ldap_pear_escape_dn_value($values = []) {
323
  // Parameter validation.
324
  $is_scalar = is_scalar($values);
325

    
326
  if (!is_array($values)) {
327
    $values = [$values];
328
  }
329

    
330
  foreach ($values as $key => $val) {
331
    // Escaping of filter meta characters.
332
    $val = str_replace('\\', '\\\\', $val);
333
    $val = str_replace(',', '\,', $val);
334
    $val = str_replace('+', '\+', $val);
335
    $val = str_replace('"', '\"', $val);
336
    $val = str_replace('<', '\<', $val);
337
    $val = str_replace('>', '\>', $val);
338
    $val = str_replace(';', '\;', $val);
339
    $val = str_replace('#', '\#', $val);
340
    $val = str_replace('=', '\=', $val);
341

    
342
    // ASCII < 32 escaping.
343
    $val = ldap_pear_asc2hex32($val);
344

    
345
    // Convert all leading and trailing spaces to sequences of \20.
346
    if (preg_match('/^(\s*)(.+?)(\s*)$/', $val, $matches)) {
347
      $val = $matches[2];
348
      for ($i = 0; $i < strlen($matches[1]); $i++) {
349
        $val = '\20' . $val;
350
      }
351
      for ($i = 0; $i < strlen($matches[3]); $i++) {
352
        $val = $val . '\20';
353
      }
354
    }
355

    
356
    // Apply escaped "null" if string is empty.
357
    if (NULL === $val) {
358
      $val = '\0';
359
    }
360

    
361
    $values[$key] = $val;
362
  }
363

    
364
  return ($is_scalar) ? $values[0] : $values;
365
}
366

    
367
/**
368
 * Undoes the conversion done by escape_dn_value().
369
 *
370
 * Any escape sequence starting with a baskslash - hexpair or special character -
371
 * will be transformed back to the corresponding character.
372
 *
373
 * @param array $values
374
 *   Array of DN Values.
375
 *
376
 * @return array Same as $values, but unescaped
377
 *
378
 * @static
379
 */
380
function ldap_pear_unescape_dn_value($values = []) {
381
  $is_scalar = is_scalar($values);
382

    
383
  // Parameter validation.
384
  if (!is_array($values)) {
385
    $values = [$values];
386
  }
387

    
388
  foreach ($values as $key => $val) {
389
    // Strip slashes from special chars.
390
    $val = str_replace('\\\\', '\\', $val);
391
    $val = str_replace('\,', ',', $val);
392
    $val = str_replace('\+', '+', $val);
393
    $val = str_replace('\"', '"', $val);
394
    $val = str_replace('\<', '<', $val);
395
    $val = str_replace('\>', '>', $val);
396
    $val = str_replace('\;', ';', $val);
397
    $val = str_replace('\#', '#', $val);
398
    $val = str_replace('\=', '=', $val);
399

    
400
    // Translate hex code into ascii.
401
    $values[$key] = ldap_pear_hex2asc($val);
402
  }
403

    
404
  return ($is_scalar) ? $values[0] : $values;
405
}
406

    
407
/**
408
 * Converts all Hex expressions ("\HEX") to their original ASCII characters.
409
 *
410
 * @param string $string
411
 *   String to convert.
412
 *
413
 * @static
414
 * @author beni@php.net, heavily based on work from DavidSmith@byu.net
415
 *
416
 * @return string
417
 */
418
function ldap_pear_hex2asc($string) {
419

    
420
  if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
421
    $string = preg_replace_callback(
422
    "/\\\([0-9A-Fa-f]{2})/",
423
    function ($m) {
424
      return chr(hexdec($m[1]));
425
    },
426
        $string);
427
  }
428
  else {
429
    $string = preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $string);
430
  }
431

    
432
  return $string;
433
}
434

    
435
/**
436
 * Converts all ASCII chars < 32 to "\HEX".
437
 *
438
 * @param string $string
439
 *   String to convert.
440
 *
441
 * @static
442
 *
443
 * @return string
444
 */
445
function ldap_pear_asc2hex32($string) {
446
  for ($i = 0; $i < strlen($string); $i++) {
447
    $char = substr($string, $i, 1);
448
    if (ord($char) < 32) {
449
      $hex = dechex(ord($char));
450
      if (strlen($hex) == 1) {
451
        $hex = '0' . $hex;
452
      }
453
      $string = str_replace($char, '\\' . $hex, $string);
454
    }
455
  }
456
  return $string;
457
}